Exemple #1
0
        //当前种群进化
        public void Evolve(SelectionType selectionType)
        {
            Population parents = null;

            if (selectionType == SelectionType.Elite)
            {
                parents = EliteSelect(this);
            }
            else if (selectionType == SelectionType.Roulette)
            {
                parents = RouletteSelect(this);
            }
            else if (selectionType == SelectionType.Hybrid)
            {
                parents = HybridSelect(this);
            }

            //crossover 得到子女种群
            if (parents != null)
            {
                var children = Crossover(Chromosomes.Count - parents.Chromosomes.Count);
                Chromosomes.Clear();
                //将选择出来的所有父母染色体,及他们 crossover 得到的子女,作为新的种群
                Chromosomes.AddRange(parents.Chromosomes);
                Chromosomes.AddRange(children.Chromosomes);
            }

            //变异
            Mutate();
        }
Exemple #2
0
        public Object Clone()
        {
            StyleCollection res = new StyleCollection();

            List <StyleObject> allStyles = new List <StyleObject>();

            res.AllStyles = allStyles;

            res.Poles = Poles.Clone() as PoleStyle;
            allStyles.Add(res.Poles);

            res.Tubes = Tubes.Clone() as TubeStyle;
            allStyles.Add(res.Tubes);

            res.Chromosomes = Chromosomes.Clone() as ChromosomeStyle;
            allStyles.Add(res.Chromosomes);

            res.Springs = Springs.Clone() as SpringStyle;
            allStyles.Add(res.Springs);

            res.Cell = Cell.Clone() as CellStyle;
            allStyles.Add(res.Cell);

            return(res);
        }
Exemple #3
0
 private List <Chromosome> GetBestModelsInList(int numberOfBestChromosomes)
 {
     EvaluateModels();
     return(Chromosomes.OrderByDescending(chromosome => chromosome.Metrics.MicroAccuracy)
            .ThenByDescending(chromosome => chromosome.Metrics.MacroAccuracy)
            .Take(numberOfBestChromosomes).ToList());
 }
Exemple #4
0
        public Population(int count, IPopulationGenerator <T> generator, IFitnessEvaluator <T> evaluator)
        {
            if (count <= 0)
            {
                throw new ArgumentException($"{nameof(count)} must be greater than 0. Actual: {count}.");
            }

            if (generator == null)
            {
                throw new System.ArgumentNullException(nameof(generator));
            }

            if (evaluator == null)
            {
                throw new System.ArgumentNullException(nameof(evaluator));
            }

            TargetSize = count;

            // TODO: This really shouldn't be here. We should instead pass the
            // population
            for (var i = 0; i < count; i++)
            {
                var value      = generator.Generate();
                var fitness    = evaluator.ComputeFitness(value);
                var chromosome = new Chromosome <T>(value, fitness);

                Chromosomes.Add(chromosome);
            }
        }
Exemple #5
0
        /// <summary>
        /// Elects the best chromosome.
        /// </summary>
        private void ElectBestChromosome()
        {
            var newBestChromosome = Chromosomes.First();

            ValidateBestChromosome(newBestChromosome);

            BestChromosome = newBestChromosome;
        }
 //The descending sorting method using the merge sort algorithm.
 private static void Sort(Chromosomes.IChromosome[] individuals, double[] f, int begin, int end)
 {
     if (begin == end)
         return;
     int mid = (begin + end) >> 1;
     Sort (individuals, f, begin, mid);
     Sort (individuals, f, mid + 1, end);
     Merge (individuals, f, begin, mid, end);
 }
Exemple #7
0
 public void Add(I interval, string chr, char strand)
 {
     if (!Chromosomes.ContainsKey(chr))
     {
         Chromosomes.Add(chr, new Chromosome <I, S>());
     }
     Chromosomes[chr].Add(interval, strand);
     Statistics.Update(interval);
 }
 //The descending sorting method using the merge sort algorithm.
 private static void Sort(Chromosomes.IChromosome[] individuals, double[] f, int begin, int end)
 {
     if (begin == end)
         return;
     int mid = (begin + end) >> 1;
     RouletteWheelSelectionMethod.Sort(individuals, f, begin, mid);
     RouletteWheelSelectionMethod.Sort(individuals, f, mid + 1, end);
     RouletteWheelSelectionMethod.Merge(individuals, f, begin, mid, end);
 }
