public void TestCalcFitness_NoCharsInCorrectPositions()
 {
     CodeBreaker cb = new CodeBreaker("ABCD", new Random());
     Chromosome c = new Chromosome("DCBA");
     Utility.CalcFitness(c, "ABCD");
     Assert.AreEqual(0, c.Fitness);
 }
 public void TestCalcFitness_NoCommonChars()
 {
     CodeBreaker cb = new CodeBreaker("ABCD", new Random());
     Chromosome c = new Chromosome("WXYZ");
     Utility.CalcFitness(c, "ABCD");
     Assert.AreEqual(0, c.Fitness);
 }
 public void TestCalcFitness_AllCorrect()
 {
     CodeBreaker cb = new CodeBreaker("ABCD", new Random());
     Chromosome c = new Chromosome("ABCD");
     Utility.CalcFitness(c, "ABCD");
     Assert.AreEqual(4, c.Fitness);
 }
 public void TestCalcFitness_OneCharInCorrectPosition()
 {
     CodeBreaker cb = new CodeBreaker("ABCD", new Random());
     Chromosome c = new Chromosome("AXYZ");
     Utility.CalcFitness(c, "ABCD");
     Assert.AreEqual(1, c.Fitness);
 }
        public void TestOnePointCrossover()
        {
            Random r = new Random(0);
            Chromosome c1 = new Chromosome("AAAA");
            Chromosome c2 = new Chromosome("BBBB");

            Utility.OnePointCrossover(c1, c2, r);
            Assert.AreEqual("AABB", new string(c1.Genes));
            Assert.AreEqual("BBAA", new string(c2.Genes));
        }
 private Tuple<Chromosome, Chromosome> Crossover(Chromosome c1, Chromosome c2)
 {
     switch (Properties.crossoverMethod)
     {
         case Properties.Crossover.OnePoint:
             return Utility.OnePointCrossover(c1, c2, r);
             break;
         case Properties.Crossover.TwoPoint:
             throw new NotImplementedException();
         case Properties.Crossover.Uniform:
             return Utility.UniformCrossover(c1, c2, r);
             break;
         default:
             throw new ArgumentException();
     }
 }
        public void ChromosomeConstructorTest()
        {
            var elementProviderMock = new Mock<IElementProvider>();
            elementProviderMock.Setup(provider => provider.Elements).Returns(new[] { 
                new Element() { Name = "Element 1", Value = 1, Weight = 1, Active = false },
                new Element() { Name = "Element 2", Value = 2, Weight = 1, Active = false },
            });
            elementProviderMock.Setup(provider => provider.Size).Returns(2);

            var randomNumberGeneratorMock = new Mock<IRandomNumberGenerator>();
            randomNumberGeneratorMock.Setup(provider => provider.NextDouble()).Returns(1);

            Chromosome chromosome = new Chromosome(elementProviderMock.Object, randomNumberGeneratorMock.Object);

            Assert.AreEqual(chromosome.Elements.Length, 2);
            Assert.IsTrue(chromosome.Elements[0] == elementProviderMock.Object.Elements[0]);
            Assert.IsTrue(chromosome.Elements[1] == elementProviderMock.Object.Elements[1]);
        }
