Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • arzba/optialgos
1 result
Show changes
Commits on Source (2)
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "java",
"name": "Current File",
"request": "launch",
"mainClass": "${file}"
},
{
"type": "java",
"name": "cvrp_ls",
"request": "launch",
"mainClass": "cvrp_ls",
"projectName": "optialgos_92db6011",
"args": ["C:\\Users\\Jule Behrens\\Documents\\JonahAlgos\\optialgos\\src\\instances\\Loggi-n401-k23.vrp", "taboo_search", "14400"]
}
]
}
\ No newline at end of file
# Optimierungsalgorithmen für schwere Systeme WiSe 24/25
### Author: Jonah Schierding
## Problem Set 1 Aufgabe 4
## Problem Set 2 Aufgabe 1
......@@ -10,4 +11,13 @@ Im src-Ordner liegen die Quelldateien und kompilierten Dateien. Aufruf erfolgt d
(TYPE : CVRP,
EDGE_WEIGHT_TYPE : EXPLICIT,
EDGE_WEIGHT_FORMAT : LOWER_ROW)
zeigen muss.
\ No newline at end of file
zeigen muss.
Das Programm gibt die Kosten für die Initial ermittelte Lösung mit einem Greedy-Approach und die mit basic local search ohne Zeitlimit optimierte Lösung und anschließend die Lösungen selbst im .sol Format aus.
Alternativ kann ein Algorithmus spezifiziert werden mit "java cvrp_ls *absolutePath* *algorithm*". Dabei sind die Optionen für *algorithm* "basic_local_serach", "taboo_search" und "ant_colony".
Für "taboo_search" und "ant_colony" muss zudem eine maximale Laufzeit (integer) für die Optimierung in vollen Sekunden angegeben werden ("java cvrp_ls *absolutePath* *algorithm* *maxTimeInSeconds*"). Für "basic_local_search" ist das optional.
"taboo_search" kann optional ein weiterer Parameter mitgegeben werden: Die Anzahl der Taboos (integer). Der Standardwert liegt bei *Anzahl der Knoten/2* abgerundet. Ein möglicher Aufruf wäre: "java cvrp_ls *absolutePath* taboo_search *maxTimeInSeconds* *numberOfTaboos*".
"ant_colony" können optional weitere Parameter mitgegeben werden: Die Anzahl der Ameisen (Standardwert: *Anzahl der Knoten x 5*), Anzahl der Pheromone, die eine Ameise zu einer Kante addiert (Standardwert: 10, integer), Anzahl der Pheromone, die in einer minor round verloren gehen (Standardwert: 1, integer), ob die Pheromone zwischen major rounds zurückgesetzt werden sollen (Standard: 0 (nein), integer[0 = nein, alles andere = ja]) und die Strategie zur Auswahl des ersten Knotens der Ameisen ("depot" oder "even", mit Standard "even"). Dabei bedeutet "depot", dass alle Ameisen vom Depot aus starten, während "even" bedeutet, dass die Ameisen gleichmäßig verteilt auf den Knoten starten, wobei ein erster Weg vom Depot aus impliziert ist. Ein möglicher Aufruf wäre: "java cvrp_ls *absolutePath* ant_colony *maxTimeInSeconds* *numberOfAnts* *numberOfPheromonesAdded* *numberOfPheromonesDecayes* *resetPheromonesBetweenMajorRounds* *antDeployStrategy*".
\ No newline at end of file
No preview for this file type
File added
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
......@@ -3,26 +3,308 @@ import java.util.Arrays;
public class Algorithms {
int pheromonesStrength = -1;
String antStartStrategy = "";
int pheromonesDecayStrength = -1;
String algorithmType;
public Algorithms(String algorithmType){
boolean resetPheromones = false;
int maxRuntimeInSeconds = -1;
int numberOfAnts = -1;
int numberOfTaboos = -1;
public Algorithms(){}
public Algorithms(String algorithmType, String[] optionalParams) throws Exception{
this.algorithmType = algorithmType;
if(algorithmType == null || algorithmType.equals("")){
this.algorithmType = "primitive_local_search";
try {
this.maxRuntimeInSeconds = Integer.valueOf(optionalParams[0]);
} catch (Exception e) {
}
//checks if algorithm specific parameters are feasible and assigns them
switch (algorithmType) {
case "none":
this.algorithmType = "basic_local_search";
break;
case "ant_colony":
try {
this.numberOfAnts = Integer.valueOf(optionalParams[1]);
this.pheromonesStrength = Integer.valueOf(optionalParams[2]);
this.pheromonesDecayStrength = Integer.valueOf(optionalParams[3]);
if(Integer.valueOf(optionalParams[4]) == 0){
this.resetPheromones = false;
} else {
this.resetPheromones = true;
}
this.antStartStrategy = optionalParams[4];
} catch (Exception e) {
}
if(maxRuntimeInSeconds <= 0)
throw new Exception();
if(this.pheromonesStrength <= 0)
System.out.println("Using standard value for pheromone strength.");
if(this.antStartStrategy.equals(""))
System.out.println("Using standard value for ant start strategy.");
if(this.pheromonesDecayStrength <= 0)
System.out.println("Using standard value for pheromone decay strength.");
if(this.numberOfAnts <= 0)
System.out.println("Using standard value for number of ants.");
break;
case "taboo_search":
try {
this.numberOfTaboos = Integer.valueOf(optionalParams[1]);
} catch (Exception e) {
}
if(maxRuntimeInSeconds <= 0)
throw new Exception();
if(this.numberOfTaboos <= 0)
System.out.println("Using standard value for number of Taboos."
);
break;
default:
break;
}
}
public Solution generateSolution(Instance instance){
return generateInitialSolutionGreedy(instance);
switch (this.algorithmType) {
case "greedy":
return generateInitialSolutionGreedy(instance);
case "ant_colony":
//setting default parameters if needed
if(this.numberOfAnts <= 0)
numberOfAnts = Math.multiplyExact(instance.getDimension(),5);
if(this.pheromonesDecayStrength <= 0)
pheromonesDecayStrength = 1;
if(this.pheromonesStrength <= 0)
pheromonesStrength = 10;
if(this.antStartStrategy.equals(""))
antStartStrategy = "even";
return generateInitialSolutionAnt(instance);
default:
return null;
}
}
public Solution generateSolution(Solution solution){
switch (this.algorithmType) {
case "primitive_local_search":
case "basic_local_search":
return localSearch(solution);
case "greedy":
return generateInitialSolutionGreedy(solution.instance);
case "taboo_search":
//setting default parameters if needed
if(this.numberOfTaboos <= 0)
numberOfTaboos = solution.instance.getDimension()/3;
return tabooSearch(solution);
case "ant_colony":
return generateSolution(solution.instance);
default:
return null;
return localSearch(solution);
}
}
private Solution tabooSearch(Solution solution) {
int[] state = {2,0,0,0};
int newBestCount = 0;
int time =0;
Solution currentSolution = solution;
Solution bestSolutionSeen = solution;
long start = System.currentTimeMillis();
long end = start + this.maxRuntimeInSeconds * 1000;
Solution possibleBetterNeighbor = getOtherNeighbor(state, bestSolutionSeen);
Solution currentBestNeighbor = possibleBetterNeighbor;
int currentBestNeighborNodeChanged = 2;
ArrayList<Integer> taboos = new ArrayList<>();
while(maxRuntimeInSeconds > 0 && System.currentTimeMillis()<end){
if(System.currentTimeMillis()>start+1000 && time == 0){
try{System.out.println("1 Sekunde: " + bestSolutionSeen.getCost());}catch(Exception e){}
time++;
}
if(System.currentTimeMillis()>start+10000 && time == 1){
try{System.out.println("10 Sekunde: " + bestSolutionSeen.getCost());}catch(Exception e){}
time++;
}
if(System.currentTimeMillis()>start+60000 && time == 2){
try{System.out.println("60 Sekunde: " + bestSolutionSeen.getCost());}catch(Exception e){}
time++;
}
try {
if(possibleBetterNeighbor.getCost() < currentBestNeighbor.getCost()){
currentBestNeighbor = possibleBetterNeighbor;
currentBestNeighborNodeChanged = state[0];
}
} catch (Exception e) {
}
//permutate state to get another neighbor which is not taboo
state[0]++;
while(taboos.contains(state[0])){
state[0]++;
}
if(state[0] > bestSolutionSeen.instance.getDimension()){
//System.out.println("reset extracted node");
state[0] = 2;
state[2]++;
if(state[2] > bestSolutionSeen.tours[state[1]].length-1){
//System.out.println("reset position");
state[2] = 0;
state[1]++;
if(state[1] > bestSolutionSeen.tours.length-1){
//System.out.println("reset tours");
state[1] = 0;
state[3]++;
//choose minimal after all neighbors are seen, update taboos, best solution see so far and current solution
if(state[3] == 2){
currentSolution = currentBestNeighbor;
//System.out.println("Made a step, taboos: "+taboos.size());
try {
if(currentSolution.getCost() < bestSolutionSeen.getCost()){
bestSolutionSeen = currentSolution;
System.out.println("Found new best solution "+(++newBestCount) + ": All "+taboos.size()+" taboos dropped");
taboos.clear();
} else {
taboos.add(currentBestNeighborNodeChanged);
if(taboos.size() > numberOfTaboos){
taboos.remove(0);
}
}
} catch (Exception e) {
}
int[] help = {2,0,0,0};
state = help;
currentBestNeighbor = getOtherNeighbor(state, currentSolution);
}
}
}
}
possibleBetterNeighbor = getOtherNeighbor(state, currentSolution);
}
System.out.println("terminated by time limit");
return bestSolutionSeen;
}
private Solution generateInitialSolutionAnt(Instance instance) {
Solution bestSeenSolution = null;
int time = 0;
int newBestSolutionCount = 0;
int[][] pheromonesOnEdge = new int[instance.getDimension()+1][instance.getDimension()+1];
//initialize all edges with phermone score 1
for (int i = 0; i < pheromonesOnEdge.length; i++) {
for (int j = 0; j < pheromonesOnEdge[i].length; j++) {
pheromonesOnEdge[i][j] = 1;
}
}
long start = System.currentTimeMillis();
long end = start + this.maxRuntimeInSeconds * 1000;
while(maxRuntimeInSeconds > 0 && System.currentTimeMillis()<end){
//if optional parameter is set, reset pheromones inbetween major rounds
if(System.currentTimeMillis()>start+1000 && time == 0){
try{System.out.println("1 Sekunde: " + bestSeenSolution.getCost());}catch(Exception e){}
time++;
}
if(System.currentTimeMillis()>start+10000 && time == 1){
try{System.out.println("10 Sekunde: " + bestSeenSolution.getCost());}catch(Exception e){}
time++;
}
if(System.currentTimeMillis()>start+60000 && time == 2){
try{System.out.println("60 Sekunde: " + bestSeenSolution.getCost());}catch(Exception e){}
time++;
}
if(resetPheromones) {
for (int i = 0; i < pheromonesOnEdge.length; i++) {
for (int j = 0; j < pheromonesOnEdge[i].length; j++) {
pheromonesOnEdge[i][j] = 1;
}
}
}
ArrayList<Ant> ants = new ArrayList<Ant>();
for (int i = 0; i < numberOfAnts; i++) {
switch (antStartStrategy) {
case "depot":
ants.add(new Ant(instance));
break;
case "even":
default:
ants.add(new Ant(instance, i+1));
break;
}
}
while(!antsAreAllDone(ants)){
ArrayList<int[]> walkedEdges = new ArrayList<int[]>();
//let ants do one minor round
for (Ant ant : ants) {
int[] walkedEdge = ant.makeStepInMinorRound(pheromonesOnEdge);
walkedEdges.add(walkedEdge);
}
//update pheromones after minor round
for (int[] walkedEdge : walkedEdges) {
if(walkedEdge != null){
if(walkedEdge[0] < walkedEdge[1]){
pheromonesOnEdge[walkedEdge[1]][walkedEdge[0]] += pheromonesStrength;
} else {
pheromonesOnEdge[walkedEdge[0]][walkedEdge[1]] += pheromonesStrength;
}
}
}
//let pheromones decay (not under 1)
for (int i = 0; i < pheromonesOnEdge.length; i++) {
for (int j = 0; j < pheromonesOnEdge[i].length; j++) {
pheromonesOnEdge[i][j] -= pheromonesDecayStrength;
if(pheromonesOnEdge[i][j]<1){
pheromonesOnEdge[i][j] = 1;
}
}
}
}
//check if ant has discovered new best solution
for (Ant ant : ants) {
Solution antsSolution = ant.toSolution();
if(bestSeenSolution == null){
System.out.println("Found new best solution "+(++newBestSolutionCount));
bestSeenSolution = antsSolution;
} else {
try {
if(bestSeenSolution.getCost() > antsSolution.getCost()){
System.out.println("Found new best solution "+(++newBestSolutionCount));
bestSeenSolution = antsSolution;
}
} catch (Exception e) {
}
}
}
}
return bestSeenSolution;
}
private boolean antsAreAllDone(ArrayList<Ant> ants){
boolean allDone = true;
for (Ant ant : ants) {
if(!ant.done){
allDone = false;
break;
}
}
return allDone;
}
//primitive greedy Approach
......@@ -85,7 +367,6 @@ public class Algorithms {
i++;
}
solution.tours = convertedTours;
solution.getCost();
return solution;
}
......@@ -94,40 +375,55 @@ public class Algorithms {
Solution currentBestSolution = solution;
int[] state = {2,0,0,0};
Solution possibleBetterSolution = getOtherNeighbor(state, currentBestSolution);
int newBestCount = 0;
int newBestSolutionCount = 0;
long start = System.currentTimeMillis();
long end = start + this.maxRuntimeInSeconds * 1000;
//tries all neighbors as possibleBetterSolution, if better solution found, change currentBestSolution and search from there
//terminates when it cannot find a better solution in its neighbarhood
while (possibleBetterSolution != null) {
if(possibleBetterSolution.getCost() < currentBestSolution.getCost()){
currentBestSolution = possibleBetterSolution;
int[] help = {2,0,0,0};
state = help;
possibleBetterSolution = getOtherNeighbor(state, currentBestSolution);
System.out.println("found new best solution "+(++newBestCount));
}else{
//permutate state to get another neighbor
state[0]++;
if(state[0] > currentBestSolution.instance.getDimension()){
//System.out.println("reset extracted node");
state[0] = 2;
state[2]++;
if(state[2] > currentBestSolution.tours[state[1]].length-1){
//System.out.println("reset position");
state[2] = 0;
state[1]++;
if(state[1] > currentBestSolution.tours.length-1){
//System.out.println("reset tours");
state[1] = 0;
state[3]++;
if(state[3] == 2){
break;
//stop if max execution time has exceeded
if(maxRuntimeInSeconds > 0 && System.currentTimeMillis()>end){
System.out.println("terminated by time limit");
break;
}
try {
if(possibleBetterSolution.getCost() < currentBestSolution.getCost()){
currentBestSolution = possibleBetterSolution;
int[] help = {2,0,0,0};
state = help;
possibleBetterSolution = getOtherNeighbor(state, currentBestSolution);
System.out.println("Found new best solution "+(++newBestSolutionCount));
}else{
//permutate state to get another neighbor
state[0]++;
if(state[0] > currentBestSolution.instance.getDimension()){
//System.out.println("reset extracted node");
state[0] = 2;
state[2]++;
if(state[2] > currentBestSolution.tours[state[1]].length-1){
//System.out.println("reset position");
state[2] = 0;
state[1]++;
if(state[1] > currentBestSolution.tours.length-1){
//System.out.println("reset tours");
state[1] = 0;
state[3]++;
//stop if all neighbors are worse/local optimum is reached
if(state[3] == 2){
System.out.println("terminated by local optimum");
break;
}
}
}
}
}
possibleBetterSolution = getOtherNeighbor(state, currentBestSolution);
}
possibleBetterSolution = getOtherNeighbor(state, currentBestSolution);
}
} catch (Exception e) {
}
}
......
File added
import java.util.ArrayList;
import java.util.Arrays;
public class Ant {
Instance instance;
Node currentNode;
ArrayList<Node> currentTour = new ArrayList<Node>();
ArrayList<ArrayList<Node>> tours = new ArrayList<ArrayList<Node>>();
ArrayList<Node> notVisitedNodes;
boolean done = false;
public Ant(Instance instance){
this.instance = instance;
notVisitedNodes = new ArrayList<Node>(Arrays.asList(instance.getNodes()));
notVisitedNodes.remove(instance.getDepot());
currentNode = instance.getDepot();
notVisitedNodes.remove(0);
}
public Ant(Instance instance, int startNodeNumber){
Node currentNode;
currentNode = instance.getDepot();
this.instance = instance;
notVisitedNodes = new ArrayList<Node>(Arrays.asList(instance.getNodes()));
for (Node node : notVisitedNodes) {
if(node != null && node.number == (startNodeNumber%instance.getDimension())+1){
currentNode = node;
break;
}
}
notVisitedNodes.remove(instance.getDepot());
notVisitedNodes.remove(0);
notVisitedNodes.remove(currentNode);
this.currentNode = currentNode;
currentTour.add(currentNode);
}
public int[] makeStepInMinorRound(int[][] pheromonesOnEdge){
//if ant is done with tour return null, else return edge, that she walked
if(this.done){
return null;
}
Node nextNode = null;
double currentProbability = 0;
ArrayList<double[]> probabilities = new ArrayList<double[]>();
if(currentNode.depot){
currentTour = new ArrayList<Node>();
} else {
double distance;
double pheromones;
if(currentNode.number < instance.getDepot().number){
distance = instance.getEdgeWeights()[instance.getDepot().number][currentNode.number];
pheromones = pheromonesOnEdge[instance.getDepot().number][currentNode.number];
} else {
distance = instance.getEdgeWeights()[currentNode.number][instance.getDepot().number];
pheromones = pheromonesOnEdge[instance.getDepot().number][currentNode.number];
}
double probability = pheromones / distance;
double[] probabilityInterval= new double[3];
probabilityInterval[0] = currentProbability;
probabilityInterval[1] = currentProbability+probability;
probabilityInterval[2] = instance.getDepot().number;
probabilities.add(probabilityInterval);
currentProbability += probability;
}
for (Node node : notVisitedNodes) {
if(node.demand + sumOfDemands(currentTour) <= instance.getTruckCapacity()){
double distance;
double pheromones;
if(currentNode.number < node.number){
distance = instance.getEdgeWeights()[node.number][currentNode.number];
pheromones = pheromonesOnEdge[node.number][currentNode.number];
} else {
distance = instance.getEdgeWeights()[currentNode.number][node.number];
pheromones = pheromonesOnEdge[node.number][currentNode.number];
}
double probability = pheromones / (distance+1);
double[] probabilityInterval= new double[3];
probabilityInterval[0] = currentProbability;
probabilityInterval[1] = currentProbability+probability;
probabilityInterval[2] = node.number;
probabilities.add(probabilityInterval);
currentProbability += probability;
}
}
double randomNumber = Math.random()*currentProbability;
int nextNodeNumber = -1;
for (double[] interval : probabilities) {
if(randomNumber >= interval[0] && randomNumber < interval[1]){
nextNodeNumber = (int)interval[2];
}
}
if(nextNodeNumber == instance.getDepot().number){
tours.add(currentTour);
nextNode = instance.getDepot();
if(notVisitedNodes.size() == 0){
this.done = true;
}
} else {
for (Node node : notVisitedNodes) {
if(node.number == nextNodeNumber){
currentTour.add(node);
nextNode = node;
notVisitedNodes.remove(node);
break;
}
}
}
int[] walkedEdge = {currentNode.number,nextNode.number};
currentNode = nextNode;
return walkedEdge;
}
private int sumOfDemands(ArrayList<Node> currentTour){
int demand = 0;
for (Node node : currentTour) {
demand += node.demand;
}
return demand;
}
public Solution toSolution(){
Solution sol = new Solution(instance);
Node[][] tours = new Node[this.tours.size()][];
int i = 0;
for (ArrayList<Node> tour : this.tours) {
tours[i] = new Node[tour.size()];
tours[i] = tour.toArray(tours[i]);
i++;
}
sol.tours = tours;
return sol;
}
}
No preview for this file type
......@@ -13,8 +13,9 @@ public class Instance {
private Node depot;
private int optimalCost;
public Instance(String fileLocation){
//import instance of cvrp from file at fileLocation, lower Marix of distances
public Instance(){}
public Instance(String fileLocation) throws Exception{
//import instance of cvrp from file at fileLocation and optimal solutioncost from sol file in same folder, lower Marix of distances
try {
File file = new File(fileLocation);
Scanner scanner = new Scanner(file);
......@@ -67,20 +68,19 @@ public class Instance {
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred at import.");
e.printStackTrace();
System.err.println("An error occurred at import, please check if your .vrp file fulfills the readme-conditions and the path is correct.");
throw new Exception();
}
try {
File file = new File(fileLocation.replace(".vrp", ".sol"));
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
if(data.contains("COST")) this.optimalCost = Integer.valueOf(data.replace("COST", "").trim());
if(data.contains("Cost")) this.optimalCost = Integer.valueOf(data.replace("Cost", "").trim());
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred at import.");
e.printStackTrace();
System.out.println("No .sol file found for optimal solution.");
}
}
......
......@@ -14,6 +14,6 @@ public class Node {
public void setDepot(){this.depot = true;}
public void setDemand(Integer demand){this.demand = demand;}
public String toString(){
return ""+this.number;
return ""+this.number+"("+this.demand+")";
}
}
No preview for this file type
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashSet;
//represents a feasible solution to a instance
public class Solution {
Instance instance;
Node[][] tours;
private int cost;
private boolean feasible = false;
public Solution(Instance instance){
this.instance = instance;
}
public int getCost(){
public boolean isFeasible() throws Exception{
ArrayList<Node> allVisitedNodes = new ArrayList<Node>();
for (Node[] tour : this.tours) {
int tourCost = 0;
int tourDemand = 0;
Node lastNode = instance.getDepot();
for (Node node : tour) {
if(node != null){
tourDemand += node.demand;
allVisitedNodes.add(node);
if(lastNode.number > node.number){
tourCost += instance.getEdgeWeights()[lastNode.number][node.number];
} else {
tourCost += instance.getEdgeWeights()[node.number][lastNode.number];
}
lastNode = node;
}
}
tourCost += instance.getEdgeWeights()[lastNode.number][instance.getDepot().number];
//check if tour is in capacity limit
if(tourDemand > instance.getTruckCapacity()) {
throw new Exception("capacity problem ("+tourDemand + " greater " +instance.getTruckCapacity()+")");
}
}
//check if nodes are duplicates
if(allVisitedNodes.size() != new HashSet<Node>(allVisitedNodes).size()) {
throw new Exception("duplicate problem");
}
//check if right number of nodes is in all tours
if(allVisitedNodes.size() != instance.getDimension()-1) {
throw new Exception("not all nodes problem");
}
return this.feasible = true;
}
public int getCost() throws Exception{
isFeasible();
this.cost = 0;
for (Node[] tour : tours) {
Node lastNode = instance.getDepot();
......@@ -23,7 +64,6 @@ public class Solution {
}
lastNode = node;
} catch (Exception e) {
// TODO: handle exception
}
......@@ -33,7 +73,7 @@ public class Solution {
return this.cost;
};
public String toString(){
String s = "name: "+instance.getName()+ "\n" + "cost: " + cost + "\nTours: ";
String s = "name: "+instance.getName()+ "\n" + "cost: " + cost + "feasible: " + feasible + "\nTours: ";
for (Node[] tour : tours) {
s += "\n[";
for (Node node : tour) {
......@@ -55,4 +95,27 @@ public class Solution {
copy.tours = toursCopy;
return copy;
}
public String toSol(){
String rep = "";
for (int i = 0; i < tours.length; i++) {
rep += "Route #"+(i+1)+":";
for (Node node : tours[i]) {
try {
rep += " "+node.number;
} catch (Exception e) {
}
}
rep += "\n";
}
try {
rep += "Cost " + this.getCost();
} catch (Exception e) {
rep = "not feasible: " + e.getMessage() + "\n" + rep;
}
return rep;
}
}
\ No newline at end of file
No preview for this file type
......@@ -3,33 +3,68 @@
public class cvrp_ls {
public static void main(String[] args) throws Exception {
String fileLocation = "";
String algorithm ="";
int maxRuntimeInSeconds = -1;
String algorithm ="none";
String[] optionalParams = new String[args.length-2];
System.arraycopy(args, 2, optionalParams, 0, args.length-2);
try {
fileLocation = args[0];
algorithm = args[1];
maxRuntimeInSeconds = Integer.valueOf(args[2]);
} catch (Exception e) {
System.out.println("Something seems to be wrong with the given parameters");
}
//create new instance from file
Instance instance = new Instance(fileLocation);
Instance instance = new Instance();
try {
instance = new Instance(fileLocation);
} catch (Exception e) {
System.err.println("Import of instance failed critically");
e.printStackTrace();
System.exit(1);
}
//create initial Greedy Solution
Algorithms greedy = new Algorithms("greedy");
Algorithms greedy = new Algorithms("greedy", optionalParams);
Solution greedySolution = greedy.generateSolution(instance);
System.out.println("Greedy done");
//optimize with chosen algorithm
Algorithms chosen = new Algorithms(algorithm);
Algorithms chosen = new Algorithms();
try {
chosen = new Algorithms(algorithm, optionalParams);
} catch (Exception e) {
System.err.println("Not all parameters for this algorithm seem to be right");
}
Solution optimizedSolution = chosen.generateSolution(greedySolution);
//print results
System.out.println("Instance name"+" & "+"Cost initial Solution"+" & "+"Cost optimized solution"+" & " + "Cost optimal solution");
System.out.println(instance.getName()+" & "+greedySolution.getCost()+" & "+optimizedSolution.getCost()+" & "+instance.getOptimalCost());
if(chosen.algorithmType.equals( "ant_colony") || chosen.algorithmType.equals("greedy")){
System.out.println(("\nSolved with "+chosen.algorithmType+" with a maximum runtime of approximately "+chosen.maxRuntimeInSeconds+" seconds!").replace("-1", "unlimited"));
if(chosen.algorithmType.equals("ant_colony"))
System.out.println("Ants: "+chosen.numberOfAnts+", Phermones Added: "+chosen.pheromonesStrength+", Pheromones Decayed: "+ chosen.pheromonesDecayStrength + ", Deploy Strategy: "+chosen.antStartStrategy+", Reset after Major round: "+chosen.resetPheromones);
System.out.println("Instance name"+" & "+" "+" & "+"Cost solution ("+chosen.algorithmType+")"+" & " + "Cost upper bound (100%)"+ " \\\\");
if(instance.getOptimalCost() > 0)
System.out.println(instance.getName()+" & " + " & "+optimizedSolution.getCost()+" ("+(float)optimizedSolution.getCost()/(float)instance.getOptimalCost()*100+"%) & "+instance.getOptimalCost() + " \\\\");
else
System.out.println(instance.getName()+" & "+greedySolution.getCost()+" & "+optimizedSolution.getCost()+" & "+ " \\\\");
System.out.println("\n Solution:\n"+optimizedSolution.toSol());
} else {
System.out.println(("\nAfter initial greedy Approach, optimized with "+chosen.algorithmType+" with a maximum runtime of approximately "+chosen.maxRuntimeInSeconds+" seconds!").replace("-1", "unlimited"));
System.out.println("Instance name"+" & "+"Cost initial Solution"+" & "+"Cost optimized solution ("+chosen.algorithmType+")"+" & " + "Cost upper bound (100%)"+ " \\\\");
if(instance.getOptimalCost() > 0)
System.out.println(instance.getName()+" & "+greedySolution.getCost()+" ("+(float)greedySolution.getCost()/(float)instance.getOptimalCost()*100+"%) & "+optimizedSolution.getCost()+" ("+(float)optimizedSolution.getCost()/(float)instance.getOptimalCost()*100+"%) & "+instance.getOptimalCost() + " \\\\");
else
System.out.println(instance.getName()+" & "+greedySolution.getCost()+" & "+optimizedSolution.getCost()+" & "+ " \\\\");
System.out.println("\n Initial solution:\n"+greedySolution.toSol());
System.out.println("\n Optimized solution:\n"+optimizedSolution.toSol());
}
}
}