Skip to content

Commit 3abb98e

Browse files
maibinKevinGilmore
authored andcommitted
Final fixes on ACO (eugenp#1339)
* Ant Colony Optimization * Updated code for Ant Colony
1 parent 1871023 commit 3abb98e

23 files changed

Lines changed: 226 additions & 200 deletions

‎algorithms/pom.xml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
<junit.version>4.12</junit.version>
1010
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
1111
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
12+
<lombok.version>1.16.12</lombok.version>
1213
</properties>
1314

1415
<dependencies>
@@ -18,6 +19,12 @@
1819
<version>${junit.version}</version>
1920
<scope>test</scope>
2021
</dependency>
22+
<dependency>
23+
<groupId>org.projectlombok</groupId>
24+
<artifactId>lombok</artifactId>
25+
<version>${lombok.version}</version>
26+
<scope>provided</scope>
27+
</dependency>
2128
</dependencies>
2229

2330
<build>

core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java renamed to algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,14 @@
99

1010
public class RunAlgorithm {
1111

12-
public static void main(String[] args) {
12+
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
1313
Scanner in = new Scanner(System.in);
1414
System.out.println("Run algorithm:");
1515
System.out.println("1 - Simulated Annealing");
1616
System.out.println("2 - Slope One");
1717
System.out.println("3 - Simple Genetic Algorithm");
1818
System.out.println("4 - Ant Colony");
19+
System.out.println("5 - Dijkstra");
1920
int decision = in.nextInt();
2021
switch (decision) {
2122
case 1:
@@ -33,6 +34,9 @@ public static void main(String[] args) {
3334
AntColonyOptimization antColony = new AntColonyOptimization(21);
3435
antColony.startAntOptimization();
3536
break;
37+
case 5:
38+
System.out.println("Please run the DijkstraAlgorithmTest.");
39+
break;
3640
default:
3741
System.out.println("Unknown option");
3842
break;

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

File renamed without changes.

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

File renamed without changes.

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

File renamed without changes.

core-java/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java renamed to algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java

File renamed without changes.
Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
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+
}

core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java renamed to algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java

File renamed without changes.

core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java renamed to algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Population.java

File renamed without changes.

core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java renamed to algorithms/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java

File renamed without changes.

0 commit comments

Comments
 (0)