Esempio n. 1
0
        internal void CalculatePopulation()
        {
            // traženje najboljih hromosoma
            fitnessMax = 0;
            fitnessSum = 0;

            if (bestChromosome == null)
            {
                bestChromosome = chromosomes[0];
            }

            for (int i = 0; i < gpParameters.popSize; i++)
            {
                float fitness = (chromosomes[i]).fitness;
                // sum calc
                fitnessSum += fitness;

                // cal the best chromosome
                if (fitness > fitnessMax)
                {
                    fitnessMax     = fitness;
                    bestChromosome = chromosomes[i];
                }
            }
            fitnessAvg = fitnessSum / gpParameters.popSize;
        }
Esempio n. 2
0
        private void FUSSSelection(int size)
        {
            // new chromosomes, initially empty
            List <GPChromosome> newPopulation = new List <GPChromosome>();
            //Maximum fitness
            double fitnessMax = chromosomes.Max(x => x.fitness);
            double rnd;
            double dif;
            int    selIndex = 0;

            for (int j = 0; j < size; j++)
            {
                rnd      = Globals.radn.NextDouble(0, fitnessMax);
                dif      = Math.Abs(chromosomes[0].fitness - rnd);
                selIndex = 0;
                for (int i = 1; i < chromosomes.Count; i++)
                {
                    double curDif = Math.Abs(chromosomes[i].fitness - rnd);
                    if (dif > curDif)
                    {
                        dif      = curDif;
                        selIndex = i;
                    }
                }
                newPopulation.Add(chromosomes[selIndex].Clone());
            }

            // survived chromosomes
            chromosomes.AddRange(newPopulation);

            // old population is goint to die
            GPChromosome.DestroyChromosomes(ref chromosomes);
        }
Esempio n. 3
0
        private void TournamentSelection(int size)
        {
            // velicinaPopulacije of current chromosomes
            int currentSize           = chromosomes.Count;
            List <GPChromosome> tourn = new List <GPChromosome>((int)gpParameters.SelParam1);
            // new chromosomes, initially empty
            List <GPChromosome> newPopulation = new List <GPChromosome>();

            for (int j = 0; j < size; j++)
            {
                currentSize = chromosomes.Count;
                for (int i = 0; i < gpParameters.SelParam1 && i < currentSize; i++)
                {
                    int ind = Globals.radn.Next(currentSize);
                    tourn.Add(chromosomes[ind]);
                }

                tourn.Sort();
                newPopulation.Add(tourn[0].Clone());
                chromosomes.Remove(tourn[0]);
                tourn.Clear();
            }

            // survived chromosomes
            chromosomes.AddRange(newPopulation);

            // old population is goint to die
            GPChromosome.DestroyChromosomes(ref chromosomes);
        }