Beispiel #8
0
        public static Solution <T>[] PMXCrossover(Solution <T> a, Solution <T> b, FitnessFunction <T> fitnessFunction)
        {
            Random r = new Random();

            var ae = a.Chromosomes.GetEnumerator();
            var be = b.Chromosomes.GetEnumerator();

            List <Chromosome <T> > cl1 = new List <Chromosome <T> >();
            List <Chromosome <T> > cl2 = new List <Chromosome <T> >();

            // For each chromosome
            while (ae.MoveNext() && be.MoveNext())
            {
                Chromosome <T> ac = ae.Current;
                Chromosome <T> bc = be.Current;

                int point = r.Next(Math.Min(ac.GenesCount, bc.GenesCount));

                // Split chromosomes into parts
                var aFrontGenes = ac.Genes.GetRange(0, point);
                var bFrontGenes = bc.Genes.GetRange(0, point);
                var aTailGenes  = ac.Genes.GetRange(point, ac.GenesCount - point);
                var bTailGenes  = bc.Genes.GetRange(point, bc.GenesCount - point);

                // Find not genes that are unique in aFrontGenes and bFrontGenes
                Stack <T> uniqueAGenes = new Stack <T>();
                Stack <T> uniqueBGenes = new Stack <T>();
                foreach (T aGene in aFrontGenes)
                {
                    int i = bFrontGenes.FindIndex(x => x.Equals(aGene));

                    if (i < 0)
                    {
                        uniqueAGenes.Push(aGene);
                    }
                }
                foreach (T bGene in bFrontGenes)
                {
                    int i = aFrontGenes.FindIndex(x => x.Equals(bGene));

                    if (i < 0)
                    {
                        uniqueBGenes.Push(bGene);
                    }
                }

                // Swap elements in Tail parts
                while (uniqueAGenes.Count > 0 && uniqueBGenes.Count > 0)
                {
                    T aEl = uniqueAGenes.Pop();
                    T bEl = uniqueBGenes.Pop();

                    int pos;

                    pos             = aTailGenes.FindIndex(x => x.Equals(bEl));
                    aTailGenes[pos] = aEl;

                    pos             = bTailGenes.FindIndex(x => x.Equals(aEl));
                    bTailGenes[pos] = bEl;
                }

                // Create new, crossed chromosomes
                List <T> gl1 = new List <T>();
                gl1.AddRange(aFrontGenes);
                gl1.AddRange(bTailGenes);
                cl1.Add(new Chromosome <T>(gl1));

                List <T> gl2 = new List <T>();
                gl2.AddRange(bFrontGenes);
                gl2.AddRange(aTailGenes);
                cl2.Add(new Chromosome <T>(gl2));
            }

            Solution <T> s1 = new Solution <T>(cl1);

            s1.Fitness = fitnessFunction(s1);
            Solution <T> s2 = new Solution <T>(cl2);

            s2.Fitness = fitnessFunction(s2);

            return(new Solution <T>[] { s1, s2 });
        }
        public void TestUniformCrossover()
        {
            Random r = new Random(1);
            Chromosome c1 = new Chromosome("AAAA");
            Chromosome c2 = new Chromosome("BBBB");

            Utility.UniformCrossover(c1, c2, r);
            Assert.AreEqual("BBBA", new string(c1.Genes));
            Assert.AreEqual("AAAB", new string(c2.Genes));
        }
        /// <summary>
        /// Sets up the population to a state before generation 1
        /// </summary>
        public void InitializePopulation()
        {
            Console.WriteLine("Population initialized");
            //make lists
            currentGen = new List<Organism>();

            //setup ideal
            //TODO make this accessible to the topmost level. i.e. population constructor takes in the ideal and allow population to externally set a new ideal
            Chromosome idealGeneticInfo = new Chromosome();
            ideal = new Organism(idealGeneticInfo);

            //fill the first list with _popSize elements
            for (int i = 0; i < _populationSize; i++)
            {
                Organism organism = new Organism();
                organism.testFitness(ideal);
                currentGen.Add(organism);
            }
        }
