Professional Documents
Culture Documents
Swarm Assignment 2
Swarm Assignment 2
Ayush Malik(2k17/CO/087)
1. TRAVELLING SALESPERSON USING PARTICLE SWARM ALGORITHM
CODE :
total_cost = 0
for i in range(self.amount_vertices - 1):
total_cost += self.edges[(path[i], path[i+1])]
initial_vertice = random.choice(list_vertices)
if initial_vertice not in list_vertices:
print('Error: initial vertice %d not exists!' % initial_vertice)
sys.exit(1)
list_vertices.remove(initial_vertice)
list_vertices.insert(0, initial_vertice)
for i in range(max_size):
list_temp = list_vertices[1:]
random.shuffle(list_temp)
list_temp.insert(0, initial_vertice)
return random_paths
# current solution
self.solution = solution
# set costs
self.cost_current_solution = cost
self.cost_pbest_solution = cost
# set pbest
def setPBest(self, new_pbest):
self.pbest = new_pbest
# set solution
def setCurrentSolution(self, solution):
self.solution = solution
# gets solution
def getCurrentSolution(self):
return self.solution
# PSO algorithm
class PSO:
# creates the particles and initialization of swap sequences in all the particles
for solution in solutions:
# creates a new particle
particle = Particle(solution=solution, cost=graph.getCostPath(solution))
# add the particle
self.particles.append(particle)
# updates "size_population"
self.size_population = len(self.particles)
print('Showing particles...\n')
for particle in self.particles:
print('pbest: %s\t|\tcost pbest: %d\t|\tcurrent solution: %s\t|\tcost current solution: %d' \
% (str(particle.getPBest()), particle.getCostPBest(), str(particle.getCurrentSolution()),
particle.getCostCurrentSolution()))
print('')
def run(self):
# updates velocity
particle.setVelocity(temp_velocity)
if __name__ == "__main__":
OUTPUT :
CODE :
import math
import random
from matplotlib import pyplot as plt
class SolveTSPUsingACO:
class Edge:
def __init__(self, a, b, weight, initial_pheromone):
self.a = a
self.b = b
self.weight = weight
self.pheromone = initial_pheromone
class Ant:
def __init__(self, alpha, beta, num_nodes, edges):
self.alpha = alpha
self.beta = beta
self.num_nodes = num_nodes
self.edges = edges
self.tour = None
self.distance = 0.0
def _select_node(self):
roulette_wheel = 0.0
unvisited_nodes = [node for node in range(self.num_nodes) if node not in self.tour]
heuristic_total = 0.0
for unvisited_node in unvisited_nodes:
heuristic_total += self.edges[self.tour[-1]][unvisited_node].weight
for unvisited_node in unvisited_nodes:
roulette_wheel += pow(self.edges[self.tour[-1]][unvisited_node].pheromone, self.alpha) * \
pow((heuristic_total / self.edges[self.tour[-1]][unvisited_node].weight), self.beta)
random_value = random.uniform(0.0, roulette_wheel)
wheel_position = 0.0
for unvisited_node in unvisited_nodes:
wheel_position += pow(self.edges[self.tour[-1]][unvisited_node].pheromone, self.alpha) * \
pow((heuristic_total / self.edges[self.tour[-1]][unvisited_node].weight), self.beta)
if wheel_position >= random_value:
return unvisited_node
def find_tour(self):
self.tour = [random.randint(0, self.num_nodes - 1)]
while len(self.tour) < self.num_nodes:
self.tour.append(self._select_node())
return self.tour
def get_distance(self):
self.distance = 0.0
for i in range(self.num_nodes):
self.distance += self.edges[self.tour[i]][self.tour[(i + 1) % self.num_nodes]].weight
return self.distance
def _acs(self):
for step in range(self.steps):
for ant in self.ants:
self._add_pheromone(ant.find_tour(), ant.get_distance())
if ant.distance < self.global_best_distance:
self.global_best_tour = ant.tour
self.global_best_distance = ant.distance
for i in range(self.num_nodes):
for j in range(i + 1, self.num_nodes):
self.edges[i][j].pheromone *= (1.0 - self.rho)
def _elitist(self):
for step in range(self.steps):
for ant in self.ants:
self._add_pheromone(ant.find_tour(), ant.get_distance())
if ant.distance < self.global_best_distance:
self.global_best_tour = ant.tour
self.global_best_distance = ant.distance
self._add_pheromone(self.global_best_tour, self.global_best_distance, weight=self.elitist_weight)
for i in range(self.num_nodes):
for j in range(i + 1, self.num_nodes):
self.edges[i][j].pheromone *= (1.0 - self.rho)
def _max_min(self):
for step in range(self.steps):
iteration_best_tour = None
iteration_best_distance = float("inf")
for ant in self.ants:
ant.find_tour()
if ant.get_distance() < iteration_best_distance:
iteration_best_tour = ant.tour
iteration_best_distance = ant.distance
if float(step + 1) / float(self.steps) <= 0.75:
self._add_pheromone(iteration_best_tour, iteration_best_distance)
max_pheromone = self.pheromone_deposit_weight / iteration_best_distance
else:
if iteration_best_distance < self.global_best_distance:
self.global_best_tour = iteration_best_tour
self.global_best_distance = iteration_best_distance
self._add_pheromone(self.global_best_tour, self.global_best_distance)
max_pheromone = self.pheromone_deposit_weight / self.global_best_distance
min_pheromone = max_pheromone * self.min_scaling_factor
for i in range(self.num_nodes):
for j in range(i + 1, self.num_nodes):
self.edges[i][j].pheromone *= (1.0 - self.rho)
if self.edges[i][j].pheromone > max_pheromone:
self.edges[i][j].pheromone = max_pheromone
elif self.edges[i][j].pheromone < min_pheromone:
self.edges[i][j].pheromone = min_pheromone
def run(self):
print('Started : {0}'.format(self.mode))
if self.mode == 'ACS':
self._acs()
elif self.mode == 'Elitist':
self._elitist()
else:
self._max_min()
print('Ended : {0}'.format(self.mode))
print('Sequence : <- {0} ->'.format(' - '.join(str(self.labels[i]) for i in self.global_best_tour)))
print('Total distance travelled to complete the tour : {0}\n'.format(round(self.global_best_distance, 2)))
if __name__ == '__main__':
_colony_size = 50
_steps = 50
_nodes = [(random.uniform(-400, 400), random.uniform(-400, 400)) for _ in range(0, 15)]
acs = SolveTSPUsingACO(mode='ACS', colony_size=_colony_size, steps=_steps, nodes=_nodes)
acs.run()
acs.plot()
elitist = SolveTSPUsingACO(mode='Elitist', colony_size=_colony_size, steps=_steps, nodes=_nodes)
elitist.run()
elitist.plot()
max_min = SolveTSPUsingACO(mode='MaxMin', colony_size=_colony_size, steps=_steps, nodes=_nodes)
max_min.run()
max_min.plot()
OUTPUT :