public QapAntAlgorithm(int pheromoneInc, int extraPheromoneInc, int nAnts, int maxIterations, int maxIterationsNoChanges) { NAnts = nAnts; PheromoneInc = pheromoneInc; ExtraPheromoneInc = extraPheromoneInc; MaxIterations = maxIterations; MaxIterationsNoChanges = maxIterationsNoChanges; BestAnt = new QapAnt {PathCost = int.MaxValue, VisitedVetecies = new List<IVertex>()}; }
public void Run() { _currentAnt = new QapAnt(); _currentIteration = 0; _currentIterationNoChanges = 0; BestAnt = new QapAnt {PathCost = Int32.MaxValue, VisitedVetecies = new List<IVertex>()}; _resultBuilder = new StringBuilder(); _resultBuilder.Append("Start\n"); while (!IsFinished()) { CreateAnts(); IList<IVertex> newPath = AntsTravel(); _currentAnt = new QapAnt {VisitedVetecies = newPath, PathCost = 0}; ComputePathCost(_currentAnt); LocalSearch(_currentAnt); if (!IsNewBestPath(_currentAnt)) { _currentIterationNoChanges++; } else _currentIterationNoChanges = 0; UpdateGeneration(); _currentIteration++; Ants.Clear(); } }
public void LocalSearch(QapAnt ant) { // set of moves, numbered from 0 to index int[] move = new int[Ants.Count * (Ants.Count - 1) / 2]; int nMoves = 0; for (int i = 0; i < Ants.Count - 1; i++) { for (int j = i + 1; j < Ants.Count; j++) { move[nMoves++] = Ants.Count * i + j; } } bool isImproved = true; for (int scan = 0; scan < 2 && isImproved; scan++) { isImproved = false; for (int i = 0; i < nMoves - 1; i++) { int x = GetPermutationalIndex(i + 1, nMoves - 1); int y = move[i]; move[i] = move[x]; move[x] = y; } for (int i = 0; i < nMoves; i++) { int r = move[i] / Ants.Count; int s = move[i] % Ants.Count; int moveCost = ComputeMoveCost(r, s, ant.VisitedVetecies); if (moveCost < 0) { ant.PathCost += moveCost; int y = ant.VisitedVetecies[r].Number; ant.VisitedVetecies[r].Number = ant.VisitedVetecies[s].Number; ant.VisitedVetecies[s].Number = y; isImproved = true; } } } }
public bool IsNewBestPath(QapAnt ant) { int bestOne = BestAnt.PathCost; int newOne = ant.PathCost; if (newOne < bestOne) { _flag = 2; BestAnt.VisitedVetecies = (IList<IVertex>)DeepObjectClone(ant.VisitedVetecies); BestAnt.PathCost = ant.PathCost; NewResultUpdate(); return true; } if (newOne == bestOne) { _flag = 1; } else { _flag = 0; } return false; }
public int ComputePathCost(QapAnt ant) { int cost = 0; for (int i = 0; i < ant.VisitedVetecies.Count; i++) { for (int j = 0; j < ant.VisitedVetecies.Count; j++) { cost += (int) (Graph.Edges[i, j].Mark.Path.Value * Graph.Flows[ant.VisitedVetecies[i].Number, ant.VisitedVetecies[j].Number]); } } ant.PathCost = cost; return cost; }