Beispiel #11
0
        private static void Algorithm3()
        {
            List <Chromosome> generation;
            Stopwatch         sw;
            TimeSpan          ts3;

            generation = Chromosome.Copy(initialChromosome);
            //算法GA

            //开始计时
            sw = new Stopwatch();
            sw.Start();

            double lastMin = 0;

            for (int i = 0, noIm = 0; i < G; i++)
            {
                Console.WriteLine("代数:" + i);
                generation.Sort(); //从小到大排列染色体

                // for (int jj = 0; jj < N; jj++)
                // {
                //     Console.WriteLine("No."+jj+":"+ string.Join(",", generation[jj].encoded));
                //     Console.WriteLine("No."+jj+":"+ string.Join(",",generation[jj].GetDecoded()));
                // }
                //Console.WriteLine("方法GA最优染色体编码为: " + string.Join(",", generation.First().encoded));
                // Console.WriteLine("方法GA最优适应函数值为: " + lastMin);
                //Console.WriteLine("代数1:" + i);
                if (i != 0)                                                                       //至少执行一次
                {
                    if (lastMin - generation.First().GetFitness() <= NoImprovedCriticalCondition) //如果没有改进,计数加一
                    {
                        noIm++;
                    }
                    else
                    {
                        Console.WriteLine("未改进代数:" + noIm);
                        noIm = 0;
                    }
                }

                if (noIm >= MaxGenerationNoImproved)//
                {
                    Console.WriteLine("代数:" + i);
                    break;
                }
                lastMin = generation.First().GetFitness();//更新 lastmin
                //generation.Sort(); //从小到大排列染色体
                var elite = generation.GetRange(0, N);
                //精英 进行 选择 ,交叉,变异
                elite = Chromosome.Select(elite);
                //Console.WriteLine("代数2:" + i);
                Chromosome.Crossover(elite);
                //Console.WriteLine("代数3:" + i);
                Chromosome.Mutation(elite);
                //Console.WriteLine("代数4:" + i);
                generation.Clear();
                generation.AddRange(elite);
                //Chromosome.Intensify(generation.GetRange(N / 2, N / 2), generation.Min());
            }

            generation.Sort();
            // Console.WriteLine("方法GA最优染色体编码为: " + string.Join(",", generation.First().encoded));
            Console.WriteLine("方法GA最优染色体序列为: " + string.Join(",", generation.First().GetDecoded()));
            Console.WriteLine("方法GA最优适应函数值为: " + generation.First().GetFitness());
            Console.WriteLine("最优适应函数值为: " + HistoryRecords.Values.Min());

            //结束计时
            sw.Stop();
            ts3 = sw.Elapsed;
            Console.WriteLine("方法GA总共花费{0}ms.", ts3.TotalMilliseconds);
            Console.WriteLine("  ");
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            int better = 0;
            int worse = 0;
            double grandAvgSum = 0;
            int runs = 0;
            for( ; runs < 1; runs++)
            {
                int populationSize = 200;
                int currentGeneration = 1;
                Chromosome[] population = new Chromosome[populationSize];
                int maxScore = 0;
                int minScore = Int32.MaxValue;
                int total = 0;

                //initial setup of the population
                for (int i = 0; i < populationSize; i++)
                {
                    population[i] = new Chromosome(4, .5, .001);

                    if (population[i].getFitnessScore() > maxScore)
                        maxScore = population[i].getFitnessScore();
                    if (population[i].getFitnessScore() < minScore)
                        minScore = population[i].getFitnessScore();
                    total += population[i].getFitnessScore();
                }
                int firstMax = maxScore;
                int lastMax = 0;
                double lastAvg = 0;
                double firstAvg = (double)(total) / (double)(populationSize);
                for (; currentGeneration <= 10000; currentGeneration++)
                {
                    Chromosome[] selected = Chromosome.rouletteSelect(population, populationSize / 2);
                    Chromosome[] nextGen = new Chromosome[populationSize];

                    maxScore = 0;
                    minScore = Int32.MaxValue;
                    total = 0;

                    //first half are selected and mated from previous set
                    for (int j = 0; j < populationSize / 2; j += 2)
                    {
                        Chromosome[] offspring = Chromosome.mate(selected[j], selected[j + 1]);

                        nextGen[j] = offspring[0];
                        nextGen[j + 1] = offspring[1];
                    }
                    //second half are just the 'parents' that live on
                    for (int j = populationSize / 2; j < populationSize; j++)
                    {
                        nextGen[j] = selected[j - (populationSize / 2)];
                    }

                    for (int j = 0; j < populationSize; j++)
                    {
                        if (nextGen[j].getFitnessScore() > maxScore)
                            maxScore = nextGen[j].getFitnessScore();
                        if (nextGen[j].getFitnessScore() < minScore)
                            minScore = nextGen[j].getFitnessScore();
                        total += nextGen[j].getFitnessScore();
                    }

                    population = nextGen;
                    lastMax = maxScore;
                    lastAvg = ((double)(total) / (double)(populationSize));
                }

                if (firstAvg < lastAvg)
                    better++;
                else
                    worse++;
                grandAvgSum += lastAvg;
            }
            Console.Write("Better performance: ");
            Console.WriteLine(better);
            Console.Write("Worse performance: ");
            Console.WriteLine(worse);
            Console.Write("Grand Average: ");
            Console.WriteLine(grandAvgSum/runs);
            Console.ReadLine();
        }
Beispiel #13
0
 private static Chromosome SelectAnswerCandidate(Chromosome source, Chromosome target)
 {
     return(IsCandidateAnswer(source) ? source : target);
 }
