|
| 1 | +package com.baeldung.algorithms.ga.ant_colony; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | +import java.util.OptionalInt; |
| 7 | +import java.util.Random; |
| 8 | +import java.util.stream.IntStream; |
| 9 | + |
| 10 | +public class AntColonyOptimization { |
| 11 | + |
| 12 | + private double c = 1.0; |
| 13 | + private double alpha = 1; |
| 14 | + private double beta = 5; |
| 15 | + private double evaporation = 0.5; |
| 16 | + private double Q = 500; |
| 17 | + private double antFactor = 0.8; |
| 18 | + private double randomFactor = 0.01; |
| 19 | + |
| 20 | + private int maxIterations = 1000; |
| 21 | + |
| 22 | + private int numberOfCities; |
| 23 | + private int numberOfAnts; |
| 24 | + private double graph[][]; |
| 25 | + private double trails[][]; |
| 26 | + private List<Ant> ants = new ArrayList<>(); |
| 27 | + private Random random = new Random(); |
| 28 | + private double probabilities[]; |
| 29 | + |
| 30 | + private int currentIndex; |
| 31 | + |
| 32 | + private int[] bestTourOrder; |
| 33 | + private double bestTourLength; |
| 34 | + |
| 35 | + public AntColonyOptimization(int noOfCities) { |
| 36 | + graph = generateRandomMatrix(noOfCities); |
| 37 | + numberOfCities = graph.length; |
| 38 | + numberOfAnts = (int) (numberOfCities * antFactor); |
| 39 | + |
| 40 | + trails = new double[numberOfCities][numberOfCities]; |
| 41 | + probabilities = new double[numberOfCities]; |
| 42 | + IntStream.range(0, numberOfAnts) |
| 43 | + .forEach(i -> ants.add(new Ant(numberOfCities))); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Generate initial solution |
| 48 | + */ |
| 49 | + public double[][] generateRandomMatrix(int n) { |
| 50 | + double[][] randomMatrix = new double[n][n]; |
| 51 | + IntStream.range(0, n) |
| 52 | + .forEach(i -> IntStream.range(0, n) |
| 53 | + .forEach(j -> randomMatrix[i][j] = Math.abs(random.nextInt(100) + 1))); |
| 54 | + return randomMatrix; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Perform ant optimization |
| 59 | + */ |
| 60 | + public void startAntOptimization() { |
| 61 | + IntStream.rangeClosed(1, 3) |
| 62 | + .forEach(i -> { |
| 63 | + System.out.println("Attempt #" + i); |
| 64 | + solve(); |
| 65 | + }); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Use this method to run the main logic |
| 70 | + */ |
| 71 | + public int[] solve() { |
| 72 | + setupAnts(); |
| 73 | + clearTrails(); |
| 74 | + IntStream.range(0, maxIterations) |
| 75 | + .forEach(i -> { |
| 76 | + moveAnts(); |
| 77 | + updateTrails(); |
| 78 | + updateBest(); |
| 79 | + }); |
| 80 | + System.out.println("Best tour length: " + (bestTourLength - numberOfCities)); |
| 81 | + System.out.println("Best tour order: " + Arrays.toString(bestTourOrder)); |
| 82 | + return bestTourOrder.clone(); |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Prepare ants for the simulation |
| 87 | + */ |
| 88 | + private void setupAnts() { |
| 89 | + IntStream.range(0, numberOfAnts) |
| 90 | + .forEach(i -> { |
| 91 | + ants.forEach(ant -> { |
| 92 | + ant.clear(); |
| 93 | + ant.visitCity(-1, random.nextInt(numberOfCities)); |
| 94 | + }); |
| 95 | + }); |
| 96 | + currentIndex = 0; |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * At each iteration, move ants |
| 101 | + */ |
| 102 | + private void moveAnts() { |
| 103 | + IntStream.range(currentIndex, numberOfCities - 1) |
| 104 | + .forEach(i -> { |
| 105 | + ants.forEach(ant -> ant.visitCity(currentIndex, selectNextCity(ant))); |
| 106 | + currentIndex++; |
| 107 | + }); |
| 108 | + } |
| 109 | + |
| 110 | + /** |
| 111 | + * Select next city for each ant |
| 112 | + */ |
| 113 | + private int selectNextCity(Ant ant) { |
| 114 | + int t = random.nextInt(numberOfCities - currentIndex); |
| 115 | + if (random.nextDouble() < randomFactor) { |
| 116 | + OptionalInt cityIndex = IntStream.range(0, numberOfCities) |
| 117 | + .filter(i -> i == t && !ant.visited(i)) |
| 118 | + .findFirst(); |
| 119 | + if (cityIndex.isPresent()) { |
| 120 | + return cityIndex.getAsInt(); |
| 121 | + } |
| 122 | + } |
| 123 | + calculateProbabilities(ant); |
| 124 | + double r = random.nextDouble(); |
| 125 | + double total = 0; |
| 126 | + for (int i = 0; i < numberOfCities; i++) { |
| 127 | + total += probabilities[i]; |
| 128 | + if (total >= r) { |
| 129 | + return i; |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + throw new RuntimeException("There are no other cities"); |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Calculate the next city picks probabilites |
| 138 | + */ |
| 139 | + public void calculateProbabilities(Ant ant) { |
| 140 | + int i = ant.trail[currentIndex]; |
| 141 | + double pheromone = 0.0; |
| 142 | + for (int l = 0; l < numberOfCities; l++) { |
| 143 | + if (!ant.visited(l)) { |
| 144 | + pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta); |
| 145 | + } |
| 146 | + } |
| 147 | + for (int j = 0; j < numberOfCities; j++) { |
| 148 | + if (ant.visited(j)) { |
| 149 | + probabilities[j] = 0.0; |
| 150 | + } else { |
| 151 | + double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta); |
| 152 | + probabilities[j] = numerator / pheromone; |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + /** |
| 158 | + * Update trails that ants used |
| 159 | + */ |
| 160 | + private void updateTrails() { |
| 161 | + for (int i = 0; i < numberOfCities; i++) { |
| 162 | + for (int j = 0; j < numberOfCities; j++) { |
| 163 | + trails[i][j] *= evaporation; |
| 164 | + } |
| 165 | + } |
| 166 | + for (Ant a : ants) { |
| 167 | + double contribution = Q / a.trailLength(graph); |
| 168 | + for (int i = 0; i < numberOfCities - 1; i++) { |
| 169 | + trails[a.trail[i]][a.trail[i + 1]] += contribution; |
| 170 | + } |
| 171 | + trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution; |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + /** |
| 176 | + * Update the best solution |
| 177 | + */ |
| 178 | + private void updateBest() { |
| 179 | + if (bestTourOrder == null) { |
| 180 | + bestTourOrder = ants.get(0).trail; |
| 181 | + bestTourLength = ants.get(0) |
| 182 | + .trailLength(graph); |
| 183 | + } |
| 184 | + for (Ant a : ants) { |
| 185 | + if (a.trailLength(graph) < bestTourLength) { |
| 186 | + bestTourLength = a.trailLength(graph); |
| 187 | + bestTourOrder = a.trail.clone(); |
| 188 | + } |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + /** |
| 193 | + * Clear trails after simulation |
| 194 | + */ |
| 195 | + private void clearTrails() { |
| 196 | + IntStream.range(0, numberOfCities) |
| 197 | + .forEach(i -> { |
| 198 | + IntStream.range(0, numberOfCities) |
| 199 | + .forEach(j -> trails[i][j] = c); |
| 200 | + }); |
| 201 | + } |
| 202 | + |
| 203 | +} |
0 commit comments