Exemple #9
0
        public object Clone()
        {
            Population copy = new Population(Chromosomes.Count());

            for (int i = 0; i < Chromosomes.Count(); ++i)
            {
                copy[i] = (Chromosome)Chromosomes[i].Clone();
            }
            return(copy);
        }
Exemple #10
0
        private void MutateBit(int chromosome, int threshold)
        {
            var random = new Random();
            var dice   = random.Next(0, 1000);

            if (dice <= threshold)
            {
                Chromosomes.Set(chromosome, !Chromosomes.Get(chromosome));
            }
        }
Exemple #11
0
        /// <summary>
        /// Ends the generation.
        /// </summary>
        /// <param name="chromosomesNumber">Chromosomes number to keep on generation.</param>
        public void End(int chromosomesNumber)
        {
            Chromosomes = Chromosomes.OrderByDescending(c => c.Fitness.Value).ToList();

            if (Chromosomes.Count > chromosomesNumber)
            {
                Chromosomes = Chromosomes.Take(chromosomesNumber).ToList();
            }

            ElectBestChromosome();
        }
Exemple #12
0
        /// <summary>
        /// Create a NEAT gnome.
        /// </summary>
        ///
        /// <param name="genomeID">The genome id.</param>
        /// <param name="neurons">The neurons.</param>
        /// <param name="links">The links.</param>
        /// <param name="inputCount_0">The input count.</param>
        /// <param name="outputCount_1">The output count.</param>
        public NEATGenome(long genomeID, Chromosome neurons,
                          Chromosome links, int inputCount_0, int outputCount_1)
        {
            GenomeID          = genomeID;
            linksChromosome   = links;
            neuronsChromosome = neurons;
            AmountToSpawn     = 0;
            AdjustedScore     = 0;
            inputCount        = inputCount_0;
            outputCount       = outputCount_1;

            Chromosomes.Add(neuronsChromosome);
            Chromosomes.Add(linksChromosome);
        }
Exemple #13
0
        /// <summary>
        /// Ends the generation.
        /// </summary>
        /// <param name="chromosomesNumber">Chromosomes number to keep on generation.</param>
        public void End(int chromosomesNumber)
        {
            Chromosomes = Chromosomes
                          .Where(ValidateChromosome)
                          .OrderByDescending(c => c.Fitness.Value)
                          .ToList();

            if (Chromosomes.Count > chromosomesNumber)
            {
                Chromosomes = Chromosomes.Take(chromosomesNumber).ToList();
            }

            BestChromosome = Chromosomes.First();
        }
