Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from copy import deepcopy
- import numpy as np
- from numpy import inf
- import random
- ant = 4
- iterations = 10
- initial_pheromone = 0.1
- alpha = 1
- beta = 1
- pheromone_evaporation_rate = 0.01
- Q = 10
- vertice = 4
- distance_array = np.array([[0, 9, 7, 2,]
- ,[9, 0, 1, 5]
- ,[7, 1, 0, 6]
- ,[2, 5, 6, 0]])
- '''
- with open("C:/Users/guilo/Downloads/cos/sos/test.txt", "r") as txt_file:
- distance_array = np.array([list(map(int, line.split())) for line in txt_file])
- '''
- ant_path = np.zeros((ant, vertice+1))
- best_distance = np.zeros((ant, 1))
- draw_first_position = np.random.randint(0, vertice)
- size = len(ant_path)
- for i in range(vertice):
- ant_path[i][0] = draw_first_position
- ant_path[i][size] = draw_first_position
- visibility = 1 / distance_array
- visibility[visibility == inf] = 0
- pheromone = 0.1 * np.ones((ant, ant))
- product_p_v = pheromone*visibility
- sum = 0
- visibility_sum = np.zeros((vertice, 1))
- for i in range(vertice):
- for j in range(vertice):
- sum += product_p_v[i][j]
- visibility_sum[i][0] = sum
- sum = 0
- probability = np.zeros((vertice, vertice))
- for i in range(vertice):
- for j in range(vertice):
- probability[i][j] = product_p_v[i][j] / visibility_sum[i][0]
- current_position = draw_first_position
- moviment_ant = 1
- ant_number = 0
- for j in range(vertice):
- sum += probability[current_position][j]
- copy_probability = deepcopy(probability)
- while(ant_number != ant):
- while(moviment_ant != vertice):
- draw = random.uniform(0, sum)
- while draw == 0.0:
- draw = random.uniform(0, sum)
- accumulated = 0
- for j in range(vertice):
- prob = copy_probability[current_position][j] / sum
- accumulated += prob
- if(draw <= accumulated):
- next_position = j
- j = vertice
- break
- ant_path[ant_number][moviment_ant] = next_position
- moviment_ant += 1
- previous_position = current_position
- for i in range(vertice):
- for j in range(vertice):
- if i == previous_position or j == previous_position:
- copy_probability[i][j] = 0
- current_position = next_position
- sum = 0
- for i in range(vertice):
- sum += copy_probability[current_position][i]
- ant_number += 1
- copy_probability = deepcopy(probability)
- sum = 0
- current_position = draw_first_position
- for j in range(vertice):
- sum += copy_probability[current_position][j]
- moviment_ant = 1
- print(ant_path)
Advertisement
Add Comment
Please, Sign In to add comment