Beispiel #14
0
        public static Chromosome[] rouletteSelect(Chromosome[] population, int numToSelect)
        {
            Chromosome[] toReturn = new Chromosome[numToSelect];
            int[] popIndex = new int[population.Length];
            bool[] hasBeenSelected = new bool[population.Length];

            // sort and compute total fitness
            int fitnessSum = 0;
            population = population.OrderByDescending(x => x.getFitnessScore()).ToArray();
            int previousFitness = 0;
            int counter = 0;
            foreach (Chromosome chrome in population)
            {
                popIndex[counter] = chrome.getFitnessScore() + previousFitness;
                previousFitness = popIndex[counter];
                counter++;
                fitnessSum += chrome.getFitnessScore();
            }

            int selected;
            for(int i = 0; i < numToSelect; i++)
            {
                selected = Program.rng.Next(fitnessSum);
                int index = 0;
                while (selected >= popIndex[index])
                {
                    index++;
                }
                // chrome @ current index was selected from the roulette
                // if the chromosome has already been selected, we just randomly
                // generate another number. This is an easy way to do this but
                // can potentially take a long time to finish the selection if
                // the proportion of selected to not selected is high.
                if (!hasBeenSelected[index])
                {
                    toReturn[i] = population[index];
                    hasBeenSelected[index] = true;
                }
                else
                {
                    // we don't want to go to the next index since we tried
                    // to select something already selected
                    i--;
                }
            }
            return toReturn;
        }
Beispiel #15
0
 /// <summary>
 /// Compares the current chromosome with another chromosome.
 /// </summary>
 /// <param name="otherChromosome">A chromosome to compare with this chromosome.</param>
 /// <returns>
 /// Less than zero if this chromosome is less than the <c>otherChromosome</c> (this chromosome is less fit than the <c>otherChromosome</c>),
 /// zero if this chromosome equals the <c>otherChromosome</c> (this chromosome and the <c>otherChromosome</c> are equally fit), and
 /// greater than zero if this chromosome is more than the <c>otherChromosome</c> (this chromosome is fitter than the <c>otherChromosome</c>).
 /// </returns>
 public int CompareTo(Chromosome <TGene> otherChromosome)
 {
     return(evaluation.CompareTo(otherChromosome.Evaluation));
 }