Exemple #14
0
        /// <summary>
        /// Construct a genome, do not provide links and neurons.
        /// </summary>
        ///
        /// <param name="id">The genome id.</param>
        /// <param name="inputCount_0">The input count.</param>
        /// <param name="outputCount_1">The output count.</param>
        public NEATGenome(long id, int inputCount_0, int outputCount_1)
        {
            GenomeID      = id;
            AdjustedScore = 0;
            inputCount    = inputCount_0;
            outputCount   = outputCount_1;
            AmountToSpawn = 0;
            speciesID     = 0;

            double inputRowSlice = 0.8d / (inputCount_0);

            neuronsChromosome = new Chromosome();
            linksChromosome   = new Chromosome();

            Chromosomes.Add(neuronsChromosome);
            Chromosomes.Add(linksChromosome);

            for (int i = 0; i < inputCount_0; i++)
            {
                neuronsChromosome.Add(new NEATNeuronGene(NEATNeuronType.Input,
                                                         i, 0, 0.1d + i * inputRowSlice));
            }

            neuronsChromosome.Add(new NEATNeuronGene(NEATNeuronType.Bias,
                                                     inputCount_0, 0, 0.9d));

            double outputRowSlice = 1 / (double)(outputCount_1 + 1);

            for (int i_2 = 0; i_2 < outputCount_1; i_2++)
            {
                neuronsChromosome.Add(new NEATNeuronGene(
                                          NEATNeuronType.Output, i_2 + inputCount_0 + 1, 1, (i_2 + 1)
                                          * outputRowSlice));
            }

            for (int i_3 = 0; i_3 < inputCount_0 + 1; i_3++)
            {
                for (int j = 0; j < outputCount_1; j++)
                {
                    linksChromosome.Add(new NEATLinkGene(
                                            ((NEATNeuronGene)neuronsChromosome.Get(i_3)).Id,
                                            ((NEATNeuronGene)Neurons.Get(
                                                 inputCount_0 + j + 1)).Id, true, inputCount_0
                                            + outputCount_1 + 1 + NumGenes,
                                            RangeRandomizer.Randomize(-1, 1), false));
                }
            }
        }
            public Population(int size, Chromosomes.IChromosomeFactory chromosomeFactory, FitnessFunctions.IFitnessFunction fitnessFunction, SelectionMethods.ISelectionMethod selectionMethod)
            {
                this.SetCrossoverProbabilityToDefault();
                this.SetMutationProbabilityToDefault();
                this.SetSelectionRateToDefault();

                this.size = size;
                this.individuals = new Chromosomes.IChromosome[size];
                for (int i = 0; i < size; ++i)
                    this.individuals[i] = chromosomeFactory.GetNewChromosome();
                this.fitnessCalculator = fitnessFunction;
                this.selector = selectionMethod;
                this.fitnesses = new double[this.size];
                for (int i = 0; i < this.size; ++i)
                    this.fitnesses[i] = this.fitnessCalculator.GetFitness(this.individuals[i]);
            }
Exemple #16
0
        private void MutatePopulation()
        {
            int    populationQty = Chromosomes.Count * 5;
            Random rand          = new Random();

            while (Chromosomes.Count < populationQty)
            {
                var firstIndex  = rand.Next(0, Chromosomes.Count);
                var secondIndex = rand.Next(0, Chromosomes.Count);
                Chromosomes.AddRange(CrossoverChromosomes(Chromosomes[firstIndex].GetTrainingGenes(), Chromosomes[secondIndex].GetTrainingGenes()));
            }

            for (int i = 0; i < Chromosomes.Count; i++)
            {
                Chromosomes[i].Mutate();
            }
        }
 //The finding method using the binary search approach.
 private static Chromosomes.IChromosome Find(Chromosomes.IChromosome[] individuals, double[] f, double r)
 {
     int begin = 0;
     int end = individuals.Length - 1;
     int idx = -1;
     while (begin <= end)
     {
         int mid = (begin + end) >> 1;
         if (f[mid] > r)
         {
             idx = mid;
             end = mid - 1;
         }
         else
             begin = mid + 1;
     }
     return individuals[idx];
 }
Exemple #18
0
 /// <summary>
 /// 初始化,设置染色体
 /// </summary>
 private static void Init()
 {
     Chromosomes.Clear();
     for (int i = 0; i < ChromosomeLength; i++)
     {
         int[,] valueLimit = new int[GenesLength, 2];
         for (int ii = 0; ii < GenesLength; ii++)
         {
             valueLimit[ii, 0] = variateInfo[ii].MinValue;
             valueLimit[ii, 1] = variateInfo[ii].MaxValue;
         }
         Chromosome chromosome = new Chromosome {
             ValueLimit = valueLimit,
         };
         chromosome.Genes = IniVariate(chromosome);
         Chromosomes.Add(chromosome);
     }
 }
 //The mergin method.
 private static void Merge(Chromosomes.IChromosome[] individuals, double[] f, int begin, int mid, int end)
 {
     int sz = end - begin + 1;
     double[] tempF = new double[sz];
     Chromosomes.IChromosome[] tempIndividuals = new Chromosomes.IChromosome[sz];
     int i = begin;
     int j = mid + 1;
     int idx = -1;
     while (true)
     {
         ++idx;
         if (f[i] <= f[j])
         {
             tempF[idx] = f[j];
             tempIndividuals[idx] = individuals[j];
             ++j;
         }
         else
         {
             tempF[idx] = f[i];
             tempIndividuals[idx] = individuals[i];
             ++i;
         }
         if ((i == mid + 1) || (j == end + 1))
             break;
     }
     for (; i < mid + 1; ++i)
     {
         ++idx;
         tempF[idx] = f[i];
         tempIndividuals[idx] = individuals[i];
     }
     for (; j < end + 1; ++j)
     {
         ++idx;
         tempF[idx] = f[j];
         tempIndividuals[idx] = individuals[j];
     }
     for (int k = 0; k < sz; ++k)
     {
         f[begin + k] = tempF[k];
         individuals[begin + k] = tempIndividuals[k];
     }
 }
