Skip to content

Commit 29882a1

Browse files
maibinKevinGilmore
authored andcommitted
Ant Colony Optimization (eugenp#1237)
1 parent 5930f9d commit 29882a1

8 files changed

Lines changed: 282 additions & 5 deletions

File tree

‎core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
import java.util.Scanner;
44

5-
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
5+
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
6+
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
67
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
78
import com.baeldung.algorithms.slope_one.SlopeOne;
89

@@ -14,6 +15,7 @@ public static void main(String[] args) {
1415
System.out.println("1 - Simulated Annealing");
1516
System.out.println("2 - Slope One");
1617
System.out.println("3 - Simple Genetic Algorithm");
18+
System.out.println("4 - Ant Colony");
1719
int decision = in.nextInt();
1820
switch (decision) {
1921
case 1:
@@ -27,6 +29,10 @@ public static void main(String[] args) {
2729
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
2830
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
2931
break;
32+
case 4:
33+
AntColonyOptimization antColony = new AntColonyOptimization(21);
34+
antColony.startAntOptimization();
35+
break;
3036
default:
3137
System.out.println("Unknown option");
3238
break;

core-java/src/main/java/com/baeldung/algorithms/annealing/City.java renamed to core-java/src/main/java/com/baeldung/algorithms/ga/annealing/City.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.algorithms.annealing;
1+
package com.baeldung.algorithms.ga.annealing;
22

33
import lombok.Data;
44

core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java renamed to core-java/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.algorithms.annealing;
1+
package com.baeldung.algorithms.ga.annealing;
22

33
public class SimulatedAnnealing {
44

core-java/src/main/java/com/baeldung/algorithms/annealing/Travel.java renamed to core-java/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.algorithms.annealing;
1+
package com.baeldung.algorithms.ga.annealing;
22

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

‎core-java/src/test/java/com/baeldung/algorithms/SimulatedAnnealingTest.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import org.junit.Assert;
44
import org.junit.Test;
55

6-
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
6+
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
77

88
public class SimulatedAnnealingTest {
99

0 commit comments

Comments
 (0)