Beispiel #16
0
 // Methods
 public abstract Chromosome PerformCrossover(Chromosome firstParent, Chromosome secondParent);
 public override void RunTest()
 {
     Console.WriteLine("Chromosome Tests");
     Console.WriteLine("~~~~~~~~~~~~~~~~");
     Console.WriteLine("Created a Chromosome (random alphanumeric string)");
     Chromosome chr1 = new Chromosome();
     Console.WriteLine(chr1.TestGenetics.First<string>());
     Console.WriteLine();
     Console.WriteLine("randomize its genetic information");
     chr1.RandomizeGenome();
     Console.WriteLine(chr1.TestGenetics.First<string>());
     Console.WriteLine();
     //TODO: set this up so you any added string truncates after the number of chars in the string before you set it
     Console.WriteLine("change to specific genetic info: \"Abnormality\"");
     string geneticInfo = "Abnormality";
     chr1.TestGenetics.RemoveRange(0, 1);
     chr1.TestGenetics.Add(geneticInfo);
     Console.WriteLine(chr1.TestGenetics.First<string>());
     Console.WriteLine();
 }
        private void GenerateNextPopulation()
        {
            Random     rnd = new Random();
            Chromosome oldBestSolution = new Chromosome(ProblemParameters.Dimension);
            Chromosome newBestSolution, newWrostSolution;

            // Store best found solution
            _bestOfCurrentPopulation.CopyTo(oldBestSolution);
            //

            #region Selection (Algorithm: Tournament)
            int    tourSize; // Tournament size
            int    bestChromosomeIndex = 0;
            double bestFitness;

            if (PopulationSize < 32)
            {
                tourSize = 3;
            }
            else
            {
                tourSize = (int)Math.Log(PopulationSize, 2) - 1;
            }


            for (int i = 0; i < PopulationSize; i++)
            {
                bestFitness = Double.NegativeInfinity;
                for (int j = 0; j < tourSize; j++)
                {
                    int rndIndex;
                    rndIndex = rnd.Next(PopulationSize);
                    if (_currentPopulation[rndIndex].FitnessValue > bestFitness)
                    {
                        bestFitness         = _currentPopulation[rndIndex].FitnessValue;
                        bestChromosomeIndex = rndIndex;
                    }
                }

                // Copy the "winner of tournament" to Intermediate Population
                _currentPopulation[bestChromosomeIndex].CopyTo(_intermediatePopulation[i]);
            }
            #endregion

            #region Crossover (Algorithm: Arithmetic Crossover)
            for (int i = 0; i < PopulationSize / 2; i++)
            {
                if (rnd.NextDouble() < ProbabilityOfCrossover)
                {
                    // Do Crossover
                    Chromosome.DoCrossover(_intermediatePopulation[i], _intermediatePopulation[i + 1],
                                           _currentPopulation[i], _currentPopulation[i + 1]);
                }
                else
                {
                    // Do NOT Crossover (Copy parents to the new population without any change)
                    _intermediatePopulation[i].CopyTo(_currentPopulation[i]);
                    _intermediatePopulation[i + 1].CopyTo(_currentPopulation[i + 1]);
                }
            }
            #endregion

            #region Mutation
            newBestSolution = newWrostSolution = _currentPopulation[0];

            for (int i = 0; i < PopulationSize; i++)
            {
                if (rnd.NextDouble() < ProbabilityOfMutation)
                {
                    _currentPopulation[i].DoMutation();
                }

                // Find wrost of this (new) population
                if (_currentPopulation[i].FitnessValue < newWrostSolution.FitnessValue)
                {
                    newWrostSolution = _currentPopulation[i];
                }

                // Find best of this (new) population
                if (_currentPopulation[i].FitnessValue > newBestSolution.FitnessValue)
                {
                    newBestSolution = _currentPopulation[i];
                }
            }

            #region Elitism
            oldBestSolution.CopyTo(newWrostSolution); // After this statement, "newWrostSolution" will point to "Old Best Solution"!
            // Now we must find best of current and old populations
            _bestOfCurrentPopulation = (oldBestSolution.FitnessValue < newBestSolution.FitnessValue)
                ? newBestSolution : newWrostSolution;
            #endregion
            #endregion
        }
Beispiel #19
0
        private static void Algorithm1()
        {
            //算法一
            //首先复制初始染色体,注意,因为list是一个引用类型,不能简单的赋值,又因为lsit中存放的也是引用类型,也不能使用浅克隆.
            var generation = Chromosome.Copy(initialChromosome);

            //开始计时
            Stopwatch sw = new Stopwatch();

            sw.Start();

            double lastMin = 0;

            for (int i = 0, noIm = 0; i < G; i++)
            {
                generation.Sort();                                                                //从小到大排列染色体

                if (i != 0)                                                                       //至少执行一次
                {
                    if (lastMin - generation.First().GetFitness() <= NoImprovedCriticalCondition) //如果没有改进,计数加一
                    {
                        noIm++;
                    }
                    else
                    {
                        Console.WriteLine("未改进代数:" + noIm);
                        noIm = 0;
                    }
                }

                if (noIm >= MaxGenerationNoImproved)//
                {
                    Console.WriteLine("代数:" + i);
                    break;
                }
                lastMin = generation.First().GetFitness();//更新 lastmain

                //舍弃适应度函数值较大的后2/1染色体
                generation.RemoveRange(N / 2, N / 2);
                //强化前二分之一

                Chromosome.Intensify(generation, generation.Min());

                var elite = Chromosome.Copy(generation);

                //选择操作
                elite = Chromosome.Select(elite);
                //交叉
                Chromosome.Crossover1(elite);
                //变异
                Chromosome.Mutation(elite);
                generation.AddRange(elite);
            }

            generation.Sort();
            //Console.WriteLine("方法1最优染色体编码为: " + string.Join(",", generation.First().encoded));
            Console.WriteLine("方法1最优染色体序列为: " + string.Join(",", generation.First().GetDecoded()));
            Console.WriteLine("方法1最优适应函数值为: " + generation.First().GetFitness());
            Console.WriteLine("最优适应函数值为: " + HistoryRecords.Values.Min());

            //结束计时
            sw.Stop();
            TimeSpan ts2 = sw.Elapsed;

            Console.WriteLine("方法1总共花费{0}ms.", ts2.TotalMilliseconds);
            Console.WriteLine("  ");
        }
