Beispiel #1
0
        // Worker thread
        void SearchSolution( )
        {
            // create fitness function
            TSPFitnessFunction fitnessFunction = new TSPFitnessFunction(map);
            // create population
            Population population = new Population(populationSize,
                                                   (greedyCrossover) ? new TSPChromosome(map) : new PermutationChromosome(citiesCount),
                                                   fitnessFunction,
                                                   (selectionMethod == 0) ? (ISelectionMethod) new EliteSelection( ) :
                                                   (selectionMethod == 1) ? (ISelectionMethod) new RankSelection( ) :
                                                   (ISelectionMethod) new RouletteWheelSelection( )
                                                   );
            // iterations
            int i = 1;

            // path
            double[,] path = new double[citiesCount + 1, 2];
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            // loop
            while (!needToStop)
            {
                // run one epoch of genetic algorithm
                population.RunEpoch( );

                // display current path
                ushort[] bestValue = ((PermutationChromosome)population.BestChromosome).Value;

                for (int j = 0; j < citiesCount; j++)
                {
                    path[j, 0] = map[bestValue[j], 0];
                    path[j, 1] = map[bestValue[j], 1];
                }
                path[citiesCount, 0] = map[bestValue[0], 0];
                path[citiesCount, 1] = map[bestValue[0], 1];

                mapControl.UpdateDataSeries("path", path);

                // set current iteration's info
                SetText(currentIterationBox, i.ToString( ));
                SetText(pathLengthBox, Math.Round(fitnessFunction.PathLength(population.BestChromosome), 2).ToString( ));

                // increase current iteration
                i++;

                //
                if ((iterations != 0) && (i > iterations))
                {
                    break;
                }
            }

            stopWatch.Stop();
            SetTextBox(Math.Round(stopWatch.Elapsed.TotalSeconds, 0) + "s lub " + Math.Round(stopWatch.Elapsed.TotalMilliseconds, 0) + "ms");

            // enable settings controls
            EnableControls(true);
        }
Beispiel #2
0
        // Worker thread
        void SearchSolution()
        {
            // create fitness function
            var fitnessFunction = new TSPFitnessFunction(map);
            // create population
            var population = new Population(populationSize,
                                            (greedyCrossover) ? new TSPChromosome(map) : new PermutationChromosome(citiesCount),
                                            fitnessFunction,
                                            (selectionMethod == 0) ? new EliteSelection() :
                                            (selectionMethod == 1) ? new RankSelection() :
                                            (ISelectionMethod) new RouletteWheelSelection()
                                            );
            // iterations
            var i = 1;

            // path
            var path = new double[citiesCount + 1, 2];

            // loop
            while (!needToStop)
            {
                // run one epoch of genetic algorithm
                population.RunEpoch();

                // display current path
                var bestValue = ((PermutationChromosome)population.BestChromosome).Value;

                for (var j = 0; j < citiesCount; j++)
                {
                    path[j, 0] = map[bestValue[j], 0];
                    path[j, 1] = map[bestValue[j], 1];
                }
                path[citiesCount, 0] = map[bestValue[0], 0];
                path[citiesCount, 1] = map[bestValue[0], 1];

                mapControl.UpdateDataSeries("path", path);

                // set current iteration's info
                SetText(currentIterationBox, i.ToString());
                SetText(pathLengthBox, fitnessFunction.PathLength(population.BestChromosome).ToString());

                // increase current iteration
                i++;

                //
                if ((iterations != 0) && (i > iterations))
                {
                    break;
                }
            }

            // enable settings controls
            EnableControls(true);
        }
Beispiel #3
0
        public void Solve(int minDistance)
        {
            var population = new Population(20, new Chromosome(), new FitnessFunction(), new  EliteSelection());

            population.CrossoverRate = 0;
            population.MutationRate  = 0.3;
            //population.RandomSelectionPortion = 0.8;

            int i = 0;

            while (i < 2500 || population.BestChromosome.Fitness > minDistance)
            {
                i++;
                population.RunEpoch();
                Console.WriteLine("distance " + population.BestChromosome.Fitness.ToString());
            }
        }
