private bool checkStopCriteria()
        {
            CTour bestGlobalTour = CIterationList.getInstance().getBestGlobalTour();

            // haben wir eine bessere Lösung als die Optimale Lösung gefunden?
            // dann können wir abbrechen
            if (mOptTour != null)
            {
                if (bestGlobalTour != null)
                {
                    if ((bestGlobalTour.getTourLength() <= mOptTour.getTourLength()) && (mAlgorithmParam.bBestTourStop == true))
                    {
                        return(true);
                    }
                }
            }

            // Haben wir den Schwellenwert unterschritten?
            if (bestGlobalTour != null)
            {
                if ((bestGlobalTour.getTourLength() <= mAlgorithmParam.iLimitStop) && (mAlgorithmParam.bLimitStop == true))
                {
                    return(true);
                }
            }
            return(false);
        }
        private void drawBestPaths()
        {
            CIterationList iterationList = CIterationList.getInstance();

            if (mDraw.optPath)
            {
                CTour optimumTour = CAntAlgorithmParameters.getInstance().optTour;
                drawTour(optimumTour, OPT_TOUR_DRAW_LAYER, 0f, 0f, 1f);
            }

            if (mDraw.bestPathOfIteration)
            {
                CTour bestIterationTour = iterationList.getBestLastIterationTour();
                drawTour(bestIterationTour, BEST_GLOBAL_TOUR_DRAW_LAYER, 0f, 1f, 0f);
            }

            if (mDraw.bestPathOfAllIterations)
            {
                CTour bestGlobalTour = iterationList.getBestGlobalTour();
                drawTour(bestGlobalTour, BEST_ITERATION_TOUR_DRAW_LAYER, 1f, 0f, 0f);
            }

#if DEBUG
            if (debugTour != null)
            {
                drawTour(debugTour, OPT_TOUR_DRAW_LAYER - 0.5f, 1f, 1f, 0f, true);
            }
#endif
        }
Exemple #3
0
 public Form1()
 {
     InitializeComponent();
     postInitialize();
     Application.Idle += new EventHandler(Application_Idle);
     CProgressManager.setProgressBar(pIterationProgressBar);
     CIterationList.setForm(this);
     refreshDelegateStatistic = new delegateRefreshStatistic(refreshStatisticNumbers);
 }
