├── CI Project Report.pdf ├── CVRP - Conventional ACO.py ├── CVRP - Genetic Algorithm.py ├── CVRP - Sequential ACO.py ├── CVRP - Visualization.py ├── CVRP-TW - Visualization.py ├── Datasets ├── A-n32-k5.txt ├── A-n34-k5.txt ├── A-n37-k5.txt ├── A-n44-k7.txt ├── A-n45-k6.txt ├── A-n48-k7.txt ├── A-n55-k9.txt ├── A-n60-k9.txt ├── A-n65-k9.txt ├── A-n69-k9.txt └── A-n80-k10.txt ├── LICENSE └── README.md /CI Project Report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abdullahcdkee/Vehicle-Routing-Problem/a65f7903ed0f24ea021af6b9e6da14a8a0e23392/CI Project Report.pdf -------------------------------------------------------------------------------- /CVRP - Conventional ACO.py: -------------------------------------------------------------------------------- 1 | ########################################################################################### 2 | ########################################################################################### 3 | ########################################################################################### 4 | ################ Code by Abdullah Siddiqui (ms03586@st.habib.edu.pk) ##################### 5 | ########################################################################################### 6 | ########################################################################################### 7 | ########################################################################################### 8 | 9 | import getopt 10 | import math 11 | import random 12 | import numpy 13 | from functools import reduce 14 | import sys 15 | from scipy.spatial.distance import pdist, squareform 16 | import numpy as np 17 | import sys 18 | import networkx as nx 19 | import random 20 | import matplotlib.pyplot as plt 21 | import math 22 | import pandas as pd 23 | import numpy as np 24 | import random 25 | import matplotlib.pyplot as plt 26 | import math 27 | 28 | 29 | # obtain the route traversed by one ant i.e. one possible solution while considering capacity requirements 30 | def single_ant_route(nodelist, graph_edges, nodecap, pheromone_trail, max_cap, alpha, beta): 31 | nodes = nodelist.copy() 32 | route = [] 33 | 34 | while len(nodes)!=0 : 35 | trip = [] 36 | 37 | # ant initialized at a random node 38 | node = int(np.random.choice(nodes)) 39 | ant_cap = max_cap - nodecap[node] 40 | trip.append(int(node)) 41 | nodes.remove(int(node)) 42 | 43 | while len(nodes) != 0: 44 | # define transition probabilities from node i to j 45 | transition_probabilities = [] 46 | for vertex in nodes: 47 | transition_probabilities.append( (( pheromone_trail[ int(min(vertex, node)), int(max(vertex, node)) ] )**alpha) * (Q/graph_edges[ int(min(vertex, node)), int(max(vertex, node)) ])**beta ) 48 | 49 | transition_probabilities = transition_probabilities/np.sum(transition_probabilities) 50 | 51 | cumsum = [] 52 | a = 0 53 | for k in transition_probabilities: 54 | a += k 55 | cumsum.append(a) 56 | 57 | # select node depending on transition probabilities 58 | random_num = random.uniform(0,1) 59 | 60 | if (len(cumsum) == 1): 61 | node = nodes[0] 62 | 63 | elif len(cumsum) == 2: 64 | if random_num < 0.5: 65 | node = nodes[0] 66 | else: 67 | node = nodes[1] 68 | 69 | else: 70 | for i in range(len(cumsum) - 1): 71 | if (random_num > cumsum[i] and random_num <= cumsum[i+1]): 72 | node = nodes[i+1] 73 | break 74 | elif (random_num <= cumsum[0]): 75 | node = nodes[0] 76 | break 77 | 78 | ant_cap = ant_cap - nodecap[node] 79 | 80 | if (ant_cap>0): 81 | if node not in trip: 82 | trip.append(int(node)) 83 | if (int(node) in nodes): 84 | nodes.remove(int(node)) 85 | else: 86 | break 87 | 88 | route.append(trip) 89 | 90 | return route 91 | 92 | 93 | # obtain fitness value for the specified route i.e. total distance traversed by an ant to explore all nodes 94 | def fitness_function(route, graph_edges): 95 | fitness = 0 96 | complete_route = [1] 97 | 98 | for trip in route: 99 | for node in trip: 100 | complete_route.append(int(node)) 101 | complete_route.append(1) 102 | 103 | for i in range(len(complete_route)-1): 104 | fitness += graph_edges[min(int(complete_route[i]), int(complete_route[i+1])), max(int(complete_route[i]), int(complete_route[i+1])) ] 105 | 106 | return fitness 107 | 108 | 109 | # define dictionaries detailing distances between nodes and the pheromone trail between nodes 110 | def create_graph(nodelist, nodecoords, nodecap): 111 | graph_edges = {} 112 | pheromone_trail = {} 113 | for i in nodelist: 114 | for j in nodelist: 115 | distance = np.sqrt( (nodecoords[i][0] - nodecoords[j][0])**2 + (nodecoords[i][1] - nodecoords[j][1])**2 ) 116 | graph_edges[ int(min( int(i), int(j) )), int(max(int(i), int(j))) ] = distance 117 | 118 | if i!=j: 119 | pheromone_trail[ int(min(int(i), int(j) )), int(max(int(i), int(j) )) ] = 1 120 | 121 | return graph_edges, pheromone_trail 122 | 123 | 124 | # update pheromone trail based on standard formula 125 | def update_pheromone_trail(pheromone_trail, routes, best_solution, rho, Q, sigma): 126 | fitness = [] 127 | for value in routes: 128 | fitness.append(value[1]) 129 | 130 | avg_fitness = sum(fitness)/len(routes) 131 | 132 | # standard pheromone update equation factoring in the evaporation rate 133 | for key, value in pheromone_trail.items(): 134 | pheromone_trail[key] = (rho + Q/avg_fitness)*value 135 | 136 | routes.sort(key = lambda x:x [1]) 137 | 138 | if (best_solution != []): 139 | 140 | if (routes[0][1] < best_solution[1]): 141 | best_solution = routes[0] 142 | 143 | # consider effect of elitist ants on updating pheromone value 144 | for trip in best_solution[0]: 145 | for i in range(len(trip) - 1): 146 | pheromone_trail[ (min(trip[i], trip[i+1]), max(trip[i], trip[i+1])) ] += sigma/best_solution[1] 147 | 148 | else: 149 | 150 | best_solution = routes[0] 151 | 152 | # incorporate effect of elitist ant strategy on pheromone trail 153 | for i in range(sigma): 154 | trips = routes[i][0] 155 | fitness = routes[i][1] 156 | 157 | for trip in trips: 158 | for j in range(len(trip) - 1): 159 | pheromone_trail[ (min(trip[j], trip[j+1]), max(trip[j], trip[j+1])) ] += (sigma - (j+1)) / (fitness**(j+1)) 160 | 161 | return best_solution 162 | 163 | 164 | # solve the vrp problem using aco 165 | def aco_solver(nodelist, nodecoords, nodecap, max_cap, iterations, alpha, beta, Q, sigma, rho, Q, ants): 166 | graph_edges, pheromone_trail = create_graph(nodelist, nodecoords, nodecap) 167 | best_solution = [] 168 | BFS = [] 169 | AFS = [] 170 | 171 | # run algorithm for specified number of iterations to find optimal solution 172 | for i in range(iterations): 173 | routes = [] 174 | avg_fitness = [] 175 | 176 | # create a colony of ants i.e. possible solutions in each iteration 177 | for j in range(ants): 178 | route = single_ant_route(nodelist, graph_edges, nodecap, pheromone_trail, max_cap, alpha, beta) 179 | fitness = fitness_function(route, graph_edges) 180 | routes.append([route, fitness]) 181 | avg_fitness.append(fitness) 182 | 183 | average_fitness = sum(avg_fitness)/len(avg_fitness) 184 | best_solution = update_pheromone_trail(pheromone_trail, routes, best_solution, rho, Q, sigma) 185 | BFS.append(best_solution[1]) 186 | AFS.append(average_fitness) 187 | print("Best: ", best_solution[1], " Avg: ", average_fitness) 188 | 189 | return best_solution, BFS, AFS 190 | 191 | 192 | # Read data file 193 | infile = open('A-n37-k5.txt', 'r') 194 | 195 | # Read instance header 196 | (infile.readline().strip().split()) 197 | (infile.readline().strip().split()) 198 | (infile.readline().strip().split()) 199 | dim = int(infile.readline().strip().split()[-1]) 200 | infile.readline().strip().split() 201 | max_cap = int(infile.readline().strip().split()[-1]) 202 | journeys = int(infile.readline().strip().split()[-1]) 203 | infile.readline().strip().split() 204 | 205 | nodecoords = {} 206 | nodecap = {} 207 | nodelist = [] 208 | 209 | for i in range(0, dim): 210 | line = infile.readline() 211 | if (line != ''): 212 | n,x,y = line.strip().split() 213 | 214 | if (n!=1): 215 | nodelist.append(int(n)) 216 | 217 | nodecoords[int(n)] = [float(x), float(y)] 218 | else: 219 | break 220 | 221 | infile.readline() 222 | 223 | for i in range(0, dim): 224 | line = infile.readline() 225 | if (line != ''): 226 | n,c = line.strip().split() 227 | nodecap[int(n)] = int(c) 228 | else: 229 | break 230 | 231 | # Define parameter values 232 | alpha = 5 233 | beta = 8 234 | sigma = 6 235 | rho = 0.9 236 | Q = 10 237 | iterations = 1000 238 | ants = dim 239 | 240 | # solve vrp using aco 241 | best_sol, BFS, AFS = aco_solver(nodelist, nodecoords, nodecap, max_cap, iterations, alpha, beta, Q, sigma, rho, Q, ants) 242 | 243 | # plot the results obtained 244 | plt.title('Fitness vs Iteration') 245 | plt.plot([i for i in range(iterations)], BFS, label="BFS") 246 | plt.ylabel('Fitness') 247 | plt.xlabel('Iterations') 248 | 249 | plt.title('Fitness vs Iteration') 250 | plt.plot([i for i in range(iterations)], AFS, label="AFS") 251 | plt.ylabel('Fitness') 252 | plt.xlabel('Iterations') 253 | plt.legend(framealpha=1, frameon=True); 254 | plt.show() 255 | 256 | ########################################################################################### 257 | ########################################################################################### 258 | ########################################################################################### 259 | ################ Code by Abdullah Siddiqui (ms03586@st.habib.edu.pk) ##################### 260 | ########################################################################################### 261 | ########################################################################################### 262 | ########################################################################################### 263 | 264 | -------------------------------------------------------------------------------- /CVRP - Genetic Algorithm.py: -------------------------------------------------------------------------------- 1 | ########################################################################################### 2 | ########################################################################################### 3 | ########################################################################################### 4 | ################ Code by Abdullah Siddiqui (ms03586@st.habib.edu.pk) ##################### 5 | ########################################################################################### 6 | ########################################################################################### 7 | ########################################################################################### 8 | 9 | from scipy.spatial.distance import pdist, squareform 10 | import numpy as np 11 | import sys 12 | import networkx as nx 13 | import random 14 | import matplotlib.pyplot as plt 15 | import math 16 | import numpy as np 17 | import random 18 | import matplotlib.pyplot as plt 19 | import math 20 | 21 | 22 | # Class that represents the genetic algorithm and associated functions 23 | class EA: 24 | 25 | def __init__(self, nodelist, nodecoords, nodecap, size, journeys, max_cap, mutation_rate = 0.5): 26 | self.nodelist = nodelist 27 | self.nodecoords = nodecoords 28 | self.nodecap = nodecap 29 | self.population_size = size 30 | self.mutation_rate = mutation_rate 31 | self.population = [] 32 | self.journeys = journeys 33 | self.max_cap = max_cap 34 | self.mutation_valid = 0 35 | self.mutation_invalid = 0 36 | self.initial_solution = [] 37 | 38 | self.initialize_population() 39 | 40 | 41 | # Initialize population randomly while following capacity requirements 42 | def initialize_population(self): 43 | 44 | candidate = nodelist.copy() 45 | 46 | for i in range(self.population_size): 47 | route = [] 48 | 49 | while (len(route)!= self.journeys): 50 | random.shuffle(candidate) 51 | cap = 0 52 | nodesvisited = 0 53 | journey = [] 54 | route = [] 55 | 56 | for i in candidate: 57 | cap += self.nodecap[i-1] 58 | 59 | if cap > max_cap: 60 | route.append(journey) 61 | journey = [] 62 | cap = self.nodecap[i-1] 63 | 64 | journey.append(i) 65 | nodesvisited += 1 66 | 67 | if journey != []: 68 | route.append(journey) 69 | 70 | self.population.append(route) 71 | 72 | self.initial_solution = self.population[1] 73 | self.initial_solution_fitness = self.individual_fitness(self.initial_solution) 74 | 75 | 76 | # Calculate euclidean distance between nodes 77 | def calculate_distance(self, node1, node2): 78 | distance = math.sqrt( (self.nodecoords[node1][0] - self.nodecoords[node2][0])**2 + (self.nodecoords[node1][1] - self.nodecoords[node2][1])**2 ) 79 | return distance 80 | 81 | 82 | # Calculate fitness for every member in the population 83 | # By default fitness is being maximized, for minimization the value's reciprocal is stored 84 | def fitness_func(self): 85 | self.fitness = [] 86 | 87 | for i in range(len(self.population)): 88 | if (not self.is_valid(self.population[i])): 89 | self.population[i] = self.shuffle_route(self.population[i]) 90 | 91 | individual_fitness = self.individual_fitness(self.population[i]) 92 | self.fitness.append(1/individual_fitness) 93 | 94 | maximum = 0 95 | idx = 0 96 | 97 | for i in range(0,len(self.fitness)): 98 | if self.fitness[i] > maximum: 99 | maximum = self.fitness[i] 100 | idx = i 101 | 102 | self.max_solution = self.population[idx] 103 | self.max_fitness = maximum 104 | 105 | 106 | # Calculate fitness of an individual i.e. total distance travelled 107 | def individual_fitness(self, candidate): 108 | individual_fitness = 0 109 | 110 | for j in range(len(candidate)): 111 | first_journey_node = candidate[j][0] 112 | individual_fitness += self.calculate_distance(0, first_journey_node) 113 | 114 | for k in range(len(candidate[j]) - 1): 115 | idx1, idx2 = candidate[j][k], candidate[j][k+1] 116 | individual_fitness += self.calculate_distance(idx1, idx2) 117 | 118 | last_journey_node = candidate[j][-1] 119 | individual_fitness += self.calculate_distance(last_journey_node, 0) 120 | 121 | return individual_fitness 122 | 123 | 124 | # Check if route is valid i.e. meets capacity requierments 125 | def is_valid(self, candidate): 126 | cap = 0 127 | for journey in candidate: 128 | for j in journey: 129 | cap += self.nodecap[j-1] 130 | 131 | if cap > self.max_cap: 132 | return False 133 | cap = 0 134 | 135 | return True 136 | 137 | 138 | # If route does not meet capacity requirements, shuffle it stochastically to ensure it does 139 | def shuffle_route(self, org_candidate): 140 | 141 | candidate = [] 142 | for i in org_candidate: 143 | for j in i: 144 | candidate.append(j) 145 | 146 | random.shuffle(candidate) 147 | route = [] 148 | 149 | while (len(route)!= self.journeys): 150 | random.shuffle(candidate) 151 | cap = 0 152 | nodesvisited = 0 153 | journey = [] 154 | route = [] 155 | 156 | for i in candidate: 157 | cap += self.nodecap[i-1] 158 | 159 | if cap > max_cap: 160 | route.append(journey) 161 | journey = [] 162 | cap = self.nodecap[i-1] 163 | 164 | journey.append(i) 165 | nodesvisited += 1 166 | 167 | if journey != []: 168 | route.append(journey) 169 | 170 | return route 171 | 172 | 173 | # Select either parents or survivors to proceed to the next stage through a variety of selection schemes 174 | # Num is the size of individuals to select and scheme defines the type of selection scheme 175 | def selection(self, num, scheme, survivor): 176 | self.selected_candidates = [] 177 | 178 | if scheme == "Random": 179 | 180 | for i in range(num): 181 | random_num = random.randrange(len(self.population)) 182 | self.selected_candidates.append(self.population[random_num]) 183 | 184 | 185 | elif scheme == "FPS": 186 | 187 | norm_fitness = [] 188 | sum_fitness = sum(self.fitness) 189 | 190 | for i in self.fitness: 191 | norm_fitness.append(i/sum_fitness) 192 | 193 | cum_prob = [] 194 | a = 0 195 | 196 | for k in norm_fitness: 197 | a += k 198 | cum_prob.append(a) 199 | 200 | np.array(cum_prob) 201 | 202 | for i in range(num): 203 | random_num = random.uniform(0,1) 204 | 205 | for j in range(len(cum_prob)-1): 206 | if (random_num > cum_prob[j] and random_num <= cum_prob[j+1]): 207 | self.selected_candidates.append(self.population[j+1]) 208 | break 209 | elif (random_num <= cum_prob[0]): 210 | self.selected_candidates.append(self.population[0]) 211 | break 212 | 213 | 214 | elif scheme == "Truncation": 215 | fitness_copy = np.copy(self.fitness) 216 | 217 | numbered_fitness_copy = list(enumerate(fitness_copy)) 218 | numbered_fitness_copy.sort(key=lambda x:x[1]) 219 | numbered_fitness_copy = numbered_fitness_copy[::-1] 220 | 221 | for i in range(num): 222 | index = numbered_fitness_copy[i][0] 223 | self.selected_candidates.append(self.population[index]) 224 | 225 | 226 | elif scheme == "RBS": 227 | 228 | fitness_copy = np.copy(self.fitness) 229 | numbered_fitness_copy = list(enumerate(fitness_copy)) 230 | numbered_fitness_copy.sort(key=lambda x:x[1]) 231 | 232 | rank_dic = dict() 233 | rank_lst = [] 234 | for i in range(1,len(self.fitness)+1): 235 | rank_dic[i] = numbered_fitness_copy[i-1] 236 | rank_lst.append(i) 237 | 238 | norm_rank_dic = dict() 239 | norm_lst = [] 240 | for j in range(1,len(self.fitness)+1): 241 | norm_rank_dic[rank_lst[j-1]/sum(rank_lst)] = rank_dic[j] 242 | norm_lst.append(rank_lst[j-1]/sum(rank_lst)) 243 | 244 | cum_lst = [] 245 | a = 0 246 | for p in norm_lst: 247 | a+=p 248 | cum_lst.append(a) 249 | 250 | for k in range(num): 251 | random_num2 = random.uniform(0,1) 252 | 253 | for m in range (len(cum_lst)-1): 254 | 255 | if (random_num2 > cum_lst[m] and random_num2 <= cum_lst[m+1]): 256 | fitness = norm_rank_dic[norm_lst[m+1]][1] 257 | index = norm_rank_dic[norm_lst[m+1]][0] 258 | self.selected_candidates.append(self.population[index]) 259 | break 260 | elif random_num2 <= cum_lst[0]: 261 | fitness = norm_rank_dic[norm_lst[0]][1] 262 | index = norm_rank_dic[norm_lst[0]][0] 263 | self.selected_candidates.append(self.population[index]) 264 | break 265 | 266 | 267 | elif scheme == 'BT': 268 | for i in range(num): 269 | cand_dic = dict() 270 | 271 | for j in range(2): 272 | rand = random.randrange(len(self.population)) 273 | cand_dic[rand] = self.fitness[rand] 274 | 275 | max_index = max(cand_dic, key=cand_dic.get) 276 | self.selected_candidates.append(self.population[max_index]) 277 | 278 | 279 | else: 280 | print("Please enter a valid scheme") 281 | 282 | 283 | if survivor == True: 284 | self.population = np.array(self.selected_candidates) 285 | else: 286 | self.selected_candidates = np.array(self.selected_candidates) 287 | 288 | 289 | # Create new generation of off springs 290 | def crossover(self): 291 | selected_candidates_copy = np.copy(self.selected_candidates) 292 | selected_candidates_copy = selected_candidates_copy.tolist() 293 | temp_offsprings = [] 294 | 295 | #Two point crossover 296 | for i in range(0,len(selected_candidates_copy)-1,2): 297 | parent1 = selected_candidates_copy[i] 298 | parent2 = selected_candidates_copy[i+1] 299 | 300 | child1 = self.create_child(parent1, parent2) 301 | child2 = self.create_child(parent2, parent1) 302 | 303 | offspring1 = np.array(child1) 304 | offspring2 = np.array(child2) 305 | temp_offsprings.append(offspring1) 306 | temp_offsprings.append(offspring2) 307 | 308 | 309 | self.offsprings = np.array(temp_offsprings) 310 | 311 | 312 | # Create child by performing two point crossover on parents 313 | def create_child(self,org_parent1, org_parent2): 314 | 315 | parent1 = [] 316 | parent2 = [] 317 | 318 | for i in org_parent1: 319 | for j in i: 320 | parent1.append(j) 321 | 322 | for i in org_parent2: 323 | for j in i: 324 | parent2.append(j) 325 | 326 | crossover_point1 = int(random.randint(0,len(parent1))) 327 | crossover_point2 = int(random.randint(0,len(parent1))) 328 | 329 | while crossover_point2 == crossover_point1: 330 | crossover_point2 = int(random.randint(0,len(parent1))) 331 | 332 | start = min(crossover_point1, crossover_point2) 333 | end = max(crossover_point1, crossover_point2) 334 | insertion = parent1[start:end] 335 | stored = [] 336 | child = [None]*len(parent1) 337 | 338 | j = 0 339 | for i in range(len(parent1)): 340 | 341 | if i>=start and i2): 357 | random.shuffle(candidate) 358 | 359 | cap = 0 360 | journey = [] 361 | route = [] 362 | 363 | for i in candidate: 364 | cap += self.nodecap[i-1] 365 | 366 | if cap > max_cap: 367 | route.append(journey) 368 | journey = [] 369 | cap = self.nodecap[i-1] 370 | 371 | journey.append(i) 372 | 373 | if journey != []: 374 | route.append(journey) 375 | 376 | attempts += 1 377 | 378 | org_child = route 379 | 380 | return org_child 381 | 382 | 383 | # mutate the offsprings by either swaps or inversion 384 | def mutation(self): 385 | for i in range(len(self.offsprings)): 386 | random_num = random.uniform(0,1) 387 | 388 | if random_num < self.mutation_rate: 389 | repeat = True 390 | 391 | while (repeat): 392 | repeat = False 393 | random_journey_idx = random.randint(0, self.journeys-1) 394 | while (len(self.offsprings[i][random_journey_idx])<2): 395 | random_journey_idx = random.randint(0, self.journeys-1) 396 | 397 | journey_length = len(self.offsprings[i][random_journey_idx]) 398 | random_idx = random.randint(0, journey_length-1) 399 | random_idx2 = random.randint(0, journey_length-1) 400 | counter = 0 401 | self.offsprings[i][random_journey_idx][random_idx], self.offsprings[i][random_journey_idx][random_idx2] = self.offsprings[i][random_journey_idx][random_idx2], self.offsprings[i][random_journey_idx][random_idx] 402 | 403 | if (not self.is_valid(self.offsprings[i])): 404 | repeat = True 405 | 406 | self.population = np.concatenate((self.population,self.offsprings)) 407 | 408 | 409 | 410 | def solve_vrp(generations, iterations, parent_size, population_size, nodelist, nodecoords, nodecap, journeys, max_cap, mutation_rate = 0.5): 411 | 412 | total_BFS = [] 413 | total_ASF = [] 414 | best_solution_set = [None]*iterations 415 | best_fitness_set = [None]*iterations 416 | 417 | for i in range(generations): 418 | total_BFS.append([]) 419 | total_ASF.append([]) 420 | 421 | # Algorithm called for different iterations to average out the result values 422 | for i in range(iterations): 423 | vrp_prob = EA(nodelist, nodecoords, nodecap, population_size, journeys, max_cap, mutation_rate) 424 | print('iteration:', i) 425 | for j in range(generations): 426 | 427 | vrp_prob.fitness_func() 428 | 429 | max_generation_fitness = vrp_prob.max_fitness# 430 | 431 | if len(total_BFS[j])==0: 432 | total_BFS[j].append(max_generation_fitness) 433 | elif max_generation_fitness >= total_BFS[j][-1]: 434 | total_BFS[j].append(max_generation_fitness) 435 | else: 436 | total_BFS[j].append(total_BFS[j][-1]) 437 | 438 | avg_generation_fitness = (np.average(vrp_prob.fitness) + sum(total_ASF[j])) / (len(total_ASF[j])+1) 439 | total_ASF[j].append(avg_generation_fitness) 440 | 441 | # Perform genetic algorithm operations 442 | vrp_prob.selection(parent_size, "BT", False) 443 | vrp_prob.crossover() 444 | vrp_prob.mutation() 445 | vrp_prob.fitness_func() 446 | vrp_prob.selection(population_size, "Truncation", True) #survivor selection hence last argument is True 447 | 448 | # Calculate initial solution/fitness and best solution/fitness 449 | initial_solution = vrp_prob.initial_solution 450 | initial_fitness = vrp_prob.initial_solution_fitness 451 | best_solution_set[i] = vrp_prob.max_solution 452 | best_fitness_set[i] = 1/max_generation_fitness 453 | 454 | 455 | # Calculate best fitness and best solution 456 | best_fitness = 1/(max(total_BFS[-1])) 457 | best_solution_set = list(best_solution_set) 458 | best_sol_idx = best_fitness_set.index(best_fitness) 459 | best_solution = list(best_solution_set[best_sol_idx]) 460 | 461 | print(best_solution) 462 | print(best_fitness) 463 | 464 | empty = [] 465 | for i in vrp_prob.max_solution: 466 | if i not in empty: 467 | empty.append(i) 468 | else: 469 | print('DUPLICATION') 470 | 471 | generations_list = [] 472 | for i in range(1,generations+1): 473 | generations_list.append(i) 474 | 475 | # Plot the best fitness and average fitness values 476 | BFS_gen = [] 477 | ASF_gen = [] 478 | gen_file = open("gen_BFS_ASF.txt","w") 479 | for i in range(0,generations): 480 | BFS_gen.append(1/np.average(total_BFS[i])) 481 | ASF_gen.append(1/np.average(total_ASF[i])) 482 | gen_file.write(str(generations_list[i])) 483 | gen_file.write(" | ") 484 | gen_file.write(str(1/np.average(total_BFS[i]))) 485 | gen_file.write(" | ") 486 | gen_file.write(str(1/np.average(total_ASF[i]))) 487 | gen_file.write("\n") 488 | 489 | BFS_iter_gen = [] 490 | ASF_iter_gen = [] 491 | BFS_iter = open("BFS_iteration_gen.txt","w") 492 | ASF_iter = open("ASF_iteration_gen.txt","w") 493 | for i in range(0,generations): 494 | temp_BFS = [] 495 | temp_ASF = [] 496 | BFS_iter.write(str(generations_list[i])) 497 | ASF_iter.write(str(generations_list[i])) 498 | for j in range(0,iterations): 499 | temp_BFS.append(1/total_BFS[i][j]) 500 | temp_ASF.append(1/total_ASF[i][j]) 501 | BFS_iter.write(" | ") 502 | ASF_iter.write(" | ") 503 | BFS_iter.write(str(1/total_BFS[i][j])) 504 | ASF_iter.write(str(1/total_ASF[i][j])) 505 | BFS_iter_gen.append(temp_BFS) 506 | ASF_iter_gen.append(temp_ASF) 507 | BFS_iter.write(" | ") 508 | BFS_iter.write(str(np.average(temp_BFS))) 509 | BFS_iter.write("\n") 510 | ASF_iter.write(" | ") 511 | ASF_iter.write(str(np.average(temp_ASF))) 512 | ASF_iter.write("\n") 513 | BFS_iter.close() 514 | ASF_iter.close() 515 | 516 | plt.close('all') 517 | plt.title('Fitness vs Generation (BT and Truncation)') 518 | plt.plot(generations_list, BFS_gen, label="BFS") 519 | plt.ylabel('Fitness') 520 | plt.xlabel('Generations') 521 | plt.plot(generations_list, ASF_gen, label="ASF") 522 | plt.legend(framealpha=1, frameon=True); 523 | plt.savefig('BTandTruncation.png') 524 | plt.show() 525 | 526 | return best_fitness 527 | 528 | # datasets -> https://github.com/giulianoxt/vehicle-routing-aco/blob/master/augerat-a/A-n32-k5.vrp 529 | # Read the data file 530 | infile = open('A-n32-k5.txt', 'r') 531 | 532 | # Read instance header 533 | infile.readline().strip().split() 534 | infile.readline().strip().split() 535 | infile.readline().strip().split() 536 | dim = int(infile.readline().strip().split()[-1]) 537 | infile.readline().strip().split() 538 | max_cap = int(infile.readline().strip().split()[-1]) 539 | journeys = int(infile.readline().strip().split()[-1]) 540 | infile.readline().strip().split() 541 | 542 | nodelist = [] 543 | nodecoords = [] 544 | nodecap = [] 545 | 546 | for i in range(0, dim): 547 | line = infile.readline() 548 | 549 | if (line != ''): 550 | n,x,y = line.strip().split() 551 | if (float(n)==1): 552 | nodecoords.append([float(x), float(y)]) 553 | else: 554 | nodelist.append(int(n)-1) 555 | nodecoords.append([float(x), float(y)]) 556 | else: 557 | break 558 | 559 | infile.readline() 560 | 561 | for i in range(0, dim): 562 | line = infile.readline() 563 | 564 | if (line != ''): 565 | n,c = line.strip().split() 566 | if (float(n)==1): 567 | pass 568 | else: 569 | nodecap.append(float(c)) 570 | else: 571 | break 572 | 573 | # Close input file 574 | infile.close() 575 | 576 | 577 | # Define parameter values 578 | generations = 400 579 | iterations = 1 580 | parent_size = 850 581 | population_size = 1500 582 | mutation_rate = 0.5 583 | 584 | solve_vrp(generations, iterations, parent_size, population_size, nodelist, nodecoords, nodecap, journeys, max_cap, mutation_rate) 585 | 586 | # mutation = [] 587 | # fitness_set = [] 588 | 589 | # for i in range(0, 1000, 20): 590 | # print(i/1000) 591 | # fitness = solve_vrp(generations, iterations, parent_size, population_size, nodelist, nodecoords, nodecap, journeys, max_cap, i/1000) 592 | # fitness_set.append(fitness) 593 | # mutation.append(i/1000) 594 | 595 | 596 | # plt.close('all') 597 | # plt.title('Fitness vs Mutation Rate') 598 | # plt.plot(mutation, fitness_set) 599 | # plt.ylabel('Fitness') 600 | # plt.xlabel('Mutation Rate') 601 | # plt.show() 602 | 603 | ########################################################################################### 604 | ########################################################################################### 605 | ########################################################################################### 606 | ################ Code by Abdullah Siddiqui (ms03586@st.habib.edu.pk) ##################### 607 | ########################################################################################### 608 | ########################################################################################### 609 | ########################################################################################### -------------------------------------------------------------------------------- /CVRP - Sequential ACO.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | from matplotlib import pyplot as plt 3 | from scipy.spatial.distance import pdist, squareform 4 | import numpy as np 5 | import sys 6 | 7 | #This function loads the datafile and returns number of nodes, number of ants/vehicles, vehicle capacity, node that is a depot, array of positions of all nodes 8 | #and array of loads of every node 9 | def read_file(): 10 | input_file = open('data.txt', 'r') 11 | nodes_position = [] 12 | nodes_load = [] 13 | for i, line in enumerate(input_file): 14 | values = line.split(' ') 15 | if i == 0: 16 | n_tours = int(values[0]) 17 | init_capacity = int(values[1]) 18 | else: 19 | if int(values[3])==0: 20 | depot = int(values[0])-1 21 | nodes_position.append([int(values[1]), int(values[2])]) 22 | nodes_load.append(int(values[3])) 23 | input_file.close() 24 | n_nodes = len(nodes_position) 25 | nodes_position = np.array(nodes_position) 26 | nodes_load = np.array(nodes_load) 27 | 28 | return n_nodes, n_tours, init_capacity, depot, nodes_position, nodes_load 29 | 30 | 31 | #This function uses networkx package to create a graph and returns it along with number of vehicles (m) and vehicle capacity 32 | def initialize_nodes(): 33 | graph = nx.DiGraph() 34 | data_file = open('data.txt', 'r') 35 | for i, line in enumerate(data_file): 36 | values = line.split(' ') 37 | if i == 0: 38 | m = int(values[0]) 39 | q = int(values[1]) 40 | else: 41 | if int(values[3])==0: 42 | depot=True 43 | else: 44 | depot=False 45 | graph.add_node(int(values[0])-1, pos=[int(values[1]), int(values[2])], q = int(values[3]), depot=depot) 46 | data_file.close() 47 | 48 | return m, q, graph 49 | 50 | 51 | #This function places vehicles to depot as their starting position along with setting their capacity limit 52 | def initialize_ants(depot_node, n_ants, init_capacity): 53 | ants_location = {} 54 | ants_capacity = np.zeros(n_ants) 55 | for i in range(n_ants): 56 | ants_location[i] = [depot_node] 57 | ants_capacity[i] = init_capacity 58 | 59 | return ants_location, ants_capacity 60 | 61 | 62 | #This function uses pdist which uses euclidean distance to computes a squareform matrix with distances between each nodes. 63 | def get_distances(pos): 64 | positions = np.array(list(pos.values())) 65 | distances = pdist(positions) 66 | distances = squareform(distances) 67 | 68 | return distances 69 | 70 | 71 | #This function uses pdist which uses euclidean distance to computes a squareform matrix with distances between each nodes. 72 | def get_distances2(nodes_position): 73 | distances = pdist(nodes_position) 74 | distances = squareform(distances) 75 | 76 | return distances 77 | 78 | 79 | #This function computes visibility for each edge which is the inverse of distance between them. 80 | def calculate_visibility(pos, n): 81 | distances = get_distances(pos) 82 | visbility = np.zeros((n,n)) 83 | for i in range(n): 84 | for j in range(n): 85 | if i != j: 86 | visbility[i][j] = 1.0/distances[i][j] 87 | 88 | return visbility 89 | 90 | 91 | #This function finds the total distance of a tour 92 | def get_Lk(ant_location, distances): 93 | dist = 0.0 94 | for m in range(1,len(ant_location)): 95 | i = ant_location[m-1] 96 | j = ant_location[m] 97 | dist += distances[i][j] 98 | 99 | return dist 100 | 101 | 102 | #This function computes the total distance covered for the entire journey 103 | def get_Lks(ants_location, n, m, distances): 104 | Lk = np.zeros(m) 105 | for ant in range(m): 106 | ant_location = ants_location[ant] 107 | Lk[ant] = get_Lk(ant_location, distances) 108 | 109 | return Lk 110 | 111 | 112 | #This function computes the total distance covered for the entire journey 113 | def get_total_distance(ants_location, n, m, distances): 114 | Lk = get_Lks(ants_location, n, m, distances) 115 | return np.sum(Lk) 116 | 117 | 118 | #This function gives the optimal distance covered 119 | def get_best_ant_distance(best_ants_location, distances): 120 | dist = 0.0 121 | for k in range(1, len(best_ants_location)): 122 | i = best_ants_location[k-1] 123 | j = best_ants_location[k] 124 | dist += distances[i][j] 125 | 126 | return dist 127 | 128 | 129 | #This function sums the capacity of nodes visited 130 | def get_tour_qs(ant_location, qs): 131 | tour_q = 0.0 132 | for location in ant_location: 133 | tour_q += qs[location] 134 | 135 | return tour_q 136 | 137 | 138 | #This function computes the sum of capacity for each journey of vehicle 139 | def get_qs(ants_location, m, qs): 140 | tour_qs = np.zeros(m) 141 | for ant in range(m): 142 | ant_location = ants_location[ant] 143 | tour_qs[ant] = get_tour_qs(ant_location, qs) 144 | 145 | return tour_qs 146 | 147 | 148 | #Calls get_qs function to compute the sum of capacity for each journey of vehicle 149 | def get_total_qs(ants_location, m, qs): 150 | tour_qs = get_qs(ants_location, m, qs) 151 | 152 | return np.sum(tour_qs) 153 | 154 | 155 | #This function updates the pheromone after evaporation 156 | def update_pheromones_rho(pheromones, ants_location, n, m, distances, qs, rho): 157 | for i in range(n): 158 | for j in range(n): 159 | pheromones[i][j] = rho*pheromones[i][j] 160 | return pheromones 161 | 162 | 163 | #This function updates the concentration of pheromone of the routes which have been covered by the elite ants 164 | def update_ant_route_pheromone(pheromones, ants_location, n, m, distances, rho, ant): 165 | ant_location = ants_location[ant] 166 | Lk = get_Lk(ant_location, distances) 167 | 168 | for i in range(n): 169 | for j in range(n): 170 | for k in range(1,len(ant_location)): 171 | if ant_location[k-1] == i and ant_location[k] == j: 172 | pheromones[i][j] += 1.0/Lk 173 | 174 | return pheromones 175 | 176 | 177 | #This function creates a window of size 50 and avearges out the values in it and slides over the entire samples 178 | def sliding_window(n_iteration, ys, k=50): 179 | ys_window = np.zeros(n_iteration) 180 | 181 | for i in range(n_iteration): 182 | k_prime = k 183 | if i= n_iteration-k: 186 | k_prim = n_iteration-i-1 187 | s = 0 188 | 189 | for j in range (i-k_prim, i+k_prim+1): 190 | s += (k_prim+1-abs(i-j)) 191 | ys_window[i]+=float((k_prim+1-abs(i-j))*ys[j]) 192 | ys_window[i] /= s 193 | 194 | return ys_window 195 | 196 | 197 | #This function uses ACO to solve VRP 198 | def VRP(n_iteration, num_ants, alpha, beta, rho): 199 | m, q, graph = initialize_nodes() 200 | n = len(graph.nodes()) 201 | pos = nx.get_node_attributes(graph, 'pos') 202 | depots = nx.get_node_attributes(graph,'depot') 203 | qs = nx.get_node_attributes(graph,'q') 204 | m = num_ants 205 | BFS = [] 206 | 207 | for key, val in depots.items(): 208 | if val == True: 209 | depot = key 210 | break 211 | 212 | solution_distances = np.zeros(n_iteration) 213 | distances = get_distances(pos) 214 | visbility = calculate_visibility(pos, n) 215 | pheromones = np.zeros((n,n)) 216 | 217 | for i in range(n): 218 | for j in range(n): 219 | pheromones[i][j] = 1.0/(n*n) 220 | 221 | ant_distances = np.zeros((n_iteration, m)) 222 | 223 | min_dist = sys.float_info.max 224 | best_locs = None 225 | 226 | for iteration in range(n_iteration): 227 | print('i: ', iteration) 228 | 229 | # init ant locations 230 | ants_location, ants_capacity = initialize_ants(depot, m, q) 231 | visited = np.zeros(n) 232 | ant_completed = np.zeros(m) 233 | 234 | if iteration > 0: 235 | pheromones = update_pheromones_rho(pheromones, ants_location, n, m, distances, qs, rho) 236 | 237 | for ant in range(m): 238 | 239 | while ant_completed[ant]==0: 240 | 241 | # find current path and current node and feasible nodes 242 | current_path = ants_location[ant] 243 | i = current_path[-1] 244 | feasible_nodes =[] 245 | tmp_nodes = np.where(visited == 0)[0] 246 | 247 | for node in tmp_nodes: 248 | if ants_capacity[ant] > qs[node]: 249 | feasible_nodes.append(node) 250 | 251 | if len (feasible_nodes) > 1: 252 | # calculate transitions 253 | sum_val = 0 254 | 255 | for node in feasible_nodes: 256 | sum_val += ((pheromones[i][node])**alpha) * (visbility[i][node]**beta) 257 | p_transition = np.zeros(n) 258 | 259 | for j in range(n): 260 | if j in feasible_nodes: 261 | p_transition[j] = ((pheromones[i][j])**alpha) *(visbility[i][j]**beta)/sum_val 262 | random_num = np.random.uniform(0,1) 263 | 264 | for k, prob in enumerate(p_transition): 265 | random_num -= prob 266 | if random_num <= 0: 267 | new_city = k 268 | break 269 | 270 | visited[new_city] = 1 271 | ants_capacity[ant] -= qs[new_city] 272 | ants_location[ant].append(new_city) 273 | 274 | else: 275 | ant_completed[ant] = 1 276 | ants_location[ant].append(depot) 277 | ant_distances[iteration][ant] = get_Lk(ants_location[ant], distances) #Total path distance 278 | 279 | pheromones = update_ant_route_pheromone(pheromones, ants_location, n, m, distances, rho, ant) 280 | 281 | solution_distances[iteration] = get_total_distance(ants_location, n, m, distances) 282 | if solution_distances[iteration] < min_dist: 283 | min_dist = solution_distances[iteration] 284 | best_locs = ants_location 285 | BFS.append(min_dist) 286 | 287 | locs = [] 288 | for ant in range(m): 289 | for node in best_locs[ant]: 290 | locs.append(node) 291 | 292 | return solution_distances, locs, BFS 293 | 294 | 295 | #This function plots the best solution 296 | def draw_best(best_locs): 297 | _, _, _, _, nodes_position, _ = read_file() 298 | pos = {} 299 | nodes_label = [] 300 | for i, node in enumerate(nodes_position): 301 | pos[i] = node 302 | nodes_label.append(str(i)) 303 | graph = nx.DiGraph() 304 | graph.add_nodes_from(pos.keys()) 305 | 306 | for n, p in pos.items(): 307 | graph.nodes[n]['pos'] = p 308 | for v in graph.nodes(): 309 | graph.nodes[v]['label']= str(v) 310 | for i in range(1,len(best_locs)): 311 | graph.add_edge(best_locs[i-1], best_locs[i]) 312 | 313 | nx.draw(graph, pos) 314 | node_labels = nx.get_node_attributes(graph,'label') 315 | nx.draw_networkx_labels(graph, pos, labels = node_labels) 316 | plt.savefig('best_locs.png') 317 | 318 | 319 | def main(n_iteration=180): 320 | y, best_locs, BFS = VRP(n_iteration, 5, 0.8, 6, 0.9) 321 | print('y: ', y) 322 | print('best loc: ', best_locs) 323 | 324 | n_nodes, n_tours, init_capacity, depot, nodes_position, nodes_load = read_file() 325 | distances = get_distances2(nodes_position) 326 | print(get_best_ant_distance(best_locs, distances)) 327 | 328 | fig = plt.figure() 329 | ax = fig.add_subplot(111) 330 | ys = sliding_window(n_iteration, y, k=20) 331 | plt.title('Fitness vs Iteration') 332 | plt.plot([i for i in range(n_iteration)], BFS, label="BFS") 333 | plt.plot([i for i in range(n_iteration)], ys, label="AFS") 334 | plt.legend(["BFS", "AFS"]) 335 | plt.ylabel('Fitness') 336 | plt.xlabel('Iterations') 337 | plt.show() 338 | ax.plot(range(n_iteration), ys) 339 | ax.set_xlabel("iteration") 340 | ax.set_ylabel("distances") 341 | ax.set_title("Convergence plot") 342 | plt.savefig('old-best.png') 343 | 344 | main() 345 | -------------------------------------------------------------------------------- /CVRP - Visualization.py: -------------------------------------------------------------------------------- 1 | ########################################################################################### 2 | ########################################################################################### 3 | ########################################################################################### 4 | ################ Code by Abdullah Siddiqui (ms03586@st.habib.edu.pk) ##################### 5 | ########################################################################################### 6 | ########################################################################################### 7 | ########################################################################################### 8 | 9 | from scipy.spatial.distance import pdist, squareform 10 | import numpy as np 11 | import sys 12 | import networkx as nx 13 | import random 14 | import matplotlib.pyplot as plt 15 | import math 16 | import numpy as np 17 | import random 18 | import matplotlib.pyplot as plt 19 | import math 20 | import veroviz as vrv 21 | import os 22 | import pandas as pd 23 | 24 | 25 | # Define directories and keys for the Veroviz library 26 | CESIUM_DIR = os.environ['CESIUMDIR'] 27 | DATA_PROVIDER = 'ORS-online' 28 | DATA_PROVIDER_ARGS = {'APIkey': os.environ['ORSKEY'], 'databaseName': None} 29 | 30 | # Define boundary in which to generate the nodes 31 | myBoundary = [[42.914949262700084, -78.90020370483398], 32 | [42.871938424448466, -78.89556884765626], 33 | [42.875083507773496, -78.82158279418947], 34 | [42.91293772859624, -78.81729125976564]] 35 | 36 | # Define number of nodes to be generated 37 | numCustomers = 29 38 | 39 | vrv.createLeaflet(boundingRegion = myBoundary) 40 | 41 | # Single depot node: 42 | nodesDF = vrv.generateNodes( 43 | numNodes = 1, 44 | startNode = 0, 45 | nodeType = 'depot', 46 | leafletColor = 'red', 47 | leafletIconType = 'home', 48 | nodeDistrib = 'uniformBB', 49 | nodeDistribArgs = { 'boundingRegion': myBoundary }, 50 | dataProvider = DATA_PROVIDER, 51 | dataProviderArgs = DATA_PROVIDER_ARGS, 52 | snapToRoad = True) 53 | 54 | 55 | # Create Customer nodes: 56 | nodesDF = vrv.generateNodes( 57 | initNodes = nodesDF, 58 | numNodes = numCustomers, 59 | startNode = 1, 60 | nodeType = 'customer', 61 | leafletColor = 'blue', 62 | leafletIconType = 'star', 63 | nodeDistrib = 'uniformBB', 64 | nodeDistribArgs = { 'boundingRegion': myBoundary }, 65 | dataProvider = DATA_PROVIDER, 66 | dataProviderArgs = DATA_PROVIDER_ARGS, 67 | snapToRoad = True) 68 | 69 | 70 | # Create a map that shows the boundary and the nodes: 71 | vrv.createLeaflet(nodes = nodesDF, 72 | boundingRegion = myBoundary, 73 | mapBackground = 'Arcgis Roadmap') 74 | 75 | [time, dist] = vrv.getTimeDist2D(nodes = nodesDF, 76 | matrixType = 'all2all', 77 | routeType = 'fastest', 78 | dataProvider = DATA_PROVIDER, 79 | dataProviderArgs = DATA_PROVIDER_ARGS) 80 | 81 | # Class that represents the genetic algorithm and associated functions 82 | class EA: 83 | def __init__(self, nodelist, nodecoords, nodecap, size, journeys, max_cap, dist): 84 | self.nodelist = nodelist 85 | self.nodecoords = nodecoords 86 | self.nodecap = nodecap 87 | self.population_size = size 88 | self.mutation_rate = 0.5 89 | self.population = [] 90 | self.dist = dist 91 | self.journeys = journeys 92 | self.max_cap = max_cap 93 | self.mutation_valid = 0 94 | self.mutation_invalid = 0 95 | self.initial_solution = [] 96 | 97 | self.initialize_population() 98 | 99 | # Initialize random chromosomes for the population 100 | def initialize_population(self): 101 | candidate = nodelist.copy() 102 | 103 | for i in range(self.population_size): 104 | 105 | route = [] 106 | 107 | while (len(route)!= self.journeys): 108 | random.shuffle(candidate) 109 | cap = 0 110 | nodesvisited = 0 111 | journey = [] 112 | route = [] 113 | 114 | for i in candidate: 115 | cap += self.nodecap[i-1] 116 | 117 | if cap > max_cap: 118 | route.append(journey) 119 | journey = [] 120 | cap = self.nodecap[i-1] 121 | 122 | journey.append(i) 123 | nodesvisited += 1 124 | 125 | if journey != []: 126 | route.append(journey) 127 | 128 | self.population.append(route) 129 | 130 | self.initial_solution = self.population[1] 131 | self.initial_solution_fitness = self.individual_fitness(self.initial_solution) 132 | 133 | 134 | # Calculate distance based on the values calculated by the map interface 135 | def calculate_distance(self, node1, node2): 136 | distance = dist[(node1, node2)] 137 | return distance 138 | 139 | 140 | # Calculate fitness for every member in the population 141 | #By default fitness is being maximized, for minimization the value's reciprocal is stored 142 | def fitness_func(self): 143 | self.fitness = [] 144 | 145 | for i in range(len(self.population)): 146 | if (not self.is_valid(self.population[i])): 147 | self.population[i] = self.shuffle_route(self.population[i]) 148 | 149 | individual_fitness = self.individual_fitness(self.population[i]) 150 | self.fitness.append(1/individual_fitness) 151 | 152 | maximum = 0 153 | idx = 0 154 | 155 | for i in range(0,len(self.fitness)): 156 | if self.fitness[i] > maximum: 157 | maximum = self.fitness[i] 158 | idx = i 159 | 160 | self.max_solution = self.population[idx] 161 | self.max_fitness = maximum 162 | 163 | 164 | # Calculate fitness of an individual i.e. total distance travelled 165 | def individual_fitness(self, candidate): 166 | individual_fitness = 0 167 | 168 | for j in range(len(candidate)): 169 | first_journey_node = candidate[j][0] 170 | individual_fitness += self.calculate_distance(0, first_journey_node) 171 | 172 | for k in range(len(candidate[j]) - 1): 173 | idx1, idx2 = candidate[j][k], candidate[j][k+1] 174 | individual_fitness += self.calculate_distance(idx1, idx2) 175 | 176 | last_journey_node = candidate[j][-1] 177 | individual_fitness += self.calculate_distance(last_journey_node, 0) 178 | 179 | return individual_fitness 180 | 181 | 182 | # Check if route is valid i.e. meets capacity requierments 183 | def is_valid(self, candidate): 184 | cap = 0 185 | for journey in candidate: 186 | for j in journey: 187 | cap += self.nodecap[j-1] 188 | 189 | if cap > self.max_cap: 190 | return False 191 | cap = 0 192 | 193 | return True 194 | 195 | 196 | # If route does not meet capacity requirements, shuffle it stochastically to ensure it does 197 | def shuffle_route(self, org_candidate): 198 | 199 | candidate = [] 200 | for i in org_candidate: 201 | for j in i: 202 | candidate.append(j) 203 | 204 | random.shuffle(candidate) 205 | route = [] 206 | 207 | while (len(route)!= self.journeys): 208 | random.shuffle(candidate) 209 | cap = 0 210 | nodesvisited = 0 211 | journey = [] 212 | route = [] 213 | 214 | for i in candidate: 215 | cap += self.nodecap[i-1] 216 | 217 | if cap > max_cap: 218 | route.append(journey) 219 | journey = [] 220 | cap = self.nodecap[i-1] 221 | 222 | journey.append(i) 223 | nodesvisited += 1 224 | 225 | if journey != []: 226 | route.append(journey) 227 | 228 | return route 229 | 230 | 231 | # Select either parents or survivors to proceed to the next stage through a variety of selection schemes 232 | # Num is the size of individuals to select and scheme defines the type of selection scheme 233 | def selection(self, num, scheme, survivor): 234 | self.selected_candidates = [] 235 | 236 | if scheme == "Random": 237 | 238 | for i in range(num): 239 | random_num = random.randrange(len(self.population)) 240 | self.selected_candidates.append(self.population[random_num]) 241 | 242 | 243 | elif scheme == "FPS": 244 | 245 | norm_fitness = [] 246 | sum_fitness = sum(self.fitness) 247 | 248 | for i in self.fitness: 249 | norm_fitness.append(i/sum_fitness) 250 | 251 | cum_prob = [] 252 | a = 0 253 | 254 | for k in norm_fitness: 255 | a += k 256 | cum_prob.append(a) 257 | 258 | np.array(cum_prob) 259 | 260 | for i in range(num): 261 | random_num = random.uniform(0,1) 262 | 263 | for j in range(len(cum_prob)-1): 264 | if (random_num > cum_prob[j] and random_num <= cum_prob[j+1]): 265 | self.selected_candidates.append(self.population[j+1]) 266 | break 267 | elif (random_num <= cum_prob[0]): 268 | self.selected_candidates.append(self.population[0]) 269 | break 270 | 271 | 272 | elif scheme == "Truncation": 273 | fitness_copy = np.copy(self.fitness) 274 | 275 | numbered_fitness_copy = list(enumerate(fitness_copy)) 276 | numbered_fitness_copy.sort(key=lambda x:x[1]) 277 | numbered_fitness_copy = numbered_fitness_copy[::-1] 278 | 279 | for i in range(num): 280 | index = numbered_fitness_copy[i][0] 281 | self.selected_candidates.append(self.population[index]) 282 | 283 | 284 | elif scheme == "RBS": 285 | 286 | fitness_copy = np.copy(self.fitness) 287 | numbered_fitness_copy = list(enumerate(fitness_copy)) 288 | numbered_fitness_copy.sort(key=lambda x:x[1]) 289 | 290 | rank_dic = dict() 291 | rank_lst = [] 292 | for i in range(1,len(self.fitness)+1): 293 | rank_dic[i] = numbered_fitness_copy[i-1] 294 | rank_lst.append(i) 295 | 296 | norm_rank_dic = dict() 297 | norm_lst = [] 298 | for j in range(1,len(self.fitness)+1): 299 | norm_rank_dic[rank_lst[j-1]/sum(rank_lst)] = rank_dic[j] 300 | norm_lst.append(rank_lst[j-1]/sum(rank_lst)) 301 | 302 | cum_lst = [] 303 | a = 0 304 | for p in norm_lst: 305 | a+=p 306 | cum_lst.append(a) 307 | 308 | for k in range(num): 309 | random_num2 = random.uniform(0,1) 310 | 311 | for m in range (len(cum_lst)-1): 312 | 313 | if (random_num2 > cum_lst[m] and random_num2 <= cum_lst[m+1]): 314 | fitness = norm_rank_dic[norm_lst[m+1]][1] 315 | index = norm_rank_dic[norm_lst[m+1]][0] 316 | self.selected_candidates.append(self.population[index]) 317 | break 318 | elif random_num2 <= cum_lst[0]: 319 | fitness = norm_rank_dic[norm_lst[0]][1] 320 | index = norm_rank_dic[norm_lst[0]][0] 321 | self.selected_candidates.append(self.population[index]) 322 | break 323 | 324 | 325 | elif scheme == 'BT': 326 | for i in range(num): 327 | cand_dic = dict() 328 | 329 | for j in range(2): 330 | rand = random.randrange(len(self.population)) 331 | cand_dic[rand] = self.fitness[rand] 332 | 333 | max_index = max(cand_dic, key=cand_dic.get) 334 | self.selected_candidates.append(self.population[max_index]) 335 | 336 | 337 | else: 338 | print("Please enter a valid scheme") 339 | 340 | 341 | if survivor == True: 342 | self.population = np.array(self.selected_candidates) 343 | else: 344 | self.selected_candidates = np.array(self.selected_candidates) 345 | 346 | 347 | # Create new generation of off springs 348 | def crossover(self): 349 | selected_candidates_copy = np.copy(self.selected_candidates) 350 | selected_candidates_copy = selected_candidates_copy.tolist() 351 | temp_offsprings = [] 352 | 353 | #Two point crossover 354 | for i in range(0,len(selected_candidates_copy)-1,2): 355 | parent1 = selected_candidates_copy[i] 356 | parent2 = selected_candidates_copy[i+1] 357 | 358 | child1 = self.child1reate_child(parent1, parent2) 359 | child2 = self.create_child(parent2, parent1) 360 | offspring1 = np.array(child1) 361 | offspring2 = np.array(child2) 362 | temp_offsprings.append(offspring1) 363 | temp_offsprings.append(offspring2) 364 | 365 | self.offsprings = np.array(temp_offsprings) 366 | 367 | 368 | # Create child by performing two point crossover on parents 369 | def create_child(self,org_parent1, org_parent2): 370 | 371 | parent1 = [] 372 | parent2 = [] 373 | 374 | for i in org_parent1: 375 | for j in i: 376 | parent1.append(j) 377 | 378 | for i in org_parent2: 379 | for j in i: 380 | parent2.append(j) 381 | 382 | crossover_point1 = int(random.randint(0,len(parent1))) 383 | crossover_point2 = int(random.randint(0,len(parent1))) 384 | 385 | while crossover_point2 == crossover_point1: 386 | crossover_point2 = int(random.randint(0,len(parent1))) 387 | 388 | start = min(crossover_point1, crossover_point2) 389 | end = max(crossover_point1, crossover_point2) 390 | 391 | insertion = parent1[start:end] 392 | stored = [] 393 | child = [None]*len(parent1) 394 | 395 | j = 0 396 | for i in range(len(parent1)): 397 | 398 | if i>=start and i2): 413 | random.shuffle(candidate) 414 | 415 | cap = 0 416 | journey = [] 417 | route = [] 418 | 419 | for i in candidate: 420 | cap += self.nodecap[i-1] 421 | 422 | if cap > max_cap: 423 | route.append(journey) 424 | journey = [] 425 | cap = self.nodecap[i-1] 426 | 427 | journey.append(i) 428 | 429 | if journey != []: 430 | route.append(journey) 431 | 432 | attempts += 1 433 | 434 | org_child = route 435 | 436 | return org_child 437 | 438 | 439 | # mutate the offsprings by either swaps or inversion 440 | def mutation(self): 441 | for i in range(len(self.offsprings)): 442 | random_num = random.uniform(0,1) 443 | 444 | if random_num < self.mutation_rate: 445 | repeat = True 446 | 447 | while (repeat): 448 | repeat = False 449 | random_journey_idx = random.randint(0, self.journeys-1) 450 | while (len(self.offsprings[i][random_journey_idx])<2): 451 | random_journey_idx = random.randint(0, self.journeys-1) 452 | 453 | journey_length = len(self.offsprings[i][random_journey_idx]) 454 | random_idx = random.randint(0, journey_length-1) 455 | random_idx2 = random.randint(0, journey_length-1) 456 | counter = 0 457 | 458 | self.offsprings[i][random_journey_idx][random_idx], self.offsprings[i][random_journey_idx][random_idx2] = self.offsprings[i][random_journey_idx][random_idx2], self.offsprings[i][random_journey_idx][random_idx] 459 | 460 | if (not self.is_valid(self.offsprings[i])): 461 | repeat = True 462 | 463 | 464 | self.population = np.concatenate((self.population,self.offsprings)) 465 | 466 | 467 | # function solves the routing problem 468 | def solve_vrp(generations, iterations, parent_size, population_size, nodelist, nodecoords, nodecap, journeys, max_cap, dist): 469 | 470 | total_BFS = [] 471 | total_ASF = [] 472 | best_solution_set = [None]*iterations 473 | best_fitness_set = [None]*iterations 474 | 475 | for i in range(generations): 476 | total_BFS.append([]) 477 | total_ASF.append([]) 478 | 479 | for i in range(iterations): 480 | vrp_prob = EA(nodelist, nodecoords, nodecap, population_size, journeys, max_cap, dist) 481 | 482 | for j in range(generations): 483 | 484 | vrp_prob.fitness_func() 485 | max_generation_fitness = vrp_prob.max_fitness 486 | 487 | if len(total_BFS[j])==0: 488 | total_BFS[j].append(max_generation_fitness) 489 | elif max_generation_fitness >= total_BFS[j][-1]: 490 | total_BFS[j].append(max_generation_fitness) 491 | else: 492 | total_BFS[j].append(total_BFS[j][-1]) 493 | 494 | avg_generation_fitness = (np.average(vrp_prob.fitness) + sum(total_ASF[j])) / (len(total_ASF[j])+1) 495 | total_ASF[j].append(avg_generation_fitness) 496 | 497 | vrp_prob.selection(parent_size, "BT", False) 498 | vrp_prob.crossover() 499 | vrp_prob.mutation() 500 | vrp_prob.fitness_func() 501 | vrp_prob.selection(population_size, "Truncation", True) #survivor selection hence last argument is True 502 | 503 | initial_solution = vrp_prob.initial_solution 504 | initial_fitness = vrp_prob.initial_solution_fitness 505 | best_solution_set[i] = vrp_prob.max_solution 506 | best_fitness_set[i] = 1/max_generation_fitness 507 | 508 | best_fitness = 1/(max(total_BFS[-1])) 509 | best_solution_set = list(best_solution_set) 510 | best_sol_idx = best_fitness_set.index(best_fitness) 511 | best_solution = list(best_solution_set[best_sol_idx]) 512 | 513 | print(initial_solution) 514 | print(initial_fitness) 515 | print(best_solution) 516 | print(best_fitness) 517 | 518 | empty = [] 519 | for i in vrp_prob.max_solution: 520 | if i not in empty: 521 | empty.append(i) 522 | 523 | generations_list = [] 524 | for i in range(1,generations+1): 525 | generations_list.append(i) 526 | 527 | # Plot the best fitness and average fitness values 528 | BFS_gen = [] 529 | ASF_gen = [] 530 | gen_file = open("gen_BFS_ASF.txt","w") 531 | for i in range(0,generations): 532 | BFS_gen.append(1/np.average(total_BFS[i])) 533 | ASF_gen.append(1/np.average(total_ASF[i])) 534 | gen_file.write(str(generations_list[i])) 535 | gen_file.write(" | ") 536 | gen_file.write(str(1/np.average(total_BFS[i]))) 537 | gen_file.write(" | ") 538 | gen_file.write(str(1/np.average(total_ASF[i]))) 539 | gen_file.write("\n") 540 | 541 | BFS_iter_gen = [] 542 | ASF_iter_gen = [] 543 | BFS_iter = open("BFS_iteration_gen.txt","w") 544 | ASF_iter = open("ASF_iteration_gen.txt","w") 545 | for i in range(0,generations): 546 | temp_BFS = [] 547 | temp_ASF = [] 548 | BFS_iter.write(str(generations_list[i])) 549 | ASF_iter.write(str(generations_list[i])) 550 | for j in range(0,iterations): 551 | temp_BFS.append(1/total_BFS[i][j]) 552 | temp_ASF.append(1/total_ASF[i][j]) 553 | BFS_iter.write(" | ") 554 | ASF_iter.write(" | ") 555 | BFS_iter.write(str(1/total_BFS[i][j])) 556 | ASF_iter.write(str(1/total_ASF[i][j])) 557 | BFS_iter_gen.append(temp_BFS) 558 | ASF_iter_gen.append(temp_ASF) 559 | BFS_iter.write(" | ") 560 | BFS_iter.write(str(np.average(temp_BFS))) 561 | BFS_iter.write("\n") 562 | ASF_iter.write(" | ") 563 | ASF_iter.write(str(np.average(temp_ASF))) 564 | ASF_iter.write("\n") 565 | BFS_iter.close() 566 | ASF_iter.close() 567 | 568 | plt.close('all') 569 | plt.title('Fitness vs Generation (BT and Truncation)') 570 | plt.plot(generations_list, BFS_gen, label="BFS") 571 | plt.ylabel('Fitness') 572 | plt.xlabel('Generations') 573 | plt.plot(generations_list, ASF_gen, label="ASF") 574 | plt.legend(framealpha=1, frameon=True); 575 | plt.savefig('BTandTruncation.png') 576 | # plt.show() 577 | 578 | initial_route = [0] 579 | for i in initial_solution: 580 | for j in i: 581 | initial_route.append(j) 582 | initial_route.append(0) 583 | 584 | best_route = [0] 585 | for i in best_solution: 586 | for j in i: 587 | best_route.append(j) 588 | best_route.append(0) 589 | 590 | print(initial_route) 591 | print(best_route) 592 | 593 | return([initial_solution, best_solution]) 594 | 595 | 596 | # Read data file to store capacity of different nodes 597 | infile = open('data2.txt', 'r') 598 | 599 | # Read instance header 600 | journeys, max_cap = infile.readline().strip().split() 601 | journeys = int(journeys) 602 | max_cap = int(max_cap) 603 | 604 | nodelist = [] 605 | nodecoords = [] 606 | nodecap = [] 607 | 608 | N = 1000 609 | for i in range(0, numCustomers+1): 610 | line = infile.readline() 611 | if (line != ''): 612 | n,x,y,c = line.strip().split() 613 | if (float(c)==0): 614 | nodecoords.append([float(x), float(y)]) 615 | else: 616 | nodelist.append(int(n)-1) 617 | nodecoords.append([float(x), float(y)]) 618 | nodecap.append(float(c)) 619 | 620 | else: 621 | break 622 | 623 | total_capacity = sum(nodecap) 624 | journeys = total_capacity//100 + 1 625 | 626 | # Close input file 627 | infile.close() 628 | 629 | 630 | # Define parameter values 631 | generations = 250 632 | iterations = 1 633 | parent_size = 90 634 | population_size = 300 635 | 636 | random_route, truck_route = solve_vrp(generations, iterations, parent_size, population_size, nodelist, nodecoords, nodecap, journeys, max_cap, dist) 637 | 638 | print(random_route) 639 | print(truck_route) 640 | 641 | 642 | # Visualize the improved routes via Cesium and Folium 643 | def vrvSolver(nodesDF, dist, time, truck_route): 644 | import pandas as pd 645 | 646 | network = [] 647 | count = 0 648 | truck = 'truck' 649 | for path in truck_route: 650 | truck = truck + str(count) 651 | route = {truck:[0]} 652 | for node in path: 653 | route[truck].append(node) 654 | route[truck].append(0) 655 | print("route: ",route) 656 | count += 1 657 | network.append(route) 658 | 659 | # Define configuration of the different vehicles used to deliver the goods 660 | configs = {'truck0': { 661 | 'vehicleModels': ['veroviz/models/ub_truck.gltf'], 662 | 'leafletColor': 'blue', 663 | 'cesiumColor': 'Cesium.Color.BLUE', 664 | 'packageModel': 'veroviz/models/box_blue.gltf', 665 | 'modelScale': 100, 666 | 'minPxSize': 55 }, 667 | 'truck01': { 668 | 'vehicleModels': ['veroviz/models/ub_truck.gltf'], 669 | 'leafletColor': 'orange', 670 | 'cesiumColor': 'Cesium.Color.ORANGE', 671 | 'packageModel': 'veroviz/models/box_blue.gltf', 672 | 'modelScale': 100, 673 | 'minPxSize': 55 }, 674 | 'truck012': { 675 | 'vehicleModels': ['veroviz/models/ub_truck.gltf'], 676 | 'leafletColor': 'red', 677 | 'cesiumColor': 'Cesium.Color.RED', 678 | 'packageModel': 'veroviz/models/box_blue.gltf', 679 | 'modelScale': 100, 680 | 'minPxSize': 55 }, 681 | 'truck0123': { 682 | 'vehicleModels': ['veroviz/models/ub_truck.gltf'], 683 | 'leafletColor': 'purple', 684 | 'cesiumColor': 'Cesium.Color.PURPLE', 685 | 'packageModel': 'veroviz/models/box_blue.gltf', 686 | 'modelScale': 100, 687 | 'minPxSize': 55 }, 688 | 'truck01234': { 689 | 'vehicleModels': ['veroviz/models/ub_truck.gltf'], 690 | 'leafletColor': 'yellow', 691 | 'cesiumColor': 'Cesium.Color.YELLOW', 692 | 'packageModel': 'veroviz/models/box_blue.gltf', 693 | 'modelScale': 100, 694 | 'minPxSize': 55 } 695 | } 696 | 697 | serviceTime = 30 # seconds 698 | 699 | # Initialize an empty "assignments" dataframe. 700 | assignmentsDF = vrv.initDataframe('assignments') 701 | 702 | startTime = 0 703 | 704 | for route in network: 705 | for vehicle in route: 706 | for i in list(range(0, len(route[vehicle])-1)): 707 | startNode = route[vehicle][i] 708 | endNode = route[vehicle][i+1] 709 | 710 | startLat = nodesDF[nodesDF['id'] == startNode]['lat'].values[0] 711 | startLon = nodesDF[nodesDF['id'] == startNode]['lon'].values[0] 712 | endLat = nodesDF[nodesDF['id'] == endNode]['lat'].values[0] 713 | endLon = nodesDF[nodesDF['id'] == endNode]['lon'].values[0] 714 | 715 | if ((vehicle == 'drone') and (startNode == 0)): 716 | # Use the 3D model of a drone carrying a package 717 | myModel = configs[vehicle]['vehicleModels'][1] 718 | else: 719 | # Use the 3D model of either a delivery truck or an empty drone 720 | myModel = configs[vehicle]['vehicleModels'][0] 721 | 722 | if (vehicle == 'truck' or vehicle == 'truck0' or vehicle == 'truck01' or vehicle == 'truck012' or vehicle == 'truck0123' or vehicle == 'truck01234'): 723 | # Get turn-by-turn navigation for the truck, as it travels 724 | # from the startNode to the endNode: 725 | shapepointsDF = vrv.getShapepoints2D( 726 | # odID = odID, 727 | objectID = vehicle, 728 | modelFile = myModel, 729 | modelScale = configs[vehicle]['modelScale'], 730 | modelMinPxSize = configs[vehicle]['minPxSize'], 731 | startTimeSec = startTime, 732 | startLoc = [startLat, startLon], 733 | endLoc = [endLat, endLon], 734 | routeType = 'fastest', 735 | leafletColor = configs[vehicle]['leafletColor'], 736 | cesiumColor = configs[vehicle]['cesiumColor'], 737 | dataProvider = DATA_PROVIDER, 738 | dataProviderArgs = DATA_PROVIDER_ARGS) 739 | else: 740 | # Get a 3D flight profile for the drone: 741 | shapepointsDF = vrv.getShapepoints3D( 742 | # odID = odID, 743 | objectID = vehicle, 744 | modelFile = myModel, 745 | modelScale = configs[vehicle]['modelScale'], 746 | modelMinPxSize = configs[vehicle]['minPxSize'], 747 | startTimeSec = startTime, 748 | startLoc = [startLat, startLon], 749 | endLoc = [endLat, endLon], 750 | takeoffSpeedMPS = 5, 751 | cruiseSpeedMPS = 20, 752 | landSpeedMPS = 3, 753 | cruiseAltMetersAGL = 100, 754 | routeType = 'square', 755 | cesiumColor = configs[vehicle]['cesiumColor']) 756 | 757 | # Update the assignments dataframe: 758 | assignmentsDF = pd.concat([assignmentsDF, shapepointsDF], ignore_index=True, sort=False) 759 | 760 | # Update the time 761 | startTime = max(shapepointsDF['endTimeSec']) 762 | 763 | # Add loitering for service 764 | assignmentsDF = vrv.addStaticAssignment( 765 | initAssignments = assignmentsDF, 766 | objectID = vehicle, 767 | modelFile = myModel, 768 | modelScale = configs[vehicle]['modelScale'], 769 | modelMinPxSize = configs[vehicle]['minPxSize'], 770 | loc = [endLat, endLon], 771 | startTimeSec = startTime, 772 | endTimeSec = startTime + serviceTime) 773 | 774 | # Update the time again 775 | startTime = startTime + serviceTime 776 | 777 | # Add a package at all non-depot nodes 778 | if (endNode != 0): 779 | assignmentsDF = vrv.addStaticAssignment( 780 | initAssignments = assignmentsDF, 781 | # odID = 0, 782 | objectID = 'package %d' % endNode, 783 | modelFile = configs[vehicle]['packageModel'], 784 | modelScale = 100, 785 | modelMinPxSize = 35, 786 | loc = [endLat, endLon], 787 | startTimeSec = startTime, 788 | endTimeSec = -1) 789 | 790 | return assignmentsDF 791 | 792 | # Generate route assignments for the initial and optimal route 793 | print("Initialized Random Route:") 794 | assignmentsDF = vrvSolver(nodesDF, dist, time, random_route) 795 | print() 796 | print("Optimal Route:") 797 | solutionDF = vrvSolver(nodesDF, dist, time, truck_route) 798 | 799 | 800 | # Create a Leaflet map showing the nodes and the routes. 801 | random_map = vrv.createLeaflet(nodes=nodesDF, arcs=assignmentsDF) 802 | optimal_map = vrv.createLeaflet(nodes=nodesDF, arcs=solutionDF) 803 | 804 | random_map.save('random_map.html') 805 | optimal_map.save('optimal_map.html') 806 | 807 | 808 | # Create a Cesium movie showing the nodes, routes, and package deliveries for the 809 | # random initialized and optimal route. 810 | vrv.createCesium( 811 | assignments = assignmentsDF, 812 | nodes = nodesDF, 813 | startTime = '10:00:00', 814 | cesiumDir = os.environ['CESIUMDIR'], 815 | problemDir = 'combine_random_initialization_withBox') 816 | 817 | 818 | vrv.createCesium( 819 | assignments = solutionDF, 820 | nodes = nodesDF, 821 | startTime = '10:00:00', 822 | cesiumDir = os.environ['CESIUMDIR'], 823 | problemDir = 'combine_optimal_route_withBox') 824 | 825 | 826 | ########################################################################################### 827 | ########################################################################################### 828 | ########################################################################################### 829 | ################ Code by Abdullah Siddiqui (ms03586@st.habib.edu.pk) ##################### 830 | ########################################################################################### 831 | ########################################################################################### 832 | ########################################################################################### 833 | 834 | -------------------------------------------------------------------------------- /CVRP-TW - Visualization.py: -------------------------------------------------------------------------------- 1 | ########################################################################################### 2 | ########################################################################################### 3 | ########################################################################################### 4 | ################ Code by Abdullah Siddiqui (ms03586@st.habib.edu.pk) ##################### 5 | ########################################################################################### 6 | ########################################################################################### 7 | ########################################################################################### 8 | 9 | from scipy.spatial.distance import pdist, squareform 10 | import numpy as np 11 | import sys 12 | import networkx as nx 13 | import random 14 | import matplotlib.pyplot as plt 15 | import math 16 | import numpy as np 17 | import random 18 | import matplotlib.pyplot as plt 19 | import math 20 | import veroviz as vrv 21 | import os 22 | import pandas as pd 23 | 24 | # Define directories and keys for the Veroviz library 25 | CESIUM_DIR = os.environ['CESIUMDIR'] 26 | DATA_PROVIDER = 'ORS-online' 27 | DATA_PROVIDER_ARGS = {'APIkey': os.environ['ORSKEY'], 'databaseName': None} 28 | 29 | # Define boundary in which to generate the nodes 30 | myBoundary = [[42.914949262700084, -78.90020370483398], 31 | [42.871938424448466, -78.89556884765626], 32 | [42.875083507773496, -78.82158279418947], 33 | [42.91293772859624, -78.81729125976564]] 34 | 35 | numCustomers = 26 36 | 37 | vrv.createLeaflet(boundingRegion = myBoundary) 38 | 39 | # Create single depot node: 40 | nodesDF = vrv.generateNodes( 41 | numNodes = 1, 42 | startNode = 0, 43 | nodeType = 'depot', 44 | leafletColor = 'red', 45 | leafletIconType = 'home', 46 | nodeDistrib = 'uniformBB', 47 | nodeDistribArgs = { 'boundingRegion': myBoundary }, 48 | dataProvider = DATA_PROVIDER, 49 | dataProviderArgs = DATA_PROVIDER_ARGS, 50 | snapToRoad = True) 51 | 52 | # Create customer nodes: 53 | nodesDF = vrv.generateNodes( 54 | initNodes = nodesDF, 55 | numNodes = numCustomers, 56 | startNode = 1, 57 | nodeType = 'customer', 58 | leafletColor = 'blue', 59 | leafletIconType = 'star', 60 | nodeDistrib = 'uniformBB', 61 | nodeDistribArgs = { 'boundingRegion': myBoundary }, 62 | dataProvider = DATA_PROVIDER, 63 | dataProviderArgs = DATA_PROVIDER_ARGS, 64 | snapToRoad = True) 65 | 66 | # Create a map that shows the boundary and the nodes: 67 | vrv.createLeaflet(nodes = nodesDF, 68 | boundingRegion = myBoundary, 69 | mapBackground = 'Arcgis Roadmap') 70 | 71 | [time, dist] = vrv.getTimeDist2D(nodes = nodesDF, 72 | matrixType = 'all2all', 73 | routeType = 'fastest', 74 | dataProvider = DATA_PROVIDER, 75 | dataProviderArgs = DATA_PROVIDER_ARGS) 76 | 77 | 78 | # Class that represents the genetic algorithm and associated functions 79 | class EA: 80 | def __init__(self, nodelist, nodecoords, nodecap, size, journeys, max_cap, dist, time = [], consider_time = False): 81 | self.nodelist = nodelist 82 | self.nodecoords = nodecoords 83 | self.nodecap = nodecap 84 | self.population_size = size 85 | self.mutation_rate = 0.5 86 | self.max_time = 10000 #seconds 87 | self.population = [] 88 | self.dist = dist 89 | self.journeys = journeys 90 | self.max_cap = max_cap 91 | self.mutation_valid = 0 92 | self.mutation_invalid = 0 93 | self.initial_solution = [] 94 | self.consider_time = consider_time 95 | 96 | self.initialize_population() 97 | 98 | 99 | # Initialize random chromosomes for the population 100 | def initialize_population(self): 101 | candidate = nodelist.copy() 102 | 103 | for i in range(self.population_size): 104 | route = [] 105 | 106 | while (len(route)!= self.journeys): 107 | 108 | random.shuffle(candidate) 109 | cap = 0 110 | nodesvisited = 0 111 | journey = [] 112 | route = [] 113 | 114 | for i in candidate: 115 | cap += self.nodecap[i-1] 116 | 117 | if cap > max_cap: 118 | route.append(journey) 119 | journey = [] 120 | cap = self.nodecap[i-1] 121 | 122 | journey.append(i) 123 | nodesvisited += 1 124 | 125 | if journey != []: 126 | route.append(journey) 127 | 128 | self.population.append(route) 129 | 130 | self.initial_solution = self.population[1] 131 | self.initial_solution_fitness = self.individual_fitness(self.initial_solution) 132 | 133 | 134 | # Calculate time of one trip based on the values calculated by the map interface 135 | def calculate_time(self, node1, node2): 136 | time_taken = time[(node1, node2)] 137 | return time_taken 138 | 139 | 140 | # Calculate time of entire route based on the values calculated by the map interface 141 | def calculate_total_time(self, candidate): 142 | 143 | if (time == []): 144 | return 0 145 | 146 | time_set = [] 147 | total_time = 0 148 | for journey in candidate: 149 | total_time = 0 150 | total_time += self.calculate_time(0, journey[0]) 151 | 152 | for j in range(len(journey)-1): 153 | total_time += self.calculate_time(journey[j], journey[j+1]) 154 | total_time += self.calculate_time(journey[-1], 0) 155 | 156 | time_set.append(total_time) 157 | 158 | return max(time_set) 159 | 160 | 161 | # Calculate distance of entire route based on the values calculated by the map interface 162 | def calculate_distance(self, node1, node2): 163 | distance = dist[(node1, node2)] 164 | return distance 165 | 166 | 167 | # Calculate fitness for every member in the population 168 | # By default fitness is being maximized, for minimization the value's reciprocal is stored 169 | def fitness_func(self): 170 | self.fitness = [] 171 | 172 | for i in range(len(self.population)): 173 | if (not self.consider_time): 174 | if ( not self.is_valid(self.population[i]) ): 175 | self.population[i] = self.shuffle_route(self.population[i]) 176 | else: 177 | if ( (not self.is_valid(self.population[i])) or (not self.is_time_valid(self.population[i]))): 178 | self.population[i] = self.shuffle_route(self.population[i]) 179 | 180 | if (not self.consider_time): 181 | individual_fitness = self.individual_fitness(self.population[i]) 182 | else: 183 | individual_fitness = self.individual_fitness(self.population[i]) + ( 30*self.calculate_total_time(self.population[i]) ) 184 | 185 | self.fitness.append(1/individual_fitness) 186 | 187 | maximum = 0 188 | idx = 0 189 | for i in range(0,len(self.fitness)): 190 | if self.fitness[i] > maximum: 191 | maximum = self.fitness[i] 192 | idx = i 193 | 194 | self.max_solution = self.population[idx] 195 | self.max_fitness = maximum 196 | 197 | 198 | # Calculate fitness of an individual i.e. total distance travelled and time taken weighted together 199 | def individual_fitness(self, candidate): 200 | individual_fitness = 0 201 | 202 | for j in range(len(candidate)): 203 | first_journey_node = candidate[j][0] 204 | individual_fitness += self.calculate_distance(0, first_journey_node) 205 | 206 | for k in range(len(candidate[j]) - 1): 207 | idx1, idx2 = candidate[j][k], candidate[j][k+1] 208 | individual_fitness += self.calculate_distance(idx1, idx2) 209 | 210 | last_journey_node = candidate[j][-1] 211 | individual_fitness += self.calculate_distance(last_journey_node, 0) 212 | 213 | return individual_fitness 214 | 215 | 216 | # Check if route is valid i.e. meets capacity requierments 217 | def is_valid(self, candidate): 218 | cap = 0 219 | for journey in candidate: 220 | for j in journey: 221 | cap += self.nodecap[j-1] 222 | 223 | if cap > self.max_cap: 224 | return False 225 | cap = 0 226 | 227 | return True 228 | 229 | 230 | # Check if route is valid i.e. meets time window requierments 231 | def is_time_valid(self, candidate): 232 | if (time == []): 233 | return True 234 | 235 | total_time = 0 236 | for journey in candidate: 237 | 238 | total_time = 0 239 | total_time += self.calculate_time(0, journey[0]) 240 | 241 | for j in range(len(journey)-1): 242 | total_time += self.calculate_time(journey[j], journey[j+1]) 243 | total_time += self.calculate_time(journey[-1], 0) 244 | 245 | if total_time > self.max_time: 246 | return False 247 | 248 | return True 249 | 250 | 251 | # If route does not meet capacity or time requirements, shuffle it stochastically to ensure it does 252 | def shuffle_route(self, org_candidate): 253 | candidate = [] 254 | for i in org_candidate: 255 | for j in i: 256 | candidate.append(j) 257 | 258 | random.shuffle(candidate) 259 | route = [] 260 | 261 | while (len(route)!= self.journeys): 262 | 263 | random.shuffle(candidate) 264 | cap = 0 265 | nodesvisited = 0 266 | journey = [] 267 | route = [] 268 | 269 | for i in candidate: 270 | cap += self.nodecap[i-1] 271 | if cap > max_cap: 272 | route.append(journey) 273 | journey = [] 274 | cap = self.nodecap[i-1] 275 | 276 | journey.append(i) 277 | nodesvisited += 1 278 | 279 | if journey != []: 280 | route.append(journey) 281 | 282 | return route 283 | 284 | 285 | # Select either parents or survivors to proceed to the next stage through a variety of selection schemes 286 | # Num is the size of individuals to select and scheme defines the type of selection scheme 287 | def selection(self, num, scheme, survivor): 288 | self.selected_candidates = [] 289 | 290 | if scheme == "Random": 291 | 292 | for i in range(num): 293 | random_num = random.randrange(len(self.population)) 294 | self.selected_candidates.append(self.population[random_num]) 295 | 296 | 297 | elif scheme == "FPS": 298 | 299 | norm_fitness = [] 300 | sum_fitness = sum(self.fitness) 301 | 302 | for i in self.fitness: 303 | norm_fitness.append(i/sum_fitness) 304 | 305 | cum_prob = [] 306 | a = 0 307 | 308 | for k in norm_fitness: 309 | a += k 310 | cum_prob.append(a) 311 | 312 | np.array(cum_prob) 313 | 314 | for i in range(num): 315 | random_num = random.uniform(0,1) 316 | 317 | for j in range(len(cum_prob)-1): 318 | 319 | if (random_num > cum_prob[j] and random_num <= cum_prob[j+1]): 320 | self.selected_candidates.append(self.population[j+1]) 321 | break 322 | elif (random_num <= cum_prob[0]): 323 | self.selected_candidates.append(self.population[0]) 324 | break 325 | 326 | 327 | elif scheme == "Truncation": 328 | 329 | fitness_copy = np.copy(self.fitness) 330 | numbered_fitness_copy = list(enumerate(fitness_copy)) 331 | numbered_fitness_copy.sort(key=lambda x:x[1]) 332 | numbered_fitness_copy = numbered_fitness_copy[::-1] 333 | 334 | for i in range(num): 335 | index = numbered_fitness_copy[i][0] 336 | self.selected_candidates.append(self.population[index]) 337 | 338 | 339 | elif scheme == "RBS": 340 | 341 | fitness_copy = np.copy(self.fitness) 342 | numbered_fitness_copy = list(enumerate(fitness_copy)) 343 | numbered_fitness_copy.sort(key=lambda x:x[1]) 344 | 345 | rank_dic = dict() 346 | rank_lst = [] 347 | for i in range(1,len(self.fitness)+1): 348 | rank_dic[i] = numbered_fitness_copy[i-1] 349 | rank_lst.append(i) 350 | 351 | norm_rank_dic = dict() 352 | norm_lst = [] 353 | for j in range(1,len(self.fitness)+1): 354 | norm_rank_dic[rank_lst[j-1]/sum(rank_lst)] = rank_dic[j] 355 | norm_lst.append(rank_lst[j-1]/sum(rank_lst)) 356 | 357 | cum_lst = [] 358 | a = 0 359 | for p in norm_lst: 360 | a+=p 361 | cum_lst.append(a) 362 | 363 | for k in range(num): 364 | random_num2 = random.uniform(0,1) 365 | 366 | for m in range (len(cum_lst)-1): 367 | 368 | if (random_num2 > cum_lst[m] and random_num2 <= cum_lst[m+1]): 369 | fitness = norm_rank_dic[norm_lst[m+1]][1] 370 | index = norm_rank_dic[norm_lst[m+1]][0] 371 | self.selected_candidates.append(self.population[index]) 372 | break 373 | elif random_num2 <= cum_lst[0]: 374 | fitness = norm_rank_dic[norm_lst[0]][1] 375 | index = norm_rank_dic[norm_lst[0]][0] 376 | self.selected_candidates.append(self.population[index]) 377 | break 378 | 379 | 380 | elif scheme == 'BT': 381 | for i in range(num): 382 | cand_dic = dict() 383 | 384 | for j in range(2): 385 | rand = random.randrange(len(self.population)) 386 | cand_dic[rand] = self.fitness[rand] 387 | 388 | max_index = max(cand_dic, key=cand_dic.get) 389 | self.selected_candidates.append(self.population[max_index]) 390 | 391 | 392 | else: 393 | print("Please enter a valid scheme") 394 | 395 | 396 | if survivor == True: 397 | self.population = np.array(self.selected_candidates) 398 | else: 399 | self.selected_candidates = np.array(self.selected_candidates) 400 | 401 | 402 | # Create new generation of off springs 403 | def crossover(self): 404 | selected_candidates_copy = np.copy(self.selected_candidates) 405 | selected_candidates_copy = selected_candidates_copy.tolist() 406 | temp_offsprings = [] 407 | 408 | #Two point crossover 409 | for i in range(0,len(selected_candidates_copy)-1,2): 410 | parent1 = selected_candidates_copy[i] 411 | parent2 = selected_candidates_copy[i+1] 412 | 413 | child1 = self.create_child(parent1, parent2) 414 | child2 = self.create_child(parent2, parent1) 415 | offspring1 = np.array(child1) 416 | offspring2 = np.array(child2) 417 | temp_offsprings.append(offspring1) 418 | temp_offsprings.append(offspring2) 419 | 420 | self.offsprings = np.array(temp_offsprings) 421 | 422 | 423 | # Create child by performing two point crossover on parents 424 | def create_child(self,org_parent1, org_parent2): 425 | parent1 = [] 426 | parent2 = [] 427 | 428 | for i in org_parent1: 429 | for j in i: 430 | parent1.append(j) 431 | 432 | for i in org_parent2: 433 | for j in i: 434 | parent2.append(j) 435 | 436 | crossover_point1 = int(random.randint(0,len(parent1))) 437 | crossover_point2 = int(random.randint(0,len(parent1))) 438 | 439 | while crossover_point2 == crossover_point1: 440 | crossover_point2 = int(random.randint(0,len(parent1))) 441 | 442 | start = min(crossover_point1, crossover_point2) 443 | end = max(crossover_point1, crossover_point2) 444 | 445 | insertion = parent1[start:end] 446 | stored = [] 447 | child = [None]*len(parent1) 448 | 449 | j = 0 450 | for i in range(len(parent1)): 451 | 452 | if i>=start and i5): 467 | random.shuffle(candidate) 468 | 469 | if attempts>15: 470 | break 471 | 472 | cap = 0 473 | journey = [] 474 | route = [] 475 | for i in candidate: 476 | cap += self.nodecap[i-1] 477 | 478 | if cap > max_cap: 479 | route.append(journey) 480 | journey = [] 481 | cap = self.nodecap[i-1] 482 | 483 | journey.append(i) 484 | 485 | if journey != []: 486 | route.append(journey) 487 | 488 | attempts += 1 489 | 490 | if (self.consider_time): 491 | if (not self.is_time_valid(route)): 492 | repeat = True 493 | 494 | org_child = route 495 | 496 | return org_child 497 | 498 | 499 | # mutate the offsprings by either swaps or inversion 500 | def mutation(self): 501 | 502 | for i in range(len(self.offsprings)): 503 | random_num = random.uniform(0,1) 504 | 505 | if random_num < self.mutation_rate: 506 | repeat = True 507 | 508 | while (repeat): 509 | repeat = False 510 | random_journey_idx = random.randint(0, len(self.offsprings[i])-1) 511 | 512 | while (len(self.offsprings[i][random_journey_idx])<2): 513 | random_journey_idx = random.randint(0, self.journeys-1) 514 | 515 | journey_length = len(self.offsprings[i][random_journey_idx]) 516 | random_idx = random.randint(0, journey_length-1) 517 | random_idx2 = random.randint(0, journey_length-1) 518 | self.offsprings[i][random_journey_idx][random_idx], self.offsprings[i][random_journey_idx][random_idx2] = self.offsprings[i][random_journey_idx][random_idx2], self.offsprings[i][random_journey_idx][random_idx] 519 | 520 | if (not self.is_valid(self.offsprings[i])): 521 | repeat = True 522 | 523 | self.population = np.concatenate((self.population,self.offsprings)) 524 | 525 | 526 | # function solves the vehicle routing problem 527 | def solve_vrp(generations, iterations, parent_size, population_size, nodelist, nodecoords, nodecap, journeys, max_cap, dist, time = [], consider_time = False, max_time = 5000): 528 | total_BFS = [] 529 | total_ASF = [] 530 | best_solution_set = [None]*iterations 531 | best_fitness_set = [None]*iterations 532 | 533 | for i in range(generations): 534 | total_BFS.append([]) 535 | total_ASF.append([]) 536 | 537 | for i in range(iterations): 538 | vrp_prob = EA(nodelist, nodecoords, nodecap, population_size, journeys, max_cap, dist, time, consider_time) 539 | 540 | for j in range(generations): 541 | 542 | if ((consider_time) and (j==290)): 543 | vrp_prob.max_time = max_time 544 | 545 | vrp_prob.fitness_func() 546 | max_generation_fitness = vrp_prob.max_fitness 547 | 548 | if len(total_BFS[j])==0: 549 | total_BFS[j].append(max_generation_fitness) 550 | elif max_generation_fitness >= total_BFS[j][-1]: 551 | total_BFS[j].append(max_generation_fitness) 552 | else: 553 | total_BFS[j].append(total_BFS[j][-1]) 554 | 555 | avg_generation_fitness = (np.average(vrp_prob.fitness) + sum(total_ASF[j])) / (len(total_ASF[j])+1) 556 | total_ASF[j].append(avg_generation_fitness) 557 | 558 | vrp_prob.selection(parent_size, "BT", False) 559 | vrp_prob.crossover() 560 | vrp_prob.mutation() 561 | vrp_prob.fitness_func() 562 | vrp_prob.selection(population_size, "Truncation", True) #survivor selection hence last argument is True 563 | 564 | initial_solution = vrp_prob.initial_solution 565 | initial_fitness = vrp_prob.initial_solution_fitness 566 | best_solution_set[i] = vrp_prob.max_solution 567 | best_fitness_set[i] = 1/max_generation_fitness 568 | 569 | best_fitness = 1/(max(total_BFS[-1])) 570 | best_solution_set = list(best_solution_set) 571 | best_sol_idx = best_fitness_set.index(best_fitness) 572 | best_solution = list(best_solution_set[best_sol_idx]) 573 | 574 | #best time 575 | best_time = vrp_prob.calculate_total_time(best_solution) 576 | #best distance 577 | best_dist = vrp_prob.individual_fitness(best_solution) 578 | 579 | print("Best Fitness: ",best_fitness) 580 | print("Best Time Fitness: ", best_time) 581 | print("Best Distance Fitness: ", best_dist) 582 | 583 | empty = [] 584 | for i in vrp_prob.max_solution: 585 | if i not in empty: 586 | empty.append(i) 587 | 588 | generations_list = [] 589 | for i in range(1,generations+1): 590 | generations_list.append(i) 591 | 592 | # plot the best and average fitness values 593 | BFS_gen = [] 594 | ASF_gen = [] 595 | gen_file = open("gen_BFS_ASF.txt","w") 596 | for i in range(0,generations): 597 | BFS_gen.append(1/np.average(total_BFS[i])) 598 | ASF_gen.append(1/np.average(total_ASF[i])) 599 | gen_file.write(str(generations_list[i])) 600 | gen_file.write(" | ") 601 | gen_file.write(str(1/np.average(total_BFS[i]))) 602 | gen_file.write(" | ") 603 | gen_file.write(str(1/np.average(total_ASF[i]))) 604 | gen_file.write("\n") 605 | 606 | BFS_iter_gen = [] 607 | ASF_iter_gen = [] 608 | BFS_iter = open("BFS_iteration_gen.txt","w") 609 | ASF_iter = open("ASF_iteration_gen.txt","w") 610 | for i in range(0,generations): 611 | temp_BFS = [] 612 | temp_ASF = [] 613 | BFS_iter.write(str(generations_list[i])) 614 | ASF_iter.write(str(generations_list[i])) 615 | for j in range(0,iterations): 616 | temp_BFS.append(1/total_BFS[i][j]) 617 | temp_ASF.append(1/total_ASF[i][j]) 618 | BFS_iter.write(" | ") 619 | ASF_iter.write(" | ") 620 | BFS_iter.write(str(1/total_BFS[i][j])) 621 | ASF_iter.write(str(1/total_ASF[i][j])) 622 | BFS_iter_gen.append(temp_BFS) 623 | ASF_iter_gen.append(temp_ASF) 624 | BFS_iter.write(" | ") 625 | BFS_iter.write(str(np.average(temp_BFS))) 626 | BFS_iter.write("\n") 627 | ASF_iter.write(" | ") 628 | ASF_iter.write(str(np.average(temp_ASF))) 629 | ASF_iter.write("\n") 630 | BFS_iter.close() 631 | ASF_iter.close() 632 | 633 | plt.close('all') 634 | plt.title('Fitness vs Generation (BT and Truncation)') 635 | plt.plot(generations_list, BFS_gen, label="BFS") 636 | plt.ylabel('Fitness') 637 | plt.xlabel('Generations') 638 | plt.plot(generations_list, ASF_gen, label="ASF") 639 | plt.legend(framealpha=1, frameon=True); 640 | plt.savefig('BTandTruncation.png') 641 | # plt.show() 642 | 643 | initial_route = [0] 644 | for i in initial_solution: 645 | for j in i: 646 | initial_route.append(j) 647 | initial_route.append(0) 648 | 649 | best_route = [0] 650 | for i in best_solution: 651 | for j in i: 652 | best_route.append(j) 653 | best_route.append(0) 654 | 655 | return([initial_solution, best_solution, best_time]) 656 | 657 | 658 | # load data file to allocate capacity to the nodes and vehicles 659 | infile = open('data2.txt', 'r') 660 | 661 | # Read instance header 662 | journeys, max_cap = infile.readline().strip().split() 663 | journeys = int(journeys) 664 | max_cap = int(max_cap) 665 | 666 | nodelist = [] 667 | nodecoords = [] 668 | nodecap = [] 669 | 670 | N = 1000 671 | for i in range(0, numCustomers+1): 672 | line = infile.readline() 673 | 674 | if (line != ''): 675 | n,x,y,c = line.strip().split() 676 | if (float(c)==0): 677 | nodecoords.append([float(x), float(y)]) 678 | else: 679 | nodelist.append(int(n)-1) 680 | nodecoords.append([float(x), float(y)]) 681 | nodecap.append(float(c)) 682 | 683 | else: 684 | break 685 | 686 | total_capacity = sum(nodecap) 687 | journeys = total_capacity//100 + 1 688 | 689 | # Close input file 690 | infile.close() 691 | 692 | 693 | # Define parameter values 694 | generations = 300 695 | iterations = 1 696 | parent_size = 150 697 | population_size = 300 698 | 699 | # Solve CVRP 700 | random_route, dist_opt_route, dist_opt_sol_time = solve_vrp(generations, iterations, parent_size, population_size, nodelist, nodecoords, nodecap, journeys, max_cap, dist) 701 | print("Dist Opt: ", dist_opt_route) 702 | print() 703 | 704 | # Specify the CVRP-TW to optimize itself with a time window of 5 minutes less than the time obtained in CVRP 705 | max_time = dist_opt_sol_time - 300 706 | # Solve the CVRP-TW problem 707 | random_route, time_opt_route, time_opt_sol_time = solve_vrp(generations, iterations, parent_size, population_size, nodelist, nodecoords, nodecap, journeys, max_cap, dist, time, True, max_time) 708 | print("Time Opt: ", time_opt_route) 709 | print() 710 | 711 | 712 | # Visualize the improved routes via Cesium and Folium 713 | def vrvSolver(nodesDF, dist, time, truck_route): 714 | import pandas as pd 715 | 716 | network = [] 717 | count = 0 718 | truck = 'truck' 719 | for path in truck_route: 720 | truck = truck + str(count) 721 | route = {truck:[0]} 722 | 723 | for node in path: 724 | route[truck].append(node) 725 | route[truck].append(0) 726 | count += 1 727 | network.append(route) 728 | 729 | # Define configuration of the different vehicles used to deliver the goods 730 | configs = {'truck0': { 731 | 'vehicleModels': ['veroviz/models/ub_truck.gltf'], 732 | 'leafletColor': 'blue', 733 | 'cesiumColor': 'Cesium.Color.BLUE', 734 | 'packageModel': 'veroviz/models/box_blue.gltf', 735 | 'modelScale': 100, 736 | 'minPxSize': 75 }, 737 | 'truck01': { 738 | 'vehicleModels': ['veroviz/models/car_green.gltf'], 739 | 'leafletColor': 'green', 740 | 'cesiumColor': 'Cesium.Color.YELLOWGREEN', 741 | 'packageModel': 'veroviz/models/rectangle_green.gltf', 742 | 'modelScale': 100, 743 | 'minPxSize': 75 }, 744 | 'truck012': { 745 | 'vehicleModels': ['veroviz/models/car_red.gltf'], 746 | 'leafletColor': 'red', 747 | 'cesiumColor': 'Cesium.Color.RED', 748 | 'packageModel': 'veroviz/models/rectangle_red.gltf', 749 | 'modelScale': 100, 750 | 'minPxSize': 75 }, 751 | 'truck0123': { 752 | 'vehicleModels': ['veroviz/models/car_blue.gltf'], 753 | 'leafletColor': 'purple', 754 | 'cesiumColor': 'Cesium.Color.LIGHTSKYBLUE', 755 | 'packageModel': 'veroviz/models/rectangle_blue.gltf', 756 | 'modelScale': 100, 757 | 'minPxSize': 75 }, 758 | 'truck01234': { 759 | 'vehicleModels': ['veroviz/models/ub_truck.gltf'], 760 | 'leafletColor': 'yellow', 761 | 'cesiumColor': 'Cesium.Color.YELLOW', 762 | 'packageModel': 'veroviz/models/box_blue.gltf', 763 | 'modelScale': 100, 764 | 'minPxSize': 75 } 765 | } 766 | 767 | serviceTime = 30 # seconds 768 | 769 | # Initialize an empty "assignments" dataframe. 770 | assignmentsDF = vrv.initDataframe('assignments') 771 | 772 | 773 | time_set = [] 774 | 775 | for route in network: 776 | startTime = 0 # line moves outside the loop 777 | for vehicle in route: 778 | for i in list(range(0, len(route[vehicle])-1)): 779 | startNode = route[vehicle][i] 780 | endNode = route[vehicle][i+1] 781 | 782 | startLat = nodesDF[nodesDF['id'] == startNode]['lat'].values[0] 783 | startLon = nodesDF[nodesDF['id'] == startNode]['lon'].values[0] 784 | endLat = nodesDF[nodesDF['id'] == endNode]['lat'].values[0] 785 | endLon = nodesDF[nodesDF['id'] == endNode]['lon'].values[0] 786 | 787 | if ((vehicle == 'drone') and (startNode == 0)): 788 | # Use the 3D model of a drone carrying a package 789 | myModel = configs[vehicle]['vehicleModels'][1] 790 | else: 791 | # Use the 3D model of either a delivery truck or an empty drone 792 | myModel = configs[vehicle]['vehicleModels'][0] 793 | 794 | if (vehicle == 'truck' or vehicle == 'truck0' or vehicle == 'truck01' or vehicle == 'truck012' or vehicle == 'truck0123' or vehicle == 'truck01234'): 795 | # Get turn-by-turn navigation for the truck, as it travels 796 | # from the startNode to the endNode: 797 | shapepointsDF = vrv.getShapepoints2D( 798 | # odID = odID, 799 | objectID = vehicle, 800 | modelFile = myModel, 801 | modelScale = configs[vehicle]['modelScale'], 802 | modelMinPxSize = configs[vehicle]['minPxSize'], 803 | startTimeSec = startTime, 804 | startLoc = [startLat, startLon], 805 | endLoc = [endLat, endLon], 806 | routeType = 'fastest', 807 | leafletColor = configs[vehicle]['leafletColor'], 808 | cesiumColor = configs[vehicle]['cesiumColor'], 809 | dataProvider = DATA_PROVIDER, 810 | dataProviderArgs = DATA_PROVIDER_ARGS) 811 | else: 812 | # Get a 3D flight profile for the drone: 813 | shapepointsDF = vrv.getShapepoints3D( 814 | objectID = vehicle, 815 | modelFile = myModel, 816 | modelScale = configs[vehicle]['modelScale'], 817 | modelMinPxSize = configs[vehicle]['minPxSize'], 818 | startTimeSec = startTime, 819 | startLoc = [startLat, startLon], 820 | endLoc = [endLat, endLon], 821 | takeoffSpeedMPS = 5, 822 | cruiseSpeedMPS = 20, 823 | landSpeedMPS = 3, 824 | cruiseAltMetersAGL = 100, 825 | routeType = 'square', 826 | cesiumColor = configs[vehicle]['cesiumColor']) 827 | 828 | # Update the assignments dataframe: 829 | assignmentsDF = pd.concat([assignmentsDF, shapepointsDF], ignore_index=True, sort=False) 830 | 831 | # Update the time 832 | startTime = max(shapepointsDF['endTimeSec']) 833 | 834 | # Add loitering for service 835 | assignmentsDF = vrv.addStaticAssignment( 836 | initAssignments = assignmentsDF, 837 | objectID = vehicle, 838 | modelFile = myModel, 839 | modelScale = configs[vehicle]['modelScale'], 840 | modelMinPxSize = configs[vehicle]['minPxSize'], 841 | loc = [endLat, endLon], 842 | startTimeSec = startTime, 843 | endTimeSec = startTime + serviceTime) 844 | 845 | # Update the time again 846 | startTime = startTime + serviceTime 847 | 848 | # Add a package at all non-depot nodes: 849 | if (endNode != 0): 850 | assignmentsDF = vrv.addStaticAssignment( 851 | initAssignments = assignmentsDF, 852 | objectID = 'package %d' % endNode, 853 | modelFile = configs[vehicle]['packageModel'], 854 | modelScale = 100, 855 | modelMinPxSize = 35, 856 | loc = [endLat, endLon], 857 | startTimeSec = startTime, 858 | endTimeSec = -1) 859 | 860 | time_set.append(startTime) 861 | 862 | return assignmentsDF 863 | 864 | # Visualize CVRP 865 | print("Distance Optimal Route:") 866 | assignmentsDF = vrvSolver(nodesDF, dist, time, dist_opt_route) 867 | 868 | # Visualize CVRP-TW 869 | print("Time Optimal Route:") 870 | solutionDF = vrvSolver(nodesDF, dist, time, time_opt_route) 871 | 872 | print("Routes Calculated") 873 | 874 | # Create a Leaflet map showing the nodes and the routes. 875 | random_map = vrv.createLeaflet(nodes=nodesDF, arcs=assignmentsDF) 876 | optimal_map = vrv.createLeaflet(nodes=nodesDF, arcs=solutionDF) 877 | 878 | random_map.save('distance_map.html') 879 | optimal_map.save('time_map.html') 880 | 881 | # Create a Cesium movie showing the nodes, routes, and package deliveries. 882 | vrv.createCesium( 883 | assignments = assignmentsDF, 884 | nodes = nodesDF, 885 | startTime = '10:00:00', 886 | cesiumDir = os.environ['CESIUMDIR'], 887 | problemDir = 'Opt_Dist') 888 | 889 | vrv.createCesium( 890 | assignments = solutionDF, 891 | nodes = nodesDF, 892 | startTime = '10:00:00', 893 | cesiumDir = os.environ['CESIUMDIR'], 894 | problemDir = 'Opt_Time') 895 | 896 | 897 | ########################################################################################### 898 | ########################################################################################### 899 | ########################################################################################### 900 | ################ Code by Abdullah Siddiqui (ms03586@st.habib.edu.pk) ##################### 901 | ########################################################################################### 902 | ########################################################################################### 903 | ########################################################################################### 904 | 905 | -------------------------------------------------------------------------------- /Datasets/A-n32-k5.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n32-k5 2 | COMMENT : (Augerat et al, Min no of trucks: 5, Optimal value: 784) 3 | TYPE : CVRP 4 | DIMENSION : 32 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 5 8 | NODE_COORD_SECTION 9 | 1 82 76 10 | 2 96 44 11 | 3 50 5 12 | 4 49 8 13 | 5 13 7 14 | 6 29 89 15 | 7 58 30 16 | 8 84 39 17 | 9 14 24 18 | 10 2 39 19 | 11 3 82 20 | 12 5 10 21 | 13 98 52 22 | 14 84 25 23 | 15 61 59 24 | 16 1 65 25 | 17 88 51 26 | 18 91 2 27 | 19 19 32 28 | 20 93 3 29 | 21 50 93 30 | 22 98 14 31 | 23 5 42 32 | 24 42 9 33 | 25 61 62 34 | 26 9 97 35 | 27 80 55 36 | 28 57 69 37 | 29 23 15 38 | 30 20 70 39 | 31 85 60 40 | 32 98 5 41 | DEMAND_SECTION 42 | 1 0 43 | 2 19 44 | 3 21 45 | 4 6 46 | 5 19 47 | 6 7 48 | 7 12 49 | 8 16 50 | 9 6 51 | 10 16 52 | 11 8 53 | 12 14 54 | 13 21 55 | 14 16 56 | 15 3 57 | 16 22 58 | 17 18 59 | 18 19 60 | 19 1 61 | 20 24 62 | 21 8 63 | 22 12 64 | 23 4 65 | 24 8 66 | 25 24 67 | 26 24 68 | 27 2 69 | 28 20 70 | 29 15 71 | 30 2 72 | 31 14 73 | 32 9 74 | DEPOT_SECTION 75 | 1 76 | -1 77 | EOF -------------------------------------------------------------------------------- /Datasets/A-n34-k5.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n34-k5 2 | COMMENT : (Augerat et al, Min no of trucks: 5, Optimal value: 778) 3 | TYPE : CVRP 4 | DIMENSION : 34 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 5 8 | NODE_COORD_SECTION 9 | 1 73 39 10 | 2 67 91 11 | 3 39 21 12 | 4 3 9 13 | 5 97 15 14 | 6 91 65 15 | 7 55 75 16 | 8 55 71 17 | 9 57 85 18 | 10 21 15 19 | 11 47 57 20 | 12 51 97 21 | 13 11 11 22 | 14 43 59 23 | 15 63 69 24 | 16 55 77 25 | 17 35 11 26 | 18 27 91 27 | 19 49 25 28 | 20 29 93 29 | 21 71 27 30 | 22 31 43 31 | 23 27 9 32 | 24 67 99 33 | 25 87 81 34 | 26 23 81 35 | 27 89 33 36 | 28 71 91 37 | 29 19 77 38 | 30 65 77 39 | 31 87 79 40 | 32 19 83 41 | 33 1 59 42 | 34 55 7 43 | DEMAND_SECTION 44 | 1 0 45 | 2 23 46 | 3 3 47 | 4 24 48 | 5 15 49 | 6 15 50 | 7 24 51 | 8 7 52 | 9 25 53 | 10 13 54 | 11 5 55 | 12 7 56 | 13 5 57 | 14 14 58 | 15 13 59 | 16 5 60 | 17 24 61 | 18 15 62 | 19 9 63 | 20 16 64 | 21 13 65 | 22 16 66 | 23 13 67 | 24 24 68 | 25 20 69 | 26 23 70 | 27 20 71 | 28 3 72 | 29 15 73 | 30 12 74 | 31 19 75 | 32 4 76 | 33 15 77 | 34 1 78 | DEPOT_SECTION 79 | 1 80 | -1 81 | EOF -------------------------------------------------------------------------------- /Datasets/A-n37-k5.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n37-k5 2 | COMMENT : (Augerat et al, Min no of trucks: 5, Optimal value: 669) 3 | TYPE : CVRP 4 | DIMENSION : 37 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 5 8 | NODE_COORD_SECTION 9 | 1 38 46 10 | 2 59 46 11 | 3 96 42 12 | 4 47 61 13 | 5 26 15 14 | 6 66 6 15 | 7 96 7 16 | 8 37 25 17 | 9 68 92 18 | 10 78 84 19 | 11 82 28 20 | 12 93 90 21 | 13 74 42 22 | 14 60 20 23 | 15 78 58 24 | 16 36 48 25 | 17 45 36 26 | 18 73 57 27 | 19 10 91 28 | 20 98 51 29 | 21 92 62 30 | 22 43 42 31 | 23 53 25 32 | 24 78 65 33 | 25 72 79 34 | 26 37 88 35 | 27 16 73 36 | 28 75 96 37 | 29 11 66 38 | 30 9 49 39 | 31 25 72 40 | 32 8 68 41 | 33 12 61 42 | 34 50 2 43 | 35 26 54 44 | 36 18 89 45 | 37 22 53 46 | DEMAND_SECTION 47 | 1 0 48 | 2 16 49 | 3 18 50 | 4 1 51 | 5 13 52 | 6 8 53 | 7 23 54 | 8 7 55 | 9 27 56 | 10 1 57 | 11 3 58 | 12 6 59 | 13 24 60 | 14 19 61 | 15 2 62 | 16 5 63 | 17 16 64 | 18 7 65 | 19 4 66 | 20 22 67 | 21 7 68 | 22 23 69 | 23 16 70 | 24 2 71 | 25 2 72 | 26 9 73 | 27 2 74 | 28 12 75 | 29 1 76 | 30 9 77 | 31 23 78 | 32 6 79 | 33 19 80 | 34 7 81 | 35 7 82 | 36 20 83 | 37 20 84 | DEPOT_SECTION 85 | 1 86 | -1 87 | EOF -------------------------------------------------------------------------------- /Datasets/A-n44-k7.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n44-k6 2 | COMMENT : (Augerat et al, Min no of trucks: 6, Optimal value: 937) 3 | TYPE : CVRP 4 | DIMENSION : 44 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 6 8 | NODE_COORD_SECTION 9 | 1 14 68 10 | 2 73 2 11 | 3 13 47 12 | 4 37 44 13 | 5 34 63 14 | 6 58 98 15 | 7 33 42 16 | 8 18 98 17 | 9 24 79 18 | 10 17 28 19 | 11 72 67 20 | 12 78 63 21 | 13 42 48 22 | 14 1 2 23 | 15 2 28 24 | 16 32 82 25 | 17 97 38 26 | 18 39 53 27 | 19 87 1 28 | 20 42 77 29 | 21 83 27 30 | 22 79 92 31 | 23 22 39 32 | 24 58 32 33 | 25 53 84 34 | 26 38 37 35 | 27 63 59 36 | 28 42 88 37 | 29 32 88 38 | 30 38 23 39 | 31 63 32 40 | 32 22 73 41 | 33 88 94 42 | 34 58 78 43 | 35 43 62 44 | 36 73 1 45 | 37 17 32 46 | 38 87 79 47 | 39 12 24 48 | 40 48 53 49 | 41 48 23 50 | 42 7 37 51 | 43 98 77 52 | 44 34 12 53 | DEMAND_SECTION 54 | 1 0 55 | 2 8 56 | 3 24 57 | 4 9 58 | 5 19 59 | 6 9 60 | 7 18 61 | 8 9 62 | 9 14 63 | 10 3 64 | 11 14 65 | 12 8 66 | 13 8 67 | 14 13 68 | 15 18 69 | 16 4 70 | 17 24 71 | 18 14 72 | 19 8 73 | 20 18 74 | 21 13 75 | 22 2 76 | 23 9 77 | 24 18 78 | 25 3 79 | 26 24 80 | 27 8 81 | 28 24 82 | 29 14 83 | 30 13 84 | 31 24 85 | 32 23 86 | 33 9 87 | 34 13 88 | 35 14 89 | 36 14 90 | 37 18 91 | 38 24 92 | 39 4 93 | 40 8 94 | 41 13 95 | 42 4 96 | 43 14 97 | 44 18 98 | DEPOT_SECTION 99 | 1 100 | -1 101 | EOF -------------------------------------------------------------------------------- /Datasets/A-n45-k6.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n45-k6 2 | COMMENT : (Augerat et al, Min no of trucks: 6, Optimal value: 944) 3 | TYPE : CVRP 4 | DIMENSION : 45 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 6 8 | NODE_COORD_SECTION 9 | 1 31 73 10 | 2 11 67 11 | 3 52 96 12 | 4 81 29 13 | 5 97 62 14 | 6 71 5 15 | 7 6 56 16 | 8 48 50 17 | 9 91 17 18 | 10 49 68 19 | 11 85 29 20 | 12 11 16 21 | 13 74 98 22 | 14 56 37 23 | 15 13 81 24 | 16 66 80 25 | 17 96 55 26 | 18 36 17 27 | 19 32 23 28 | 20 6 13 29 | 21 64 30 30 | 22 87 5 31 | 23 75 61 32 | 24 40 72 33 | 25 1 44 34 | 26 60 95 35 | 27 27 49 36 | 28 15 33 37 | 29 46 53 38 | 30 28 43 39 | 31 3 9 40 | 32 1 100 41 | 33 53 46 42 | 34 98 8 43 | 35 6 25 44 | 36 7 81 45 | 37 96 88 46 | 38 2 35 47 | 39 32 94 48 | 40 95 94 49 | 41 9 11 50 | 42 96 16 51 | 43 90 68 52 | 44 33 31 53 | 45 6 59 54 | DEMAND_SECTION 55 | 1 0 56 | 2 19 57 | 3 2 58 | 4 12 59 | 5 20 60 | 6 6 61 | 7 17 62 | 8 8 63 | 9 14 64 | 10 2 65 | 11 8 66 | 12 5 67 | 13 7 68 | 14 22 69 | 15 14 70 | 16 17 71 | 17 23 72 | 18 15 73 | 19 21 74 | 20 2 75 | 21 24 76 | 22 10 77 | 23 20 78 | 24 6 79 | 25 21 80 | 26 10 81 | 27 6 82 | 28 13 83 | 29 21 84 | 30 24 85 | 31 11 86 | 32 16 87 | 33 8 88 | 34 11 89 | 35 11 90 | 36 22 91 | 37 17 92 | 38 22 93 | 39 17 94 | 40 8 95 | 41 23 96 | 42 5 97 | 43 3 98 | 44 18 99 | 45 12 100 | DEPOT_SECTION 101 | 1 102 | -1 103 | EOF -------------------------------------------------------------------------------- /Datasets/A-n48-k7.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n48-k7 2 | COMMENT : (Augerat et al, Min no of trucks: 7, Best value: 1073) 3 | TYPE : CVRP 4 | DIMENSION : 48 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 7 8 | NODE_COORD_SECTION 9 | 1 47 5 10 | 2 1 19 11 | 3 97 35 12 | 4 23 79 13 | 5 77 87 14 | 6 3 9 15 | 7 5 27 16 | 8 41 53 17 | 9 51 87 18 | 10 67 73 19 | 11 89 45 20 | 12 71 99 21 | 13 11 1 22 | 14 85 85 23 | 15 57 11 24 | 16 57 85 25 | 17 71 33 26 | 18 61 13 27 | 19 39 15 28 | 20 13 59 29 | 21 43 99 30 | 22 87 73 31 | 23 11 37 32 | 24 21 11 33 | 25 77 81 34 | 26 3 63 35 | 27 47 95 36 | 28 53 75 37 | 29 73 55 38 | 30 81 71 39 | 31 89 75 40 | 32 11 9 41 | 33 27 37 42 | 34 95 59 43 | 35 63 63 44 | 36 37 21 45 | 37 33 47 46 | 38 23 63 47 | 39 13 55 48 | 40 47 93 49 | 41 45 43 50 | 42 83 7 51 | 43 69 91 52 | 44 13 11 53 | 45 37 15 54 | 46 53 59 55 | 47 97 83 56 | 48 75 31 57 | DEMAND_SECTION 58 | 1 0 59 | 2 20 60 | 3 14 61 | 4 5 62 | 5 11 63 | 6 22 64 | 7 25 65 | 8 2 66 | 9 18 67 | 10 10 68 | 11 26 69 | 12 14 70 | 13 22 71 | 14 9 72 | 15 11 73 | 16 18 74 | 17 24 75 | 18 15 76 | 19 23 77 | 20 16 78 | 21 14 79 | 22 8 80 | 23 5 81 | 24 12 82 | 25 8 83 | 26 16 84 | 27 12 85 | 28 15 86 | 29 9 87 | 30 2 88 | 31 10 89 | 32 2 90 | 33 3 91 | 34 20 92 | 35 3 93 | 36 13 94 | 37 25 95 | 38 23 96 | 39 8 97 | 40 16 98 | 41 9 99 | 42 14 100 | 43 4 101 | 44 13 102 | 45 7 103 | 46 16 104 | 47 18 105 | 48 16 106 | DEPOT_SECTION 107 | 1 108 | -1 109 | EOF -------------------------------------------------------------------------------- /Datasets/A-n55-k9.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n55-k9 2 | COMMENT : (Augerat et al, Min no of trucks: 9, Optimal value: 1073) 3 | TYPE : CVRP 4 | DIMENSION : 55 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 9 8 | NODE_COORD_SECTION 9 | 1 36 64 10 | 2 94 47 11 | 3 10 23 12 | 4 16 46 13 | 5 25 79 14 | 6 41 30 15 | 7 81 45 16 | 8 14 79 17 | 9 42 56 18 | 10 90 17 19 | 11 41 39 20 | 12 21 14 21 | 13 41 46 22 | 14 65 96 23 | 15 13 49 24 | 16 21 14 25 | 17 57 2 26 | 18 14 42 27 | 19 66 62 28 | 20 58 96 29 | 21 5 51 30 | 22 41 50 31 | 23 50 99 32 | 24 84 85 33 | 25 97 90 34 | 26 47 76 35 | 27 11 54 36 | 28 60 97 37 | 29 60 89 38 | 30 58 68 39 | 31 30 93 40 | 32 9 60 41 | 33 47 44 42 | 34 19 40 43 | 35 15 40 44 | 36 88 21 45 | 37 33 58 46 | 38 21 51 47 | 39 57 7 48 | 40 81 6 49 | 41 49 6 50 | 42 51 78 51 | 43 9 62 52 | 44 84 36 53 | 45 95 76 54 | 46 89 44 55 | 47 10 49 56 | 48 69 16 57 | 49 75 66 58 | 50 97 11 59 | 51 74 69 60 | 52 1 14 61 | 53 96 91 62 | 54 46 22 63 | 55 74 92 64 | DEMAND_SECTION 65 | 1 0 66 | 2 3 67 | 3 12 68 | 4 25 69 | 5 4 70 | 6 11 71 | 7 20 72 | 8 21 73 | 9 10 74 | 10 20 75 | 11 13 76 | 12 14 77 | 13 16 78 | 14 17 79 | 15 11 80 | 16 36 81 | 17 6 82 | 18 7 83 | 19 21 84 | 20 11 85 | 21 17 86 | 22 22 87 | 23 10 88 | 24 19 89 | 25 21 90 | 26 23 91 | 27 19 92 | 28 15 93 | 29 22 94 | 30 7 95 | 31 11 96 | 32 15 97 | 33 22 98 | 34 12 99 | 35 24 100 | 36 25 101 | 37 2 102 | 38 15 103 | 39 18 104 | 40 13 105 | 41 3 106 | 42 20 107 | 43 14 108 | 44 10 109 | 45 10 110 | 46 66 111 | 47 10 112 | 48 7 113 | 49 12 114 | 50 24 115 | 51 5 116 | 52 18 117 | 53 7 118 | 54 11 119 | 55 12 120 | DEPOT_SECTION 121 | 1 122 | -1 123 | EOF -------------------------------------------------------------------------------- /Datasets/A-n60-k9.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n60-k9 2 | COMMENT : (Augerat et al, Min no of trucks: 9, Best value: 1408) 3 | TYPE : CVRP 4 | DIMENSION : 60 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 9 8 | NODE_COORD_SECTION 9 | 1 27 93 10 | 2 33 27 11 | 3 29 39 12 | 4 7 81 13 | 5 1 59 14 | 6 49 9 15 | 7 21 53 16 | 8 79 89 17 | 9 81 83 18 | 10 85 11 19 | 11 45 9 20 | 12 7 65 21 | 13 95 27 22 | 14 81 85 23 | 15 37 81 24 | 16 69 69 25 | 17 15 95 26 | 18 89 75 27 | 19 33 93 28 | 20 57 83 29 | 21 11 95 30 | 22 3 57 31 | 23 45 11 32 | 24 43 61 33 | 25 35 43 34 | 26 19 83 35 | 27 83 69 36 | 28 85 77 37 | 29 19 39 38 | 30 83 87 39 | 31 1 13 40 | 32 15 39 41 | 33 83 17 42 | 34 41 97 43 | 35 31 61 44 | 36 59 69 45 | 37 29 15 46 | 38 93 83 47 | 39 63 97 48 | 40 65 57 49 | 41 15 69 50 | 42 31 97 51 | 43 57 9 52 | 44 85 37 53 | 45 21 29 54 | 46 53 11 55 | 47 15 77 56 | 48 41 69 57 | 49 45 17 58 | 50 13 25 59 | 51 63 57 60 | 52 95 5 61 | 53 55 91 62 | 54 3 31 63 | 55 47 7 64 | 56 61 69 65 | 57 85 35 66 | 58 89 81 67 | 59 45 47 68 | 60 65 93 69 | DEMAND_SECTION 70 | 1 0 71 | 2 16 72 | 3 2 73 | 4 7 74 | 5 11 75 | 6 9 76 | 7 17 77 | 8 21 78 | 9 23 79 | 10 10 80 | 11 6 81 | 12 19 82 | 13 18 83 | 14 20 84 | 15 13 85 | 16 5 86 | 17 11 87 | 18 24 88 | 19 2 89 | 20 3 90 | 21 1 91 | 22 5 92 | 23 20 93 | 24 23 94 | 25 24 95 | 26 18 96 | 27 19 97 | 28 2 98 | 29 17 99 | 30 17 100 | 31 9 101 | 32 11 102 | 33 2 103 | 34 6 104 | 35 9 105 | 36 5 106 | 37 9 107 | 38 2 108 | 39 14 109 | 40 19 110 | 41 11 111 | 42 21 112 | 43 20 113 | 44 21 114 | 45 18 115 | 46 48 116 | 47 1 117 | 48 17 118 | 49 42 119 | 50 2 120 | 51 4 121 | 52 24 122 | 53 18 123 | 54 21 124 | 55 11 125 | 56 9 126 | 57 18 127 | 58 22 128 | 59 9 129 | 60 23 130 | DEPOT_SECTION 131 | 1 132 | -1 133 | EOF -------------------------------------------------------------------------------- /Datasets/A-n65-k9.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n65-k9 2 | COMMENT : (Augerat et al, Min no of trucks: 9, Best value: 1177) 3 | TYPE : CVRP 4 | DIMENSION : 65 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 9 8 | NODE_COORD_SECTION 9 | 1 25 51 10 | 2 35 7 11 | 3 93 75 12 | 4 53 95 13 | 5 51 81 14 | 6 51 55 15 | 7 1 67 16 | 8 9 23 17 | 9 75 7 18 | 10 15 97 19 | 11 79 5 20 | 12 9 19 21 | 13 39 1 22 | 14 47 1 23 | 15 33 97 24 | 16 27 83 25 | 17 83 79 26 | 18 17 59 27 | 19 47 19 28 | 20 57 9 29 | 21 87 41 30 | 22 55 25 31 | 23 21 91 32 | 24 21 13 33 | 25 67 1 34 | 26 59 21 35 | 27 1 75 36 | 28 33 85 37 | 29 25 21 38 | 30 45 29 39 | 31 63 77 40 | 32 1 77 41 | 33 77 41 42 | 34 35 11 43 | 35 9 77 44 | 36 61 87 45 | 37 59 91 46 | 38 63 79 47 | 39 97 67 48 | 40 9 45 49 | 41 93 21 50 | 42 83 71 51 | 43 95 57 52 | 44 31 69 53 | 45 77 17 54 | 46 63 57 55 | 47 3 63 56 | 48 11 69 57 | 49 7 9 58 | 50 37 65 59 | 51 75 83 60 | 52 15 53 61 | 53 69 5 62 | 54 69 27 63 | 55 5 19 64 | 56 49 31 65 | 57 77 17 66 | 58 15 7 67 | 59 91 39 68 | 60 79 17 69 | 61 67 75 70 | 62 93 51 71 | 63 25 33 72 | 64 9 19 73 | 65 3 65 74 | DEMAND_SECTION 75 | 1 0 76 | 2 12 77 | 3 24 78 | 4 16 79 | 5 7 80 | 6 9 81 | 7 20 82 | 8 10 83 | 9 18 84 | 10 26 85 | 11 17 86 | 12 2 87 | 13 11 88 | 14 9 89 | 15 12 90 | 16 11 91 | 17 12 92 | 18 23 93 | 19 7 94 | 20 1 95 | 21 26 96 | 22 10 97 | 23 9 98 | 24 22 99 | 25 21 100 | 26 17 101 | 27 2 102 | 28 15 103 | 29 16 104 | 30 14 105 | 31 23 106 | 32 24 107 | 33 2 108 | 34 12 109 | 35 18 110 | 36 5 111 | 37 19 112 | 38 15 113 | 39 8 114 | 40 6 115 | 41 14 116 | 42 13 117 | 43 5 118 | 44 24 119 | 45 25 120 | 46 2 121 | 47 8 122 | 48 14 123 | 49 2 124 | 50 13 125 | 51 10 126 | 52 6 127 | 53 6 128 | 54 24 129 | 55 21 130 | 56 20 131 | 57 24 132 | 58 4 133 | 59 19 134 | 60 14 135 | 61 23 136 | 62 2 137 | 63 16 138 | 64 23 139 | 65 14 140 | DEPOT_SECTION 141 | 1 142 | -1 143 | EOF -------------------------------------------------------------------------------- /Datasets/A-n69-k9.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n69-k9 2 | COMMENT : (Augerat et al, Min no of trucks: 9, Best value: 1168) 3 | TYPE : CVRP 4 | DIMENSION : 69 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 9 8 | NODE_COORD_SECTION 9 | 1 59 44 10 | 2 9 23 11 | 3 84 68 12 | 4 36 93 13 | 5 87 9 14 | 6 34 16 15 | 7 40 98 16 | 8 72 43 17 | 9 0 60 18 | 10 64 90 19 | 11 11 8 20 | 12 46 7 21 | 13 33 54 22 | 14 23 84 23 | 15 67 18 24 | 16 34 93 25 | 17 19 25 26 | 18 14 9 27 | 19 70 64 28 | 20 58 50 29 | 21 5 78 30 | 22 95 39 31 | 23 38 54 32 | 24 50 73 33 | 25 48 46 34 | 26 64 4 35 | 27 39 28 36 | 28 79 30 37 | 29 61 36 38 | 30 28 50 39 | 31 51 91 40 | 32 68 59 41 | 33 14 9 42 | 34 94 87 43 | 35 68 29 44 | 36 12 91 45 | 37 2 22 46 | 38 25 16 47 | 39 11 57 48 | 40 3 51 49 | 41 13 52 50 | 42 9 76 51 | 43 58 18 52 | 44 40 39 53 | 45 32 89 54 | 46 9 92 55 | 47 36 14 56 | 48 82 13 57 | 49 10 25 58 | 50 96 97 59 | 51 20 21 60 | 52 40 91 61 | 53 33 31 62 | 54 72 74 63 | 55 41 24 64 | 56 90 20 65 | 57 4 44 66 | 58 54 22 67 | 59 43 59 68 | 60 3 70 69 | 61 94 16 70 | 62 94 54 71 | 63 14 40 72 | 64 37 0 73 | 65 88 55 74 | 66 80 25 75 | 67 37 64 76 | 68 87 47 77 | 69 18 68 78 | DEMAND_SECTION 79 | 1 0 80 | 2 2 81 | 3 1 82 | 4 6 83 | 5 9 84 | 6 16 85 | 7 5 86 | 8 3 87 | 9 9 88 | 10 12 89 | 11 1 90 | 12 1 91 | 13 18 92 | 14 10 93 | 15 5 94 | 16 5 95 | 17 9 96 | 18 16 97 | 19 12 98 | 20 6 99 | 21 6 100 | 22 20 101 | 23 23 102 | 24 39 103 | 25 17 104 | 26 8 105 | 27 2 106 | 28 13 107 | 29 17 108 | 30 3 109 | 31 2 110 | 32 7 111 | 33 23 112 | 34 10 113 | 35 7 114 | 36 12 115 | 37 20 116 | 38 13 117 | 39 21 118 | 40 25 119 | 41 5 120 | 42 4 121 | 43 13 122 | 44 12 123 | 45 23 124 | 46 19 125 | 47 10 126 | 48 7 127 | 49 15 128 | 50 5 129 | 51 15 130 | 52 13 131 | 53 30 132 | 54 15 133 | 55 7 134 | 56 9 135 | 57 23 136 | 58 8 137 | 59 5 138 | 60 8 139 | 61 25 140 | 62 12 141 | 63 25 142 | 64 24 143 | 65 8 144 | 66 22 145 | 67 7 146 | 68 24 147 | 69 18 148 | DEPOT_SECTION 149 | 1 150 | -1 151 | EOF -------------------------------------------------------------------------------- /Datasets/A-n80-k10.txt: -------------------------------------------------------------------------------- 1 | NAME : A-n80-k10 2 | COMMENT : (Augerat et al, Min no of trucks: 10, Best value: 1764) 3 | TYPE : CVRP 4 | DIMENSION : 80 5 | EDGE_WEIGHT_TYPE : EUC_2D 6 | CAPACITY : 100 7 | TRUCKS : 10 8 | NODE_COORD_SECTION 9 | 1 92 92 10 | 2 88 58 11 | 3 70 6 12 | 4 57 59 13 | 5 0 98 14 | 6 61 38 15 | 7 65 22 16 | 8 91 52 17 | 9 59 2 18 | 10 3 54 19 | 11 95 38 20 | 12 80 28 21 | 13 66 42 22 | 14 79 74 23 | 15 99 25 24 | 16 20 43 25 | 17 40 3 26 | 18 50 42 27 | 19 97 0 28 | 20 21 19 29 | 21 36 21 30 | 22 100 61 31 | 23 11 85 32 | 24 69 35 33 | 25 69 22 34 | 26 29 35 35 | 27 14 9 36 | 28 50 33 37 | 29 89 17 38 | 30 57 44 39 | 31 60 25 40 | 32 48 42 41 | 33 17 93 42 | 34 21 50 43 | 35 77 18 44 | 36 2 4 45 | 37 63 83 46 | 38 68 6 47 | 39 41 95 48 | 40 48 54 49 | 41 98 73 50 | 42 26 38 51 | 43 69 76 52 | 44 40 1 53 | 45 65 41 54 | 46 14 86 55 | 47 32 39 56 | 48 14 24 57 | 49 96 5 58 | 50 82 98 59 | 51 23 85 60 | 52 63 69 61 | 53 87 19 62 | 54 56 75 63 | 55 15 63 64 | 56 10 45 65 | 57 7 30 66 | 58 31 11 67 | 59 36 93 68 | 60 50 31 69 | 61 49 52 70 | 62 39 10 71 | 63 76 40 72 | 64 83 34 73 | 65 33 51 74 | 66 0 15 75 | 67 52 82 76 | 68 52 82 77 | 69 46 6 78 | 70 3 26 79 | 71 46 80 80 | 72 94 30 81 | 73 26 76 82 | 74 75 92 83 | 75 57 51 84 | 76 34 21 85 | 77 28 80 86 | 78 59 66 87 | 79 51 16 88 | 80 87 11 89 | DEMAND_SECTION 90 | 1 0 91 | 2 24 92 | 3 22 93 | 4 23 94 | 5 5 95 | 6 11 96 | 7 23 97 | 8 26 98 | 9 9 99 | 10 23 100 | 11 9 101 | 12 14 102 | 13 16 103 | 14 12 104 | 15 2 105 | 16 2 106 | 17 6 107 | 18 20 108 | 19 26 109 | 20 12 110 | 21 15 111 | 22 13 112 | 23 26 113 | 24 17 114 | 25 7 115 | 26 12 116 | 27 4 117 | 28 4 118 | 29 20 119 | 30 10 120 | 31 9 121 | 32 2 122 | 33 9 123 | 34 1 124 | 35 2 125 | 36 2 126 | 37 12 127 | 38 14 128 | 39 23 129 | 40 21 130 | 41 13 131 | 42 13 132 | 43 23 133 | 44 3 134 | 45 6 135 | 46 23 136 | 47 11 137 | 48 2 138 | 49 7 139 | 50 13 140 | 51 10 141 | 52 3 142 | 53 6 143 | 54 13 144 | 55 2 145 | 56 14 146 | 57 7 147 | 58 21 148 | 59 7 149 | 60 22 150 | 61 13 151 | 62 22 152 | 63 18 153 | 64 22 154 | 65 6 155 | 66 2 156 | 67 11 157 | 68 5 158 | 69 9 159 | 70 9 160 | 71 5 161 | 72 12 162 | 73 2 163 | 74 12 164 | 75 19 165 | 76 6 166 | 77 14 167 | 78 2 168 | 79 2 169 | 80 24 170 | DEPOT_SECTION 171 | 1 172 | -1 173 | EOF -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vehicle-Routing-Problem 2 | The repository details using ant colony optimization and genetic algorithms to optimize VRP for the Computational Intelligence course project at Habib University (Spring 2021) 3 | 4 | # Visualization of a Vehicle Routing Problem 5 | Click on image for Youtube video! 6 | 7 | [![IMAGE ALT TEXT HERE](https://img.youtube.com/vi/WO9a6r6Jce4/0.jpg)](https://www.youtube.com/watch?v=WO9a6r6Jce4) 8 | 9 | # Visualization of a Capacitated Vehicle Routing Problem with Time Window 10 | Click on image for Youtube video! 11 | 12 | [![IMAGE ALT TEXT HERE](https://img.youtube.com/vi/Ox7kWTFZD8w/0.jpg)](https://www.youtube.com/watch?v=Ox7kWTFZD8w) 13 | 14 | # For more details... 15 | 16 | Checkout the attached PDF titled "CI Project Report". 17 | --------------------------------------------------------------------------------