Question
Asked 15th Mar, 2014

Does anyone have code for ant colony optimization algorithm in java?

I need to use my project

Most recent answer

package de.jungblut.antcolony;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import cern.jet.random.Uniform;
public final class AntColonyOptimization {
// greedy
public static final double ALPHA = -0.2d;
// rapid selection
public static final double BETA = 9.6d;
// heuristic parameters
public static final double Q = 0.0001d; // somewhere between 0 and 1
public static final double PHEROMONE_PERSISTENCE = 0.3d; // between 0 and 1
public static final double INITIAL_PHEROMONES = 0.8d; // can be anything
// use power of 2
public static final int numOfAgents = 2048 * 20;
private static final int poolSize = Runtime.getRuntime().availableProcessors();
private Uniform uniform;
private final ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
private final ExecutorCompletionService agentCompletionService = new ExecutorCompletionService(
threadPool);
final double[][] matrix;
final double[][] invertedMatrix;
private final double[][] pheromones;
private final Object[][] mutexes;
public AntColonyOptimization() throws IOException {
// read the matrix
matrix = readMatrixFromFile();
invertedMatrix = invertMatrix();
pheromones = initializePheromones();
mutexes = initializeMutexObjects();
// (double min, double max, int seed)
uniform = new Uniform(0, matrix.length – 1, (int) System.currentTimeMillis());
}
private final Object[][] initializeMutexObjects() {
final Object[][] localMatrix = new Object[matrix.length][matrix.length];
int rows = matrix.length;
for (int columns = 0; columns < matrix.length; columns++) {
for (int i = 0; i = 0.0d) {
pheromones[x][y] = result;
} else {
pheromones[x][y] = 0;
}
}
}
private final double calculatePheromones(double current, double newPheromone) {
final double result = (1 – AntColonyOptimization.PHEROMONE_PERSISTENCE) * current
+ newPheromone;
return result;
}
final void adjustPheromone(int[] way, double newPheromone) {
synchronized (pheromones) {
for (int i = 0; i < way.length – 1; i++) {
pheromones[way[i]][way[i + 1]] = calculatePheromones(
pheromones[way[i]][way[i + 1]], newPheromone);
}
pheromones[way[way.length – 1]][way[0]] = calculatePheromones(
pheromones[way.length – 1][way[0]], newPheromone);
}
}
private final double[][] initializePheromones() {
final double[][] localMatrix = new double[matrix.length][matrix.length];
int rows = matrix.length;
for (int columns = 0; columns < matrix.length; columns++) {
for (int i = 0; i < rows; i++) {
localMatrix[columns][i] = INITIAL_PHEROMONES;
}
}
return localMatrix;
}
private final double[][] readMatrixFromFile() throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(new File("files/berlin52.tsp")));
final LinkedList records = new LinkedList();
boolean readAhead = false;
String line;
while ((line = br.readLine()) != null) {
if (line.equals(“EOF”)) {
break;
}
if (readAhead) {
String[] split = line.trim().split(” “);
records.add(new Record(Double.parseDouble(split[1].trim()), Double
.parseDouble(split[2].trim())));
}
if (line.equals(“NODE_COORD_SECTION”)) {
readAhead = true;
}
}
br.close();
final double[][] localMatrix = new double[records.size()][records.size()];
int rIndex = 0;
for (Record r : records) {
int hIndex = 0;
for (Record h : records) {
localMatrix[rIndex][hIndex] = calculateEuclidianDistance(r.x, r.y, h.x, h.y);
hIndex++;
}
rIndex++;
}
return localMatrix;
}
private final double[][] invertMatrix() {
double[][] local = new double[matrix.length][matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
local[i][j] = invertDouble(matrix[i][j]);
}
}
return local;
}
private final double invertDouble(double distance) {
if (distance == 0)
return 0;
else
return 1.0d / distance;
}
private final double calculateEuclidianDistance(double x1, double y1, double x2, double y2) {
return Math.abs((Math.sqrt(Math.pow(x2 – x1, 2) + Math.pow(y2 – y1, 2))));
}
final double start() throws InterruptedException, ExecutionException {
WalkedWay bestDistance = null;
int agentsSend = 0;
int agentsDone = 0;
int agentsWorking = 0;
for (int agentNumber = 0; agentNumber = poolSize) {
WalkedWay way = agentCompletionService.take().get();
if (bestDistance == null || way.distance < bestDistance.distance) {
bestDistance = way;
System.out.println("Agent returned with new best distance of: " + way.distance);
}
agentsDone++;
agentsWorking–;
}
}
final int left = agentsSend – agentsDone;
System.out.println("Waiting for " + left + " agents to finish their random walk!");
for (int i = 0; i < left; i++) {
WalkedWay way = agentCompletionService.take().get();
if (bestDistance == null || way.distance < bestDistance.distance) {
bestDistance = way;
System.out.println("Agent returned with new best distance of: " + way.distance);
}
}
threadPool.shutdownNow();
System.out.println("Found best so far: " + bestDistance.distance);
System.out.println(Arrays.toString(bestDistance.way));
return bestDistance.distance;
}
private final int getGaussianDistributionRowIndex() {
return uniform.nextInt();
}
static class Record {
double x;
double y;
public Record(double x, double y) {
super();
this.x = x;
this.y = y;
}
}
static class WalkedWay {
int[] way;
double distance;
public WalkedWay(int[] way, double distance) {
super();
this.way = way;
this.distance = distance;
}
}
public static void main(String[] args) throws IOException, InterruptedException,
ExecutionException {
long start = System.currentTimeMillis();
AntColonyOptimization antColonyOptimization = new AntColonyOptimization();
antColonyOptimization.start();
System.out.println("Took: " + (System.currentTimeMillis() – start) + " ms!");
}
}
1 Recommendation