Exemple #4
0
        private void button_Start_Click(object sender, EventArgs e)
        {
            CAntAlgorithmParameters antAlgorithmParameters = CAntAlgorithmParameters.getInstance();

            antAlgorithmParameters.numberAnts          = Convert.ToInt32(uAntsQuantity.Value);
            antAlgorithmParameters.numberMaxIterations = Convert.ToInt32(uQuantityIterations.Value);
            antAlgorithmParameters.pheromoneParameter  = pheromonValue;
            antAlgorithmParameters.pheromoneUpdate     = heuristicPheromonUpdateValue;
            antAlgorithmParameters.initialPheromone    = initialPheromonValue;
            antAlgorithmParameters.localInformation    = heuristicValue;
            antAlgorithmParameters.evaporationFactor   = evaporationValue;
            antAlgorithmParameters.bBestTourStop       = cStoppLoesung.Checked;
            antAlgorithmParameters.bLimitStop          = cStopSchwellenwert.Checked;
            antAlgorithmParameters.iLimitStop          = 0;
            if (antAlgorithmParameters.bLimitStop == true)
            {
                antAlgorithmParameters.iLimitStop = Convert.ToInt32(tThreshold.Text);
            }
            //MessageBox.Show("Ants: " + CAntAlgorithmParameters.getInstance().numberAnts + "\n" + CAntAlgorithmParameters.getInstance().numberMaxIterations + "\n" + CAntAlgorithmParameters.getInstance().pheromoneParameter + " \n" + "usw usw");

            if (!(mAntAlgorithmThread == null) && (mAntAlgorithmThread.IsAlive == true) && (button_Start.Text == BUTTON_START_TEXT_STOP))
            {
                mAntAlgorithmThread.Abort();
                CIterationList.getInstance().Clear();
                GC.Collect();
            }
            if (CTSPPointList.getInstance().length() < 2)
            {
                MessageBox.Show("Anzahl der Städte beträgt weniger als 2.");
                return;
            }

            if (((mAntAlgorithmThread == null) || (mAntAlgorithmThread.IsAlive == false)) && (button_Start.Text == BUTTON_START_TEXT_START))
            {
                CAntAlgorithm antAlgorithm = new CAntAlgorithm(mRenderWindow, tNumberOfIteration);
                mAntAlgorithmThread          = new Thread(antAlgorithm.startAlgorithm);
                mAntAlgorithmThread.Name     = "AntAlgorithmThread";
                mAntAlgorithmThread.Priority = ThreadPriority.Normal;
                mAntAlgorithmThread.Start();

                mTimerThread          = new Thread(this.timerThread);
                mTimerThread.Name     = "TimerThread";
                mTimerThread.Priority = ThreadPriority.Lowest;
                mTimerThread.Start();
            }

            if (button_Start.Text == BUTTON_START_TEXT_START)
            {
                button_Start.Text = BUTTON_START_TEXT_STOP;
            }
            else
            {
                button_Start.Text = BUTTON_START_TEXT_START;
            }
        }
        public void NewIteration()
        {
            CreateNewAnts();

            List <Thread> antThreadList = new List <Thread>();

            // Ameisen laufen lassen
            foreach (CAnt ant in arrayOfAnts)
            {
                Thread antThread = new Thread(new ParameterizedThreadStart(this.handleAnt));
                antThreadList.Add(antThread);

                antThread.Name     = "AntThread" + antThreadList.Count.ToString();
                antThread.Priority = ThreadPriority.Highest;

                antThread.Start(ant);
            }

            // Prüfen ob alle Threads fertig sind
            bool bAllThreadsFinished = false;

            while (bAllThreadsFinished == false)
            {
                Thread.Sleep(1);
                bAllThreadsFinished = true;

                foreach (Thread antThread in antThreadList)
                {
                    if (antThread.ThreadState == System.Threading.ThreadState.Running)
                    {
                        bAllThreadsFinished = false;
                    }
                }
            }

            // kürzeste Tour ermitteln und die durchschnittliche Länge
            CTour  shortestTour      = new CTour();
            double averageTourLength = 0;

            foreach (CAnt ant in arrayOfAnts)
            {
                averageTourLength += ant.GetTour().getTourLength() / arrayOfAnts.Length;
                if ((ant.GetTour().getTourLength() < shortestTour.getTourLength()) || (shortestTour.getTourLength() == 0))
                {
                    shortestTour = ant.GetTour();
                }
            }

            Debug.WriteLine(shortestTour.getTourLength());

            // Iteration in die Liste zurückspeichern
            CIterationList.getInstance().Add(new CIteration(shortestTour, averageTourLength));
        }
Exemple #6
0
        public void refreshStatisticNumbers()
        {
            CIterationList iterationList = CIterationList.getInstance();

            if (iterationList.Last() != null)
            {
                tØIteration.Text = String.Format("{0:f}", iterationList.Last().AverageTourLength);
            }
            if (iterationList.GlobalAverageTourLength() != 0)
            {
                tØGlobal.Text = String.Format("{0:f}", iterationList.GlobalAverageTourLength());
            }
            if (iterationList.getBestLastIterationTour() != null)
            {
                tBestIteration.Text = String.Format("{0:f}", iterationList.getBestLastIterationTour().getTourLength());
            }
            if (iterationList.getBestGlobalTour() != null)
            {
                tBestGlobal.Text = String.Format("{0:f}", iterationList.getBestGlobalTour().getTourLength());
            }
        }