Exemple #20
0
        /// <summary>
        /// Construct a genome by copying another.
        /// </summary>
        ///
        /// <param name="other">The other genome.</param>
        public NEATGenome(NEATGenome other)
        {
            neuronsChromosome = new Chromosome();
            linksChromosome   = new Chromosome();
            GA = other.GA;

            Chromosomes.Add(neuronsChromosome);
            Chromosomes.Add(linksChromosome);

            GenomeID      = other.GenomeID;
            networkDepth  = other.networkDepth;
            Population    = other.Population;
            Score         = other.Score;
            AdjustedScore = other.AdjustedScore;
            AmountToSpawn = other.AmountToSpawn;
            inputCount    = other.inputCount;
            outputCount   = other.outputCount;
            speciesID     = other.speciesID;


            // copy neurons
            foreach (IGene gene  in  other.Neurons.Genes)
            {
                var oldGene = (NEATNeuronGene)gene;
                var newGene = new NEATNeuronGene(
                    oldGene.NeuronType, oldGene.Id,
                    oldGene.SplitY, oldGene.SplitX,
                    oldGene.Recurrent, oldGene.ActivationResponse);
                Neurons.Add(newGene);
            }


            // copy links
            foreach (IGene gene_0  in  other.Links.Genes)
            {
                var oldGene_1 = (NEATLinkGene)gene_0;
                var newGene_2 = new NEATLinkGene(
                    oldGene_1.FromNeuronID, oldGene_1.ToNeuronID,
                    oldGene_1.Enabled, oldGene_1.InnovationId,
                    oldGene_1.Weight, oldGene_1.Recurrent);
                Links.Add(newGene_2);
            }
        }
        /// <summary>
        /// Construct a neural genome.
        /// </summary>
        ///
        /// <param name="network">The network to use.</param>
        public NeuralGenome(BasicNetwork network)
        {
            Organism = network;

            _networkChromosome = new Chromosome();

            // create an array of "double genes"
            int size = network.Structure.CalculateSize();

            for (int i = 0; i < size; i++)
            {
                IGene gene = new DoubleGene();
                _networkChromosome.Genes.Add(gene);
            }

            Chromosomes.Add(_networkChromosome);

            Encode();
        }
        public TSPGenome(GeneticAlgorithm owner, City[] cities)
        {
            var organism = new int[cities.Length];
            var taken    = new bool[cities.Length];

            for (int i = 0; i < organism.Length; i++)
            {
                taken[i] = false;
            }
            for (int i = 0; i < organism.Length - 1; i++)
            {
                int icandidate;
                do
                {
                    icandidate = (int)(ThreadSafeRandom.NextDouble() * organism.Length);
                } while (taken[icandidate]);
                organism[i]       = icandidate;
                taken[icandidate] = true;
                if (i == organism.Length - 2)
                {
                    icandidate = 0;
                    while (taken[icandidate])
                    {
                        icandidate++;
                    }
                    organism[i + 1] = icandidate;
                }
            }

            pathChromosome = new Chromosome();
            Chromosomes.Add(pathChromosome);

            for (int i = 0; i < organism.Length; i++)
            {
                var gene = new IntegerGene();
                gene.Value = organism[i];
                pathChromosome.Genes.Add(gene);
            }
            Organism = organism;

            Encode();
        }
Exemple #23
0
        //随机生成若干染色体
        public void RandomGenerateChromosome()
        {
            var rnd = new Random();

            for (var i = 0; i < ChromosomeQuantity; i++)
            {
                var chromosome = new Chromosome {
                    Population = this
                };
                var valueString = "";

                for (var k = 0; k < ChromosomeLength; k++)
                {
                    valueString += Convert.ToInt32(rnd.Next(0, 2)).ToString();
                }

                chromosome.Value = Convert.ToInt64(valueString, 2);
                Chromosomes.Add(chromosome);
            }
        }
