Demo entry 6658842

show

   

Submitted by anonymous on Nov 08, 2017 at 13:14
Language: Python 3. Code size: 2.3 kB.

class _Ant(object):
    def __init__(self, aco: ACO, graph: Graph):
        self.colony = aco
        self.graph = graph
        self.total_cost = 0.0
        self.tabu = []  # 禁忌表
        self.pheromone_delta = []  
        self.allowed = [i for i in range(graph.rank)]  
        self.eta = [[0 if i == j else 1 / graph.matrix[i][j] for j in range(graph.rank)] for i in
                    range(graph.rank)]  
        start = random.randint(0, graph.rank - 1)  
        self.tabu.append(start)
        self.current = start
        self.allowed.remove(start)

    def _select_next(self):
        denominator = 0
        for i in self.allowed:
            denominator += self.graph.pheromone[self.current][i] ** self.colony.alpha * self.eta[self.current][
                                                                                            i] ** self.colony.beta
       
        probabilities = [0 for i in range(self.graph.rank)]  
        for i in range(self.graph.rank):
            try:
                self.allowed.index(i) 
                probabilities[i] = self.graph.pheromone[self.current][i] ** self.colony.alpha * \
                    self.eta[self.current][i] ** self.colony.beta / denominator
            except ValueError:
                pass  # do nothing
       
        selected = 0
        rand = random.random()
        for i, probability in enumerate(probabilities):
            rand -= probability
            if rand <= 0:
                selected = i
                break
        self.allowed.remove(selected)
        self.tabu.append(selected)
        self.total_cost += self.graph.matrix[self.current][selected]
        self.current = selected

    
    def _update_pheromone_delta(self):
        self.pheromone_delta = [[0 for j in range(self.graph.rank)] for i in range(self.graph.rank)]
        for _ in range(1, len(self.tabu)):
            i = self.tabu[_ - 1]
            j = self.tabu[_]
            if self.colony.update_strategy == 1: 
                self.pheromone_delta[i][j] = self.colony.Q
            elif self.colony.update_strategy == 2:
                
                self.pheromone_delta[i][j] = self.colony.Q / self.graph.matrix[i][j]
            else: 
                self.pheromone_delta[i][j] = self.colony.Q / self.total_cost

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).