Beispiel #20
0
        // crossing genes of 2 mates
        public static Chromosome[] mate(Chromosome mate1, Chromosome mate2)
        {
            //crossover points = 2
            //For 2 crossover points, just do the process twice

            uint[] childGenes1 = new uint[mate1.getNumGenes()];
            uint[] childGenes2 = new uint[mate2.getNumGenes()];

            Chromosome[] toReturn = new Chromosome[2];

            //chose which change to split on
            int geneToSplit = Program.rng.Next(mate1.getNumGenes());

            //calculate how many bits we are using
            int bitPos = 0;
            int bitsCalc = maxGeneVal;
            while (bitsCalc != 1)
            {
                bitsCalc = bitsCalc >> 1;
                bitPos++;
            }
            int pivot = Program.rng.Next(bitPos + 1);

            //no mid-gene swap
            if (pivot == 0)
            {
                childGenes1[geneToSplit] = mate1.getGenes()[geneToSplit];
                childGenes2[geneToSplit] = mate2.getGenes()[geneToSplit];
            }//swap all bits of this gene
            else if (pivot == bitPos)
            {
                childGenes1[geneToSplit] = mate2.getGenes()[geneToSplit];
                childGenes2[geneToSplit] = mate1.getGenes()[geneToSplit];
            }//mid bitstring swap, actually have to do stuff here
            else
            {
                uint saveMask = uint.MaxValue << pivot;
                uint swapMask = uint.MaxValue >> 32 - pivot;
                // half of the chunk that is swapping
                uint swapChunk1 = mate1.getGenes()[geneToSplit] & swapMask;
                uint swapChunk2 = mate2.getGenes()[geneToSplit] & swapMask;

                //put two havles together with bitwise 'or'
                childGenes1[geneToSplit] = (mate1.getGenes()[geneToSplit] & saveMask) | swapChunk2;
                childGenes2[geneToSplit] = (mate2.getGenes()[geneToSplit] & saveMask) | swapChunk1;
            }

            //then, copy all genes before the pivot, and swap all genes after pivot
            for (int i = 0; i < mate1.getNumGenes(); i++)
            {
                if (i < geneToSplit)
                {
                    childGenes1[i] = mate1.getGenes()[i];
                    childGenes2[i] = mate2.getGenes()[i];
                }
                else if (i > geneToSplit)
                {
                    childGenes1[i] = mate2.getGenes()[i];
                    childGenes2[i] = mate1.getGenes()[i];
                }
            }

            Chromosome newChild1 = new Chromosome(childGenes1, mate1.getCrossoverRate(), mate1.getMutationRate());
            Chromosome newChild2 = new Chromosome(childGenes2, mate2.getCrossoverRate(), mate2.getMutationRate());

            toReturn[0] = newChild1;
            toReturn[1] = newChild2;

            if (hasMated)
            {
                hasMated = false;
                toReturn[0] = mutateGenes(toReturn[0], mate1.getMutationRate());
                toReturn[1] = mutateGenes(toReturn[1], mate2.getMutationRate());
                return toReturn;
            }
            else
            {
                hasMated = true;
                return mate(newChild1, newChild2);
            }
        }
Beispiel #21
0
 private static bool IsCandidateAnswer(Chromosome candidate)
 {
     return(candidate.Score == 0);
 }
Beispiel #22
0
        // random chance that a bit is flipped
        private static Chromosome mutateGenes(Chromosome toMutate, double mutationRate)
        {
            double target = 1.0 / mutationRate;
            if (target == Program.rng.Next(1000) + 1)
            {
                // mutation! now we randomly select bit to change

                int geneToMutate = Program.rng.Next(toMutate.getNumGenes());
                int bitsCalc = maxGeneVal;
                int bitPos = 0;
                while (bitsCalc != 1)
                {
                    bitsCalc = bitsCalc >> 1;
                    bitPos++;
                }

                int bitToFlip = Program.rng.Next(bitPos);
                uint newGeneVal = toMutate.getGenes()[geneToMutate];
                newGeneVal ^= (uint)(1 << bitToFlip);

                toMutate.setGene(geneToMutate, newGeneVal);
            }
            return toMutate;
        }