Exemple #24
0
        public Population(int count, IPopulationGenerator <T> generator, IFitnessEvaluator <T> evaluator)
        {
            Contract.Requires <ArgumentOutOfRangeException>(count > 0);
            Contract.Requires <ArgumentNullException>(generator != null);
            Contract.Requires <ArgumentNullException>(evaluator != null);

            TargetSize = count;
            Evaluator  = evaluator;

            // TODO: This really shouldn't be here. We should instead pass the
            // population
            for (var i = 0; i < count; i++)
            {
                var value      = generator.Generate();
                var chromosome = new Chromosome <T>(value);
                chromosome.Fitness = evaluator.ComputeFitness(chromosome.Genes);

                Chromosomes.Add(chromosome);
            }
        }
        public void NextGeneration(ISelection selectionScheme)
        {
            var selected = selectionScheme.Select(Chromosomes, 5).OrderByDescending(s => s.Cost).ToList();

            Chromosomes.Remove(selected[0]);
            Chromosomes.Remove(selected[1]);

            // fill the remaining empty space with children generated from selected chromosomes
            Chromosome parent1 = selected[3];
            Chromosome parent2 = selected[4];

            Chromosome child1 = OrderedCrossover.MakeChild(parent1, parent2);
            Chromosome child2 = OrderedCrossover.MakeChild(parent2, parent1);

            if (ThreadSafeRandom.CurrentThreadRandom.Next(100) < 3)
            {
                child1.Mutate();
            }
            if (ThreadSafeRandom.CurrentThreadRandom.Next(100) < 3)
            {
                child2.Mutate();
            }

            Chromosomes.Add(child1);
            Chromosomes.Add(child2);

            double currentTour = Chromosomes.Where(c => c.Cost > 0).Min(c => c.Cost);

            if (currentTour < BestTour)
            {
                BestTour = currentTour;
                Console.WriteLine("Generation " + currentGeneration + " Best: " + BestTour);
            }

            currentGeneration++;
        }
 public Chromosome GetBestSolutionSoFar()
 {
     return(Chromosomes.Aggregate((curMin, x) => (curMin == null || x.RouteLength < curMin.RouteLength ? x : curMin)));
 }
Exemple #27
0
        public State <T> AddChromosome(Chromosome <T> chromosome)
        {
            var newChromosomes = Chromosomes.Add(chromosome).OrderByDescending(c => c.Fitness);

            return(new State <T>(newChromosomes));
        }
Exemple #28
0
 /// <summary>
 /// Elects the best chromosome.
 /// </summary>
 private void ElectBestChromosome()
 {
     BestChromosome = Chromosomes.First();
 }
Exemple #29
0
 private Chromosome GetBestModelInList()
 {
     EvaluateModels();
     return(Chromosomes.OrderByDescending(chromosome => chromosome.Metrics.MicroAccuracy).ThenByDescending(chromosome => chromosome.Metrics.MicroAccuracy).ToList().First());
 }
Exemple #30
0
 public void JoinPopulation(Population p)
 {
     Chromosomes.AddRange(p.Chromosomes);
 }
Exemple #31
0
 public void AddChromosome(T chromosome)
 {
     Chromosomes.Add(chromosome);
 }
Exemple #32
0
 public void RemoveChromosome(T chromosome)
 {
     Chromosomes.Remove(chromosome);
 }
Exemple #33
0
 // TODO -> This should not be like this
 public void SortByFitness()
 {
     Chromosomes = Chromosomes.OrderByDescending(c => c.Fitness).ToArray();
 }