Esempio n. 4
0
        /// <summary>
        /// HalfAndHalf method of initialization,all chromosomes is grouped in equal number of chromosome
        /// and generates with the same levels.
        /// </summary>
        /// <param name="size"></param>
        private void HalfHalfInitialization(int size)
        {
            //The max init depth of tree
            int n = GetMaxInitializeLevel();

            //Make equal group for each level
            int br = (size / n);

            //Create equal number of choromosomes for each level
            for (int i = 2; i <= n; i++)
            {
                if (i == n)//at the end take the rest
                {
                    br = (size - ((i - 2) * br));
                }
                //Chromosome generation with exact level
                for (int j = 0; j < br; j++)
                {
                    // create new chromosome
                    GPChromosome c = GenerateChromosome(i);

                    // add to chromosomes
                    chromosomes.Add(c);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Randomly generate chromosome with exact number of levels
        /// </summary>
        /// <param name="levels">Tree leveles</param>
        /// <returns></returns>
        public GPChromosome GenerateChromosome(int levels)
        {
            GPChromosome ch = GPChromosome.NewChromosome();

            ch.expressionTree = GenerateTreeStructure(levels);
            return(ch);
        }
Esempio n. 6
0
        public static HashSet <IGPChromosome> GenerateAllCombinations(SocialGPChromosome socialChromosome)
        {
            var allSubCombinations = new GPChromosome[socialChromosome.NumAgents][];

            for (var i = 0; i < socialChromosome.NumAgents; i++)
            {
                //adds sub-element and all its combinations to list
                var gpChromosome  = (GPChromosome)socialChromosome[i];
                var allChromCombs = Learning.IMRL.EC.Util.GenerateAllCombinations(gpChromosome).ToList();
                allChromCombs.Add(gpChromosome);
                var allChromCombsArray = new GPChromosome[allChromCombs.Count];
                for (var j = 0; j < allChromCombs.Count; j++)
                {
                    allChromCombsArray[j] = (GPChromosome)allChromCombs[j];
                }
                allSubCombinations[i] = allChromCombsArray;
            }

            //makes combinations with all chromosomes
            var chromCombs      = allSubCombinations.AllCombinations();
            var allCombinations = new HashSet <IGPChromosome>();

            foreach (var chromComb in chromCombs)
            {
                allCombinations.Add(new SocialGPChromosome(chromComb));
            }

            return(allCombinations);
        }
Esempio n. 7
0
        private void SkrgicSelection(int size)
        {
            // new chromosomes, initially empty
            List <GPChromosome> newPopulation = new List <GPChromosome>();
            //  double k = 0.2; //additionalParameter;
            double fitnessMax = chromosomes.Max(x => x.fitness) * (1.0 + gpParameters.SelParam1);

            for (int i = 0; i < size; i++)
            {
                //Slucajni index iz populacije
                int randomIndex = Globals.radn.Next(0, chromosomes.Count);
                //Slucajni broj izmedju 0-maxFitnes ukljucujuci i maxFitness koje je prethodno vec izracunat kod evaluacije hromosoma
                double randomFitness = Globals.radn.NextDouble(0, fitnessMax /*, true include MaxValue*/);

                while (true)
                {
                    //Akoje slucajno generirani broj manji ili jednak fitnesu slucajnog hromosoma selektuj hromosom
                    if (randomFitness <= chromosomes[randomIndex].fitness * (1.0 + gpParameters.SelParam1 / fitnessMax))
                    {
                        newPopulation.Add(chromosomes[randomIndex].Clone());
                        break;
                    }

                    randomIndex   = Globals.radn.Next(0, chromosomes.Count);
                    randomFitness = Globals.radn.NextDouble(0, fitnessMax /*, true include MaxValue*/);
                }
            }

            // survived chromosomes
            chromosomes.AddRange(newPopulation);

            // old population is goint to die
            GPChromosome.DestroyChromosomes(ref chromosomes);
        }
Esempio n. 8
0
        /// <summary>
        /// Randomly generate chromosome with exact number of levels
        /// </summary>
        /// <param name="levels">Tree leveles</param>
        /// <returns></returns>
        public GPChromosome GenerateGPChromosome(int levels)
        {
            GPChromosome ch = GPChromosome.NewChromosome();

            ch.Generate(levels);
            return(ch);
        }
Esempio n. 9
0
        /// <summary>
        /// Calculates model/prediction using best chromosome. Also it denormalized valuse if they  were normalized
        /// </summary>
        /// <param name="ch"> bestchromosomes</param>
        /// <param name="testData"></param>
        /// <returns></returns>
        protected virtual double[][] CalculateModel(GPChromosome ch, bool btrainingData = true)
        {
            if (ch != null)
            {
                var pts = GPdotNET.Core.Globals.CalculateGPModel(ch.expressionTree, btrainingData);
                if (pts == null)
                {
                    return(null);
                }

                //calculate output
                var model = new double[1][];
                var outv  = new double[1][];
                if (m_Experiment != null)
                {
                    outv[0]  = new double[1];
                    model[0] = new double[pts.Length];
                    for (int i = 0; i < pts.Length; i++)
                    {
                        outv[0][0] = pts[i];
                        var outv1 = m_Experiment.GetDenormalizedOutputRow(outv[0]);
                        model[0][i] = outv1[0];
                    }
                }
                else
                {
                    model[0] = pts;//old version
                }
                return(model);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Before we start GP prepare all neccessery information
        /// </summary>
        /// <param name="termSet"></param>
        /// <param name="funSet"></param>
        /// <param name="gpParams"></param>
        public void PrepareAlgorithm(GPTerminalSet termSet, GPFunctionSet funSet, GPParameters gpParams = null)
        {
            m_IterationCounter = 0;
            if (Population == null)
            {
                Population = new CHPopulation();
            }

            Population.InitPopulation(termSet, funSet, gpParams);
            Population.CalculatePopulation();

            IsAlgorthmPrepared = true;

            StopIteration = false;


            //calculate model and prediction
            GPChromosome ch = Population.bestChromosome as GPChromosome;

            double[][] model      = CalculateModel(ch);
            double[][] prediction = CalculateModel(ch, false);

            //Report the evolution has been started
            if (ReportEvolution != null)
            {
                ReportEvolution(this,
                                new ProgressIndicatorEventArgs()
                {
                    ReportType       = ProgramState.Started,
                    AverageFitness   = Population.fitnessAvg,
                    BestChromosome   = Population.bestChromosome,
                    CurrentIteration = 0, LearnOutput = model, PredicOutput = prediction
                });
            }
        }
Esempio n. 11
0
        private void UniversalStohasticSelection(int size)
        {
            // new chromosomes, initially empty
            List <GPChromosome> newPopulation = new List <GPChromosome>();
            //chromosomes.Sort();

            int   currentSize = chromosomes.Count();
            float fitnessSum  = chromosomes.Sum(c => c.fitness);

            // get random distance value
            float randDist   = (float)Globals.radn.NextDouble(0, 1.0 / (double)size);
            float partFitnes = 0;

            for (int j = 0; j < size; j++)
            {
                partFitnes = 0;
                for (int i = 0; i < chromosomes.Count; i++)
                {
                    partFitnes += chromosomes[i].fitness / fitnessSum;

                    if (randDist <= partFitnes)
                    {
                        newPopulation.Add(chromosomes[i].Clone());
                        break;
                    }
                }
                randDist += 1.0F / (float)size;
            }

            // survived chromosomes
            chromosomes.AddRange(newPopulation);

            // old population is goint to die
            GPChromosome.DestroyChromosomes(ref chromosomes);
        }
Esempio n. 12
0
        /// <summary>
        /// Fitness šproportionate selection.
        /// </summary>
        /// <param name="size"></param>
        private void FitnessProportionateSelection(int size)
        {
            // new chromosomes, initially empty
            List <GPChromosome> newPopulation = new List <GPChromosome>();


            int    currentSize  = chromosomes.Count;
            double sumOfFitness = 0;

            //calculate sum of fitness
            for (int i = 0; i < currentSize; i++)
            {
                sumOfFitness += chromosomes[i].fitness;
            }


            // create wheel ranges
            double[] rangeMax = new double[currentSize];
            double   s        = 0;

            for (int i = 0; i < currentSize; i++)
            {
                // cumulative normalized fitness
                s          += (chromosomes[i].fitness / sumOfFitness);
                rangeMax[i] = s;
            }

            // select chromosomes from old chromosomes to the new chromosomes
            for (int j = 0; j < size; j++)
            {
                // get wheel value
                double wheelValue = Globals.radn.NextDouble();
                // find the chromosome for the wheel value
                for (int i = 0; i < currentSize; i++)
                {
                    //double wheelValue = rand.NextDouble();
                    if (wheelValue <= rangeMax[i] && chromosomes[i].fitness != -1)
                    {
                        // add the chromosome to the new population
                        var ch = chromosomes[i].Clone();
                        newPopulation.Add(ch);
                        chromosomes[i].fitness = -1;

                        break;
                    }
                }
            }

            // survived chromosomes
            chromosomes.AddRange(newPopulation);

            // old population is goint to die
            GPChromosome.DestroyChromosomes(ref chromosomes);
        }
Esempio n. 13
0
        public override void Train(IForecastingDataSets datasets)
        {
            OnStartRunning(new ComponentRunEventArgs(datasets));
            NumberOfVariables = datasets.InputVectorLength;
            NumberOfSamples   = datasets.Length;
            EnvolutionStep    = 0;
            if (functionSet == null)
            {
                functionSet = new GPFunctionSet();
            }
            Initialize();
            GenerateFunction();
            double [] gpConstraints = GenerateConstants(mGPModelParameter.ConstantsIntervalFrom, mGPModelParameter.ConstantsIntervalTo, mGPModelParameter.ConstantsNumber);
            GenerateTerminals(datasets, gpConstraints);

            if (population == null)
            {
                EnvolutionStep = 1;
                population     = new GPPopulation(mGPModelParameter.PopulationSize, terminalSet, functionSet, parameters, mGPModelParameter.MultipleCore);
            }
            GPBestHromosome = population.bestChromosome;

            while (ProveEnvolution(EnvolutionStep, mGPModelParameter.EnvolveConditionValue, mGPModelParameter.EnvolveIndicator))
            {
                population.StartEvolution();
                OnRunningEpoch(new ComponentRunEpochEventArgs(EnvolutionStep));
                EnvolutionStep++;
            }

            int        indexOutput = terminalSet.NumConstants + terminalSet.NumVariables - 1;
            List <int> lst         = new List <int>();

            FunctionTree.ToListExpression(lst, GPBestHromosome.Root);
            double y = 0;

            datasets.ForecastedData = new double[datasets.Length][];
            for (int i = 0; i < terminalSet.RowCount; i++)
            {
                // evalue the function
                y = functionSet.Evaluate(lst, terminalSet, i);

                // check for correct numeric value
                if (double.IsNaN(y) || double.IsInfinity(y))
                {
                    y = 0;
                }
                datasets.ForecastedData[i]    = new double[1];
                datasets.ForecastedData[i][0] = y;
            }
            OnFinishRunning(new ComponentRunEventArgs(datasets)
            {
                State = functionSet.DecodeExpression(lst, terminalSet)
            });
        }
 public SocialGPChromosome(uint numAgents, GPChromosome baseChromosome)
 {
     this.NumAgents    = numAgents;
     this._chromosomes = new GPChromosome[numAgents];
     for (var i = 0; i < numAgents; i++)
     {
         this._chromosomes[i] = (GPChromosome)baseChromosome.Clone();
     }
     this.Population = baseChromosome.Population;
     this.Init();
 }
        public override IECChromosome CreateBaseChromosome()
        {
            var gpChromosome = new GPChromosome(
                new FlexibleGPGene(this.AllowedFunctions.ToList(), (int)(this.Constants.Length + this.NumBaseVariables)));

            return(this.SameAgentParameters
                ? (IECChromosome) new SocialCommonGPChromosome(this.NumAgents, gpChromosome)
                : new SocialGPChromosome(this.NumAgents, gpChromosome)
            {
                SymmetryFactor = this.SymmetryFactor
            });
        }
Esempio n. 16
0
        /// <summary>
        /// Full initialization method, all choromosomes have the same level.
        /// </summary>
        /// <param name="size"></param>
        private void FullInitialization(int size)
        {
            //Chromosome generation with exact level
            for (int i = 0; i < size; i++)
            {
                // generate new chromosome
                GPChromosome c = GenerateChromosome(GetMaxInitializeLevel());

                //add to poppulation
                chromosomes.Add(c);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Main function for running GP
        /// </summary>
        /// <param name="terValue">termination value</param>
        /// <param name="termType">type of termination</param>
        public void StartEvolution(float terValue, int termType)
        {
            if (!IsAlgorthmPrepared)
            {
                throw new Exception("Algorithm is not prepared!");
            }

            if (Population == null)
            {
                throw new Exception("Population is null!");
            }

            //before we start set variable to initial value
            StopIteration = false;


            while (CanContinue(terValue, termType))
            {
                //increase evolution
                m_IterationCounter++;

                Population.Crossover();

                Population.Mutate();

                Population.EvaluatePopulation();

                Population.Selection();

                Population.CalculatePopulation();

                //calculate model and prediction
                GPChromosome ch         = Population.bestChromosome as GPChromosome;
                double[][]   model      = CalculateModel(ch);
                double[][]   prediction = CalculateModel(ch, false);


                if (ReportEvolution != null)
                {
                    ReportEvolution(this,
                                    new ProgressIndicatorEventArgs()
                    {
                        ReportType       = CanContinue(terValue, termType) ? ProgramState.Running : ProgramState.Finished,
                        AverageFitness   = Population.fitnessAvg,
                        BestChromosome   = Population.bestChromosome,
                        CurrentIteration = m_IterationCounter,
                        LearnOutput      = model,
                        PredicOutput     = prediction
                    });
                }
            }
        }
Esempio n. 18
0
        public static uint GetDepth(GPChromosome chromosome)
        {
            var nodeStack = GetNodeStack(chromosome.ToString());

            if ((nodeStack == null) || (nodeStack.Count == 0))
            {
                return(0);
            }
            var rootNode = nodeStack.Pop();

            GenerateNodeStructure(rootNode, nodeStack);

            return(GetDepth(rootNode, 0));
        }
Esempio n. 19
0
        private void ApplyCrossover(GPChromosome ch1, GPChromosome ch2)
        {
            //Get random numbers between 0 and maximum index
            int index1 = GetRandomNode(ch1.expressionTree.NodeCount());
            int index2 = GetRandomNode(ch2.expressionTree.NodeCount());

            //Exchange the geene material
            Crossover(ch1.expressionTree, ch2.expressionTree, index1, index2);


            //if some tree exceed the levels trim it
            ch1.Trim(GetMaxOperationLevel());
            ch2.Trim(GetMaxOperationLevel());
        }
Esempio n. 20
0
        public static HashSet <IGPChromosome> GenerateAllCombinations(GPChromosome chromosome)
        {
            var nodeStack = GetNodeStack(chromosome.ToString());

            if ((nodeStack == null) || (nodeStack.Count == 0))
            {
                return(new HashSet <IGPChromosome>());
            }

            var rootNode = nodeStack.Pop();

            GenerateNodeStructure(rootNode, nodeStack);

            return(GenerateAllCombinations(rootNode));
        }
Esempio n. 21
0
        private void RankSelection(int size)
        {
            // new chromosomes, initially empty
            List <GPChromosome> newPopulation = new List <GPChromosome>();
            // velicinaPopulacije of current chromosomes
            int currentSize = chromosomes.Count;

            // sort current chromosomes
            //chromosomes.Sort();

            // calculate amount of ranges in the wheel
            double ranges = currentSize * (currentSize + 1) / 2;

            // create wheel ranges
            double[] rangeMax = new double[currentSize];
            double   s        = 0;

            for (int i = 0, n = currentSize; i < currentSize; i++, n--)
            {
                s          += ((double)n / ranges);
                rangeMax[i] = s;
            }

            // select chromosomes from old chromosomes to the new chromosomes
            for (int j = 0; j < size; j++)
            {
                // get wheel value
                double wheelValue = Globals.radn.NextDouble();
                // find the chromosome for the wheel value
                for (int i = 0; i < currentSize; i++)
                {
                    // get wheel value
                    if (wheelValue <= rangeMax[i])
                    {
                        // add the chromosome to the new chromosomes
                        newPopulation.Add(chromosomes[i].Clone());
                        break;
                    }
                    //Debug.Assert(false);
                }
            }

            // survived chromosomes
            chromosomes.AddRange(newPopulation);

            // old population is goint to die
            GPChromosome.DestroyChromosomes(ref chromosomes);
        }
Esempio n. 22
0
        /// <summary>
        /// Every chromosome have randomly generated  levels between 2 and maximumValue.
        /// </summary>
        /// <param name="size"></param>
        private void GrowInitialization(int size)
        {
            int levels = 2;

            //Chromosome generation with exact level
            for (int i = 0; i < size; i++)
            {
                //Randomly choose which level chromose will have
                levels = Globals.radn.Next(2, GetMaxInitializeLevel() + 1);

                // generate new chromosome
                GPChromosome c = GenerateChromosome(levels);

                // pridruzivanje populaciji
                chromosomes.Add(c);
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Reports about current evolution. See other reposrt methods
        /// </summary>
        /// <param name="currentEvolution"></param>
        /// <param name="averageFitness"></param>
        /// <param name="ch"></param>
        /// <param name="repType"></param>
        public void ReportProgress(int currentEvolution, float averageFitness, IChromosome ch, int repType)
        {
            if (ch == null)
            {
                return;
            }

            if (prevFitness < ch.Fitness)
            {
                prevFitness = ch.Fitness;
                if (ch is GPChromosome)
                {
                    _gpModel = (GPdotNET.Engine.GPChromosome)ch;

                    if (Globals.functions != null)
                    {
                        enooptMatematickiModel.Text = Globals.functions.DecodeExpression(_gpModel.expressionTree);
                    }

                    treeCtrlDrawer1.DrawTreeExpression(_gpModel.expressionTree, Globals.GetGPNodeStringRep);
                }
            }
        }
        public IChromosome CreateNew()
        {
            var newChromosomes = new GPChromosome[this.NumAgents];

            //gets symmetry prob
            var symmetricProb = Rand.NextDouble();

            //creates first (base) individual chromosome
            newChromosomes[0] = (GPChromosome)this._chromosomes[0].CreateNew();

            //creates new chromosomes or copies base one based on symmetry prob.
            for (var i = 1; i < this.NumAgents; i++)
            {
                newChromosomes[i] = (GPChromosome)(symmetricProb <= this.SymmetryFactor
                    ? newChromosomes[0].Clone()
                    : this._chromosomes[i].CreateNew());
            }

            return(new SocialGPChromosome(newChromosomes)
            {
                Population = this.Population,
                SymmetryFactor = this.SymmetryFactor
            });
        }
Esempio n. 25
0
 public double[][] CalculateTestModel(GPChromosome ch)
 {
     return(CalculateModel(ch, false));
 }
Esempio n. 26
0
 public double[][] CalculateTrainModel(GPChromosome ch)
 {
     return(CalculateModel(ch, true));
 }
 public SocialCommonGPChromosome(uint numAgents, GPChromosome commomTestParameters)
     : base(commomTestParameters.BaseChromosome ?? commomTestParameters, commomTestParameters.Population)
 {
     this.NumAgents = numAgents;
 }
Esempio n. 28
0
 /// <summary>
 /// Resets previous solution
 /// </summary>
 public void ResetSolution()
 {
     prevFitness = -1;
     _gpModel    = null;
 }
Esempio n. 29
0
 public void EvaluateChromosome(GPChromosome c)
 {
     c.fitness = fitnessFunction.Evaluate(c.expressionTree, functionSet);
 }
Esempio n. 30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="lines"></param>
        /// <param name="factory"></param>
        /// <param name="curLine"></param>
        /// <param name="typeChromosome"></param>
        /// <returns></returns>
        private int MainPopulationFromString(string[] lines, GPFactory factory, int curLine)
        {
            curLine++;
            //Line 8: populationSize; maxFitness; BestChromosome
            if (lines.Length <= curLine)
            {
                //MessageBox.Show("Fie is corrupt!");
                return(-1);
            }
            var str = lines[curLine].Split(';');


            if (lines[curLine] == "-" || lines[curLine] == "-\r")
            {
                return(curLine += 2);
            }

            if (_GPModel == GPModelType.TSP)
            {
                PrepareTSP(false);
            }
            else if (_GPModel == GPModelType.AP)
            {
                PrepareALOC(false);
            }
            else if (_GPModel == GPModelType.TP)
            {
                PrepareTrans(false);
            }
            else
            {
                PrepareGP(false);
            }


            int popSize = 0;

            if (!int.TryParse(str[0], out popSize))
            {
                popSize = 0;
            }

            List <IChromosome> chromosomes = new List <IChromosome>();

            for (int i = 0; i < popSize; i++)
            {
                IChromosome ch = null;
                if (_GPModel == GPModelType.TSP || _GPModel == GPModelType.AP)
                {
                    ch = GAVChromosome.CreateFromString(lines[i + curLine + 1]);
                }
                else if (_GPModel == GPModelType.TP)
                {
                    ch = GAMChromosome.CreateFromString(lines[i + curLine + 1]);
                }
                else
                {
                    ch = GPChromosome.CreateFromString(lines[i + curLine + 1]);
                }
                chromosomes.Add(ch);
            }

            factory.SetChromosomes(chromosomes);

            factory.CalculatePopulation();
            return(popSize + 7);
        }