Beispiel #23
0
 private static void SetCandidates()
 {
     source = myHabitat.ExtractCandidate(pool);
     target = myHabitat.ExtractCandidate(pool);
 }
Beispiel #24
0
        public Tuple <bool, double, double[], bool[]> Execute(Point goal)
        {
            Goal = goal;

            /*Chs = new Chromosome<double>[GenSize];
             * Fit = new double[GenSize];
             *
             * for (int i = 0; i < GenSize; i++)
             * {
             *  Chs[i] = new Chromosome<double>(ParamNum);
             *  for (int j = 0; j < ParamNum; j++)
             *      Chs[i].Genes[j] = Agent.StepRanges[j, 0] + (Agent.StepRanges[j, 1] - Agent.StepRanges[j, 0]) * Rng.NextDouble();
             * }
             *
             * Chromosome<double> dominant = null;
             * double Min = double.PositiveInfinity;
             * bool Converged = false;
             * Stopwatch sw = new Stopwatch();
             * sw.Start();
             * while (Time++ < MaxTime)
             * {
             *  //fitting
             *  FitnessFunction();
             *  Array.ConvertAll(Fit, (t) => { return Math.Abs(t); });
             *
             *  //qualification
             *  Min = Fit.Min();
             *  if (Min < Precision)
             *  {
             *      dominant = Chs[Array.IndexOf(Fit, Min)];
             *      Converged = true;
             *      break;
             *  }
             *
             *  //selection
             *  RouletteWheelSelection(Chs, Fit);
             *
             *  //mutation
             *  Mutation(Chs, Pm, t => t + -0.1 + 0.2 * Rng.NextDouble());
             *
             *  //crossover
             *  Crossover(Chs);
             * }
             * sw.Stop();
             * TotalRealTime += (int)sw.ElapsedTicks / 10;
             * Console.WriteLine("IKP Time: {0}; Real time: {1}", Time, sw.ElapsedTicks / 10);
             *
             * //if dominant chromosome wasn't found, consider last result the best result
             * if (dominant == null)
             * {
             *  dominant = Chs[Array.IndexOf(Fit, Min)];
             * }
             *
             * //decoding chromosome
             * double[] dq = dominant.GetParamAll(Decode);
             *
             * //detect all collisions
             * Manipulator AgentNext = new Manipulator(Agent)
             * {
             *  q = Agent.q.Zip(dq, (t, s) => { return t + s; }).ToArray()
             * };
             * bool[] Collisions = DetectCollisions(AgentNext);
             *
             * Time = 0;
             * return new Tuple<bool, double, double[], bool[]>(Converged, Min, dq, Collisions);*/

            double range = 0;

            for (int i = 0; i < ParamNum; i++)
            {
                range = -120 * Math.PI / 180 - Agent.q[i];
                Agent.StepRanges[i, 0] = range / 5;  // <= -1 ? -1 : range;

                range = 120 * Math.PI / 180 - Agent.q[i];
                Agent.StepRanges[i, 1] = range / 5;  // >= 1 ? 1 : range;
            }

            Manipulator Contestant = new Manipulator(Agent);

            double[] q_init = new double[ParamNum];
            Array.Copy(Agent.q, q_init, ParamNum);
            double dist = Agent.DistanceTo(Goal), init_dist = dist, coeff = 1;
            double Min       = double.PositiveInfinity;
            bool   Converged = false;

            Stopwatch sw = new Stopwatch();

            sw.Start();
            while (Time++ < 1000)
            {
                Chromosome <double> ch = new Chromosome <double>(ParamNum);
                for (int i = 0; i < ParamNum; i++)
                {
                    ch.Genes[i]  = Agent.StepRanges[i, 0] + (Agent.StepRanges[i, 1] - Agent.StepRanges[i, 0]) * Rng.NextDouble();
                    ch.Genes[i] *= coeff;
                }

                double[] dq = ch.GetParamAll(Decode);
                Contestant.q = Agent.q.Zip(dq, (t, s) => { return(t + s); }).ToArray();
                double dist_new = Contestant.DistanceTo(Goal);
                if (dist_new < dist)
                {
                    Array.Copy(Contestant.q, Agent.q, ParamNum);
                    Min   = dist = dist_new;
                    coeff = dist / init_dist;
                }

                if (dist < 0.002)
                {
                    Converged = true;
                    break;
                }
            }
            sw.Stop();
            Console.WriteLine("IKP Time: {0}; Real time: {1}", Time, sw.ElapsedTicks / 10);

            bool[] Collisions = DetectCollisions(Agent);

            Time = 0;
            return(new Tuple <bool, double, double[], bool[]>(Converged, Min, Agent.q.Zip(q_init, (t, s) => { return t - s; }).ToArray(), Collisions));
        }