All Answers (5)

Amir Sedaghatdoost
Texas A&M University
Thanks Mr. Karthikeyan for this question.
I will also glad if anyone have the FORTRAN code too.
Tousif Zaman
Worcester Polytechnic Institute
Carlos Gavidia-Calderon
Alan Turing Institute
I know is kind of late, but this Java Framework might be useful: http://cptanalatriste.github.io/isula/
1 Recommendation
package de.jungblut.antcolony;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import cern.jet.random.Uniform;
public final class AntColonyOptimization {
// greedy
public static final double ALPHA = -0.2d;
// rapid selection
public static final double BETA = 9.6d;
// heuristic parameters
public static final double Q = 0.0001d; // somewhere between 0 and 1
public static final double PHEROMONE_PERSISTENCE = 0.3d; // between 0 and 1
public static final double INITIAL_PHEROMONES = 0.8d; // can be anything
// use power of 2
public static final int numOfAgents = 2048 * 20;
private static final int poolSize = Runtime.getRuntime().availableProcessors();
private Uniform uniform;
private final ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
private final ExecutorCompletionService agentCompletionService = new ExecutorCompletionService(
threadPool);
final double[][] matrix;
final double[][] invertedMatrix;
private final double[][] pheromones;
private final Object[][] mutexes;
public AntColonyOptimization() throws IOException {
// read the matrix
matrix = readMatrixFromFile();
invertedMatrix = invertMatrix();
pheromones = initializePheromones();
mutexes = initializeMutexObjects();
// (double min, double max, int seed)
uniform = new Uniform(0, matrix.length – 1, (int) System.currentTimeMillis());
}
private final Object[][] initializeMutexObjects() {
final Object[][] localMatrix = new Object[matrix.length][matrix.length];
int rows = matrix.length;
for (int columns = 0; columns < matrix.length; columns++) {
for (int i = 0; i = 0.0d) {
pheromones[x][y] = result;
} else {
pheromones[x][y] = 0;
}
}
}
private final double calculatePheromones(double current, double newPheromone) {
final double result = (1 – AntColonyOptimization.PHEROMONE_PERSISTENCE) * current
+ newPheromone;
return result;
}
final void adjustPheromone(int[] way, double newPheromone) {
synchronized (pheromones) {
for (int i = 0; i < way.length – 1; i++) {
pheromones[way[i]][way[i + 1]] = calculatePheromones(
pheromones[way[i]][way[i + 1]], newPheromone);
}
pheromones[way[way.length – 1]][way[0]] = calculatePheromones(
pheromones[way.length – 1][way[0]], newPheromone);
}
}
private final double[][] initializePheromones() {
final double[][] localMatrix = new double[matrix.length][matrix.length];
int rows = matrix.length;
for (int columns = 0; columns < matrix.length; columns++) {
for (int i = 0; i < rows; i++) {
localMatrix[columns][i] = INITIAL_PHEROMONES;
}
}
return localMatrix;
}
private final double[][] readMatrixFromFile() throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(new File("files/berlin52.tsp")));
final LinkedList records = new LinkedList();
boolean readAhead = false;
String line;
while ((line = br.readLine()) != null) {
if (line.equals(“EOF”)) {
break;
}
if (readAhead) {
String[] split = line.trim().split(” “);
records.add(new Record(Double.parseDouble(split[1].trim()), Double
.parseDouble(split[2].trim())));
}
if (line.equals(“NODE_COORD_SECTION”)) {
readAhead = true;
}
}
br.close();
final double[][] localMatrix = new double[records.size()][records.size()];
int rIndex = 0;
for (Record r : records) {
int hIndex = 0;
for (Record h : records) {
localMatrix[rIndex][hIndex] = calculateEuclidianDistance(r.x, r.y, h.x, h.y);
hIndex++;
}
rIndex++;
}
return localMatrix;
}
private final double[][] invertMatrix() {
double[][] local = new double[matrix.length][matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
local[i][j] = invertDouble(matrix[i][j]);
}
}
return local;
}
private final double invertDouble(double distance) {
if (distance == 0)
return 0;
else
return 1.0d / distance;
}
private final double calculateEuclidianDistance(double x1, double y1, double x2, double y2) {
return Math.abs((Math.sqrt(Math.pow(x2 – x1, 2) + Math.pow(y2 – y1, 2))));
}
final double start() throws InterruptedException, ExecutionException {
WalkedWay bestDistance = null;
int agentsSend = 0;
int agentsDone = 0;
int agentsWorking = 0;
for (int agentNumber = 0; agentNumber = poolSize) {
WalkedWay way = agentCompletionService.take().get();
if (bestDistance == null || way.distance < bestDistance.distance) {
bestDistance = way;
System.out.println("Agent returned with new best distance of: " + way.distance);
}
agentsDone++;
agentsWorking–;
}
}
final int left = agentsSend – agentsDone;
System.out.println("Waiting for " + left + " agents to finish their random walk!");
for (int i = 0; i < left; i++) {
WalkedWay way = agentCompletionService.take().get();
if (bestDistance == null || way.distance < bestDistance.distance) {
bestDistance = way;
System.out.println("Agent returned with new best distance of: " + way.distance);
}
}
threadPool.shutdownNow();
System.out.println("Found best so far: " + bestDistance.distance);
System.out.println(Arrays.toString(bestDistance.way));
return bestDistance.distance;
}
private final int getGaussianDistributionRowIndex() {
return uniform.nextInt();
}
static class Record {
double x;
double y;
public Record(double x, double y) {
super();
this.x = x;
this.y = y;
}
}
static class WalkedWay {
int[] way;
double distance;
public WalkedWay(int[] way, double distance) {
super();
this.way = way;
this.distance = distance;
}
}
public static void main(String[] args) throws IOException, InterruptedException,
ExecutionException {
long start = System.currentTimeMillis();
AntColonyOptimization antColonyOptimization = new AntColonyOptimization();
antColonyOptimization.start();
System.out.println("Took: " + (System.currentTimeMillis() – start) + " ms!");
}
}
1 Recommendation

