Demo entry 6658838



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

class ACO(object):
    def __init__(self, ant_count: int, generations: int, alpha: float, 
                 beta: float, rho: float, q: int, strategy: int):
        :param ant_count:
        :param generations:迭代次数
        :param alpha: pheromone的相对重要因子
        :param beta: heuristic信息的相对重要因子
        :param rho: pheromone的历史剩余系数
        :param q: pheromone intensity
        :param strategy: pheromone的三种更新策略的选择. 0 - ant-cycle, 1 - ant-quality, 2 - ant-density
        self.Q = q
        self.rho = rho
        self.beta = beta
        self.alpha = alpha
        self.ant_count = ant_count
        self.generations = generations
        self.update_strategy = strategy

    def _update_pheromone(self, graph: Graph, ants: list):
        for i, row in enumerate(graph.pheromone):
            for j, col in enumerate(row):
                graph.pheromone[i][j] *= self.rho
                for ant in ants:
                    graph.pheromone[i][j] += ant.pheromone_delta[i][j]

    def solve(self, graph: Graph):
        :param graph:
        best_cost = float('inf') #初始化最优值设置为最大
        best_solution = []
        for gen in range(self.generations): #迭代求解
            ants = [_Ant(self, graph) for i in range(self.ant_count)] #生成蚂蚁
            for ant in ants:
                for i in range(graph.rank - 1):
                ant.total_cost += graph.matrix[ant.tabu[-1]][ant.tabu[0]]
                if ant.total_cost < best_cost:
                    best_cost = ant.total_cost
                    best_solution = [] + ant.tabu
                ant._update_pheromone_delta() #更新信息素
            self._update_pheromone(graph, ants)

        return best_solution, best_cost

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).