Beispiel #25
0
        private static void Algorithm2()
        {
            List <Chromosome> generation;
            Stopwatch         sw;
            TimeSpan          ts2;

            generation = Chromosome.Copy(initialChromosome);
            //算法二

            //开始计时
            sw = new Stopwatch();
            sw.Start();

            double lastMin = 0;

            for (int i = 0, noIm = 0; i < G; i++)
            {
                generation.Sort(); //从小到大排列染色体
                // Console.WriteLine("方法2最优染色体编码为: " + string.Join(",", generation.First().encoded));
                // Console.WriteLine("方法2最优适应函数值为: " + generation.First().GetFitness());
                // Console.WriteLine("方法2最差适应函数值为: " + generation.Last().GetFitness());
                if (i != 0)                                                                       //至少执行一次
                {
                    if (lastMin - generation.First().GetFitness() <= NoImprovedCriticalCondition) //如果没有改进,计数加一
                    {
                        noIm++;
                    }
                    else
                    {
                        noIm = 0;
                    }
                }
                //Console.WriteLine("未改进代数:" + noIm);
                if (noIm >= MaxGenerationNoImproved)//
                {
                    Console.WriteLine("代数:" + i);
                    break;
                }
                lastMin = generation.First().GetFitness();//更新 lastmain

                var elite    = generation.GetRange(0, N / 2);
                var ordinary = generation.GetRange(N / 2, N / 2);

                //Console.WriteLine("代数:" + i);

                //Console.WriteLine("目前代最优适应函数值为: " + generation.Min().GetFitness());
                //Console.WriteLine("目前代第一适应函数值为: " + generation.First().GetFitness());
                //Console.WriteLine("目前代最差适应函数值为: " + generation.Last().GetFitness());
                //Console.WriteLine("方法2最优染色体序列为: " + string.Join(",", generation.Last().GetDecoded()));
                //Console.WriteLine("目前精英最优适应函数值为: " + elite.Min().GetFitness());
                //精英 进行 选择 ,交叉,变异
                elite = Chromosome.Select(elite);
                // Console.WriteLine("目前代最优适应函数值为: " + generation.Min().GetFitness());
                //Console.WriteLine("目前精英最优适应函数值为: " + elite.Min().GetFitness());

                Chromosome.Crossover(elite);
                // Console.WriteLine("目前代最优适应函数值为: " + generation.Min().GetFitness());
                // Console.WriteLine("目前精英最优适应函数值为: " + elite.Min().GetFitness());


                Chromosome.Mutation(elite);
                //Console.WriteLine("目前代最优适应函数值为: " + generation.Min().GetFitness());
                //Console.WriteLine("目前精英最优适应函数值为: " + elite.Min().GetFitness());


                Chromosome.Intensify(ordinary, elite.Min());

                generation.Clear();
                generation.AddRange(elite);
                generation.AddRange(ordinary);

                // Console.WriteLine("目前代最优适应函数值为: " + generation.Min().GetFitness());
                //Console.WriteLine("目前精英最优适应函数值为: " + elite.Min().GetFitness());

                //Console.WriteLine("  ");
            }

            generation.Sort();
            // Console.WriteLine("方法2最优染色体编码为: " + string.Join(",", generation.First().encoded));
            Console.WriteLine("方法2最优染色体序列为: " + string.Join(",", generation.First().GetDecoded()));
            Console.WriteLine("方法2最优适应函数值为: " + generation.First().GetFitness());
            Console.WriteLine("最优适应函数值为: " + HistoryRecords.Values.Min());


            //结束计时
            sw.Stop();
            ts2 = sw.Elapsed;
            Console.WriteLine("方法2总共花费{0}ms.", ts2.TotalMilliseconds);
            Console.WriteLine("  ");
        }