Beispiel #4
0
        void SearchSolution( )
        {
            // створення фітнес функції
            TSPFitnessFunction fitnessFunction = new TSPFitnessFunction(map);
            // створення популяції
            Population population = new Population(populationSize,
                                                   (greedyCrossover) ? new TSPChromosome(map) : new PermutationChromosome(citiesCount),
                                                   fitnessFunction,
                                                   (selectionMethod == 0) ? (ISelectionMethod) new EliteSelection( ) :
                                                   (selectionMethod == 1) ? (ISelectionMethod) new RankSelection( ) :
                                                   (ISelectionMethod) new RouletteWheelSelection( )
                                                   );
            // ітерації
            int i = 1;

            // петля
            while (!needToStop)
            {
                // запус одного покоління генетичного алгоритму
                population.RunEpoch( );

                // відобразити поточний шлях
                mapControl.Path = ((PermutationChromosome)population.BestChromosome).Value;

                // встановити дані поточної ітерації
                currentIterationBox.Text = i.ToString( );
                pathLengthBox.Text       = fitnessFunction.PathLength(population.BestChromosome).ToString( );

                // наступна ітерація
                i++;


                if ((iterations != 0) && (i > iterations))
                {
                    break;
                }
            }

            EnableControls(true);
        }
Beispiel #5
0
        // hlavna metoda programu
        static void Main(string[] args)
        {
            // otvorenie vstupneho suboru
            System.IO.StreamReader inputfile = new System.IO.StreamReader(args[0]);

            string line;
            int    citycounter = 0;

            while ((line = inputfile.ReadLine()) != null)
            {
                if (line == "")
                {
                    citycounter++;
                }
            }

            inputfile.Close();

            // deklarovanie pola koordinacii pre vsetky mesta
            map = new double[citycounter, 2];

            // otvorenie vstupneho suboru
            inputfile = new System.IO.StreamReader(args[0]);

            int city = 0;

            line = "yes";

            while (true)
            {
                line = inputfile.ReadLine();
                if (line == null)
                {
                    break;
                }
                map[city, 0] = System.Convert.ToDouble(line);
                line         = inputfile.ReadLine();
                map[city, 1] = System.Convert.ToDouble(line);
                line         = inputfile.ReadLine();
                city++;
            }

            inputfile.Close();

            // vytvorenie ohodnocovacej fitness funkcie
            TSPFitnessFunction fitnessFunction = new TSPFitnessFunction(map);

            // vytvorenie uvodnej populacie genetickeho algoritmu
            Population population = new Population(POPULATION_SIZE,
                                                   ( CROSSOVER ) ? new TSPChromosome(map) : new PermutationChromosome(citycounter),
                                                   fitnessFunction,
                                                   (SELECTION_METHOD == 0) ? (ISelectionMethod) new EliteSelection( ) :
                                                   (SELECTION_METHOD == 1) ? (ISelectionMethod) new RankSelection( ) :
                                                   (ISelectionMethod) new RouletteWheelSelection( )
                                                   );

            // poradove cislo iteracie
            int i = 1;

            // cyklus genetickeho algoritmu
            while (true)
            {
                // prebehnutie jednej generacie
                population.RunEpoch( );

                // vypis fitness najlepsieho jedinca aktualnej generacie
                System.Console.WriteLine(System.Convert.ToInt32(fitnessFunction.PathLength(population.BestChromosome)).ToString( ));
                // inkrementacie premennej uchovavajucej poradove cislo generacie
                i++;

                // ukoncovacia podmienka
                // - dopredu znamy pocet opakovani
                if (i > ITERATIONS)
                {
                    break;
                }
            }
            string       s      = (string)fitnessFunction.Translate(population.BestChromosome);
            StringReader reader = new StringReader(s);

            line = "yes";
            int from  = 0;
            int to    = 0;
            int first = 0;

            System.IO.StreamWriter outputfile = new System.IO.StreamWriter(args[1]);

            outputfile.Write("<center><div id=\"canvas\" style=\"position:relative;width:700px;height:700px;background:white;float:center;\"></div></center><script type=\"text/JavaScript\">var canvasDiv=document.getElementById(\"canvas\");var gr = new jsGraphics(canvasDiv);var col = new jsColor(\"red\");var pen = new jsPen(col,1);var col2 = new jsColor(\"black\");");

            line  = reader.ReadLine();
            from  = System.Convert.ToInt32(line);
            first = from;
            while (line != null)
            {
                line = reader.ReadLine();
                to   = System.Convert.ToInt32(line);
                if (line == null)
                {
                    to = first;
                }
                outputfile.WriteLine("gr.drawLine(pen,new jsPoint(" + map[from, 0] + "," + map[from, 1] + "),new jsPoint(" + map[to, 0] + "," + map[to, 1] + "));");
                from = to;
            }

            for (int x = 0; x < citycounter; x++)
            {
                outputfile.WriteLine("gr.fillCircle(col2,new jsPoint(" + map[x, 0] + "," + map[x, 1] + "),4);");
            }
            outputfile.Write("</script>");
            outputfile.Close();
        }