Similar questions and discussions

Has anyone else received this email? Is this the scam?
Question
70 answers
  • Fariha KanwalFariha Kanwal
Dear Prof. Fariha Kanwal
I hope this letter finds you well. It is my honor to extend to you an invitation to speak at our upcoming scholar's conference for researchers and students across Asia.
Your expertise and achievements are most impressive. Our participants would greatly benefit from your insights and knowledge. This event aims to connect bright minds like yourself with the next generation of researchers and foster meaningful collaboration.
The conference will be held virtually over Zoom. We kindly request a 30-40 minute presentation from you, focusing on your notable work and advice to young academics. Should the situation allow, we plan to also host an in-person lecture in the future.
Rest assured, we will handle all coordination leading up to the event and provide an honorarium for your time. This is an impactful opportunity to share your wisdom and grow your network across Asia.
I sincerely hope you will consider this invitation. Please let me know if you have any questions. I look forward to your reply.
Best regards,
Risa Wada
Workshop on Search and Selection in Continuous Domains - WCCI/CEC2024
Discussion
6 replies
  • Stephen ChenStephen Chen
A recurring theme in metaheuristics research is to consider the balance between Exploration and Exploitation. An often forgotten area of research is the effect of Selection on Search/Exploration. A method of selection that rejects all exploratory search solutions can cause any metaheuristic to stall, and elitist fitness-based selection in continuous domains often behaves in this fashion. A building body of research suggests that alternate methods of selection are required, and that these methods of selection should be specifically matched to the employed methods of exploration.
We invite all interested researchers to join our workshop to expand upon related research topics such as
  • Benchmark problems for exploration
  • Methods for exploration (and their verification)
  • Observation of optima hopping behaviours in metaheuristics
  • Comparison of selection in combinatorial and continuous domains
  • Measurements of stall and/or selection errors
  • Non-fitness based methods of selection (for exploration)
  • A review of selection
Workshop participation is open to all conference attendees. If you would like to present relevant research during a plenary session of the workshop, please contact the organizers:
Stephen Chen, Associate Professor, School of Information Technology, York University, Canada
Marjan Mernik, Professor, Faculty of Electrical Engineering and Computer Science, University of Maribor, Slovenia
We look forward to seeing you in Yokohama!

Related Publications

Article
Full-text available
Breast cancer is the second leading cause of mortality among women. Early and accurate detection plays a crucial role in lowering its mortality rate. Timely detection and classification of breast cancer enable the most effective treatment. Convolutional neural networks (CNNs) have significantly improved the accuracy of tumor detection and classific...
Got a technical question?
Get high-quality answers from experts.