Exemple #7
0
        private void openTSPFile()
        {
            CIterationList.getInstance().Clear();

            // Open the selected file to read.
            System.IO.Stream myResult = openTspFileDialog1.OpenFile();

            string tspFilePath  = openTspFileDialog1.FileName;
            string tourFilePath = tspFilePath.Substring(0, tspFilePath.LastIndexOf('.')) + ".opt.tour";

            try
            {
                // zuerst mal das TSPfile parsen
                CTSPLibFileParser tspParser = new CTSPLibFileParser(myResult);
                tspParser.fillTSPPointList();

                // prüfen ob eine Datei mit der optimalen Tour existiert
                if (File.Exists(tourFilePath) == true)
                {
                    // Dann die Optimale Tour parsen
                    FileStream        optTourFile = File.Open(tourFilePath, FileMode.Open);
                    CTSPLibFileParser tourParser  = new CTSPLibFileParser(optTourFile);
                    tourParser.getOptTour();
                }
                else
                {
                    CAntAlgorithmParameters.getInstance().optTour = null;
                }
            }
            catch (ThreadAbortException)
            {
                // wir machen nichts .. das ist nur zum verhindern das eine Meldung angezeigt wird
            }
            catch (CInsufficientMemoryException exception)
            {
                if (exception.getType() == CInsufficientMemoryException.E_EXCEPTION_TYPE.E_32_BIT_ERROR)
                {
                    MessageBox.Show("Um dieses Projekt laden zu können werden ca. " + exception.getMemoryNeeded()
                                    + " MByte benötigt. 32-Bit-Anwendungen können aber maximal " + exception.getMemoryAvailable() + " MByte verwalten. "
                                    + "Bitte verwenden sie die 64-Bit Version oder öffnen Sie ein kleineres Projekt.", "Fehler!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("Auf ihrem System stehen noch " + exception.getMemoryAvailable() + " MByte zur Verfügung. Es werden aber ca. "
                                    + exception.getMemoryNeeded() + " MByte benötigt. "
                                    + "Wenn Sie dieses Projekt laden möchten stellen Sie Bitte mehr RAM zur Verfügung.", "Fehler!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "Fehler!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CAntAlgorithmParameters.getInstance().optTour = null;
            }
            finally
            {
                // stream wieder schließen
                myResult.Close();
            }

            // Schaltfläche der Stoppkriterien, Lösung gefunden, (de)aktivieren
            this.Invoke(new Action(setStopCriteriaSolutionFound));

            // Länge der optimalen Tour anzeigen
            tOptimalerPfad.Invoke(new Action(delegate()
            {
                if (CAntAlgorithmParameters.getInstance().optTour != null)
                {
                    tOptimalerPfad.Text = CAntAlgorithmParameters.getInstance().optTour.getTourLength().ToString();
                }
                else
                {
                    tOptimalerPfad.Text = "";
                }
            }));

            // neu Rendern
            mRenderWindow.Invoke(new Action(delegate()
            {
                mRenderWindow.initViewPort();
                mRenderWindow.Refresh();
            }));

            CProgressManager.setFinished();
        }
        public void startAlgorithm()
        {
            CProgressManager.setStepsIteration(mMaxIterations);

            mConnectionList.SetInitialPheromone(mInitialPheromone);

            mItertationsTextbox.Invoke(new Action(delegate()
            {
                mItertationsTextbox.Text = "0/" + mMaxIterations;
            }));

            DateTime startTime = DateTime.Now;

            int  iteration      = 0;
            bool bStopAlgorithm = false;

            while ((iteration < mMaxIterations) && (bStopAlgorithm == false))
            {
                NewIteration();

                // Evaporation (verdunstung)
                //--------------------------------
                // Dazu iterieren wir durch alle Verbindungen und lassen das Pheromon verdunsten
                foreach (CConnection connection in mConnectionList)
                {
                    connection.evaporate(mEvaporationFactor);
                }

                // Pheromon-Update
                //--------------------------------
                // Dazu durch alle Touren von allen Ameisen nachgehen und für jede Verbindung die
                // Pheromonwerte neu berechnen
                // Formel: delta(t ij) = Q / (distance ij)
                foreach (CAnt ant in arrayOfAnts)
                {
                    CTour antTour = ant.GetTour();

                    // wir fangen mit Index 1 an! Damit die Punkte der Verbindungen mit den Indizies
                    // index -1 und index geholt werden können
                    for (int pointIndex = 1; pointIndex < antTour.getListLength(); pointIndex++)
                    {
                        CTSPPoint fromPoint = antTour.getPoint(pointIndex - 1);
                        CTSPPoint toPoint   = antTour.getPoint(pointIndex);

                        CConnection tourConnection = mConnectionList.getConnection(fromPoint, toPoint);
                        tourConnection.addPheromone(mPhermomoneUpdate);
                    }
                }

                CIterationList.getInstance().refreshStatisticNumbers();
                mRenderWindow.Invoke(mRenderWindow.refreshDelegate);
                CProgressManager.stepDone();

                mItertationsTextbox.Invoke(new Action(delegate()
                {
                    mItertationsTextbox.Text = (iteration + 1) + "/" + mMaxIterations;
                }));

                Debug.WriteLine("Iteration done: " + (iteration + 1));


                // Stopkriterien testen
                bStopAlgorithm = checkStopCriteria();

                // Iterationszähler erhöhen
                iteration++;
            }

            Debug.WriteLine("Dauer: " + (DateTime.Now - startTime).TotalSeconds + " sek");
        }