예제 #1
0
파일: Form1.cs 프로젝트: bjutlgr/ga1
        private void Go_Click(object sender, EventArgs e)
        {
            //initialize var
            int cLength = Convert.ToInt32(chromoLength.Text);
            EliteSelection<int> sel2 = new EliteSelection<int>(0);
            RouletteSelection<int> sel1 = new RouletteSelection<int>();
            GreedyCrossover cros = new GreedyCrossover(-1, -1, matrix);
            GoldenMutation<int> mut = new GoldenMutation<int>(cLength);
            pop = new Population<int>(mut, cros, sel1, sel2, x => 1 / cros.CalcFitness(x),
                Convert.ToDouble(mProb.Text), Convert.ToDouble(cProb.Text));
            maxF = new double[Convert.ToInt32(expCount.Text), Convert.ToInt32(iterCount.Text) + 1];
            avgF = new double[Convert.ToInt32(expCount.Text), Convert.ToInt32(iterCount.Text) + 1];
            double min = 100500; // Hi to Max ))
            string bestChromo = null;

            //experiments
            for (int i = 0; i < Convert.ToInt32(expCount.Text); ++i)
            {
                //initial chromosomes
                Trace.WriteLine("experiment #" + (i + 1).ToString());
                Trace.Indent();
                ChromosomesFromArray();
                maxF[i, 0] = Math.Round(1 / pop.GetMaxFitness());
                avgF[i, 0] = 1 / pop.GetPopulationFitness();
                Trace.WriteLine("initial best fitness = " + Math.Round((1 / pop.GetMaxFitness())).ToString());
                Trace.WriteLine("initial avg fitness = " + (1 / pop.GetPopulationFitness()).ToString());
                Trace.WriteLine("initia;best fitness chromo = " + pop.GetMaxChromo());

                // iterations
                for (int j = 0; j < Convert.ToInt32(iterCount.Text); ++j)
                {
                    Trace.WriteLine("iteration #" + (j + 1).ToString());
                    Trace.Indent();
                    pop.Iteration();
                    maxF[i, j + 1] = Math.Round(1 / pop.GetMaxFitness());
                    avgF[i, j + 1] = 1 / pop.GetPopulationFitness();
                    Trace.WriteLine(" best fitness  = " + Math.Round((1 / pop.GetMaxFitness())).ToString());
                    Trace.WriteLine("avg fitness = " + (1 / pop.GetPopulationFitness()).ToString());
                    Trace.WriteLine("best fitness chromo = " + pop.GetMaxChromo());
                    Trace.Unindent();
                }
                if (Math.Round(1 / pop.GetMaxFitness()) < min)
                {
                    min = Math.Round(1 / pop.GetMaxFitness());
                    bestChromo = pop.GetMaxChromo();
                }
                Trace.Unindent();
            }
            answer.Text = "Best Path: " + bestChromo + "Path Length" + min.ToString();
        }