Exemple #34
0
        /// <summary>
        /// Trains and evaluates a genetic algorithm with the specified parameters.
        /// </summary>
        /// <param name="data">The data to be used for training.</param>
        /// <param name="solution">The reference to where the solution will be stored.</param>
        /// <param name="bestChromosome">The best chromosome.</param>
        /// <param name="error">The reference where error rate will be stored.</param>
        /// <param name="predictions">The reference to where the predictions will be stored.</param>
        /// <param name="iterations">The number of iterations to perform.</param>
        /// <param name="population">The size of the population.</param>
        /// <param name="inputCount">The number of inputs.</param>
        /// <param name="shuffle">Value indicating whether to shuffle the chromosomes on each epoch.</param>
        /// <param name="constants">The constant inputs.</param>
        /// <param name="geneType">Type of the gene functions.</param>
        /// <param name="chromosomeType">Type of the chromosome.</param>
        /// <param name="selectionType">Type of the chromosome selection.</param>
        /// <param name="cancelToken">The cancellation token for the async operation.</param>
        /// <param name="progressCallback">The progress callback: current iteration.</param>
        /// <returns>
        ///   <c>true</c> if the training and evaluation was successful, <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentException">Array should be size of data minus number of inputs.</exception>
        public static bool TrainAndEval(double[] data, ref double[] solution, ref string bestChromosome, ref double error, ref double[] predictions, int iterations, int population, int inputCount, bool shuffle, double[] constants, GeneFunctions geneType, Chromosomes chromosomeType, Selections selectionType, CancellationToken cancelToken, Action <int> progressCallback = null)
        {
            IGPGene gene;

            switch (geneType)
            {
            case GeneFunctions.Simple:
                gene = new SimpleGeneFunction(inputCount + constants.Length);
                break;

            case GeneFunctions.Extended:
                gene = new ExtendedGeneFunction(inputCount + constants.Length);
                break;

            default: return(false);
            }

            IChromosome chromosome;

            switch (chromosomeType)
            {
            case Chromosomes.GPT:
                chromosome = new GPTreeChromosome(gene);
                break;

            case Chromosomes.GEP:
                chromosome = new GEPChromosome(gene, 20);
                break;

            default: return(false);
            }

            ISelectionMethod selection;

            switch (selectionType)
            {
            case Selections.Elite:
                selection = new EliteSelection();
                break;

            case Selections.Rank:
                selection = new RankSelection();
                break;

            case Selections.Roulette:
                selection = new RouletteWheelSelection();
                break;

            default: return(false);
            }

            cancelToken.ThrowIfCancellationRequested();

            var ga = new Population(
                population,
                chromosome,
                new TimeSeriesPredictionFitness(data, inputCount, 0, constants),
                selection
                )
            {
                AutoShuffling = shuffle
            };

            if (solution.Length != data.Length - inputCount)
            {
                throw new ArgumentException("Array should be the size of data minus number of inputs.", nameof(solution));
            }

            var input = new double[inputCount + constants.Length];

            for (var j = 0; j < data.Length - inputCount; j++)
            {
                solution[j] = j + inputCount;
            }

            Array.Copy(constants, 0, input, inputCount, constants.Length);

            for (var i = 0; i < iterations; i++)
            {
                ga.RunEpoch();

                progressCallback?.Invoke(i);

                cancelToken.ThrowIfCancellationRequested();
            }

            error          = 0.0;
            bestChromosome = ga.BestChromosome.ToString();

            for (int j = 0, n = data.Length - inputCount; j < n; j++)
            {
                for (int k = 0, b = j + inputCount - 1; k < inputCount; k++)
                {
                    input[k] = data[b - k];
                }

                solution[j] = PolishExpression.Evaluate(bestChromosome, input);

                error += Math.Abs((solution[j] - data[inputCount + j]) / data[inputCount + j]);

                cancelToken.ThrowIfCancellationRequested();
            }

            error = error / (data.Length - inputCount) * 100;

            if (predictions.Length != 0)
            {
                Array.Copy(solution, solution.Length - inputCount, predictions, 0, inputCount);

                for (var i = inputCount; i < predictions.Length; i++)
                {
                    for (int j = 0; j < inputCount; j++)
                    {
                        input[j] = predictions[(i - inputCount) + j];
                    }

                    predictions[i] = PolishExpression.Evaluate(bestChromosome, input);

                    cancelToken.ThrowIfCancellationRequested();
                }
            }

            return(true);
        }
Exemple #35
0
 public IEnumerator <T> GetEnumerator()
 {
     return(Chromosomes.GetEnumerator());
 }