예제 #1
0
    def ant_colony(self, pop=50, num_iter=200):
        dst_matrix = self.dst
        path = []

        def cal_total_distance(routine):
            num_points, = routine.shape
            return sum([
                dst_matrix[routine[i % num_points],
                           routine[(i + 1) % num_points]]
                for i in range(num_points)
            ])

        aca = ACA_TSP(func=cal_total_distance,
                      n_dim=self.num_nodes,
                      size_pop=pop,
                      max_iter=num_iter,
                      distance_matrix=self.dst)

        # aca = ACA_TSP_Graph(func=cal_total_distance, n_dim=self.num_nodes,
        #                     size_pop=pop, max_iter=num_iter,
        #                     distance_matrix=self.dst, graph=self.graph)

        path_index, path_dst = aca.run()

        travelled_dst = 0
        for i in range(len(path_index)):
            idx = path_index[i]
            path.append(self.nodes[idx])
            if i >= 1:
                former_idx = path_index[i - 1]
                travelled_dst = travelled_dst + self.real_dst[former_idx, idx]
        return path, travelled_dst
예제 #2
0
# ax[0].plot(sa_tsp.best_y_history)
# ax[0].set_xlabel("Iteration")
# ax[0].set_ylabel("Distance")
# ax[1].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1],
#            marker='o', markerfacecolor='b', color='r', linestyle='-')
# ax[1].xaxis.set_major_formatter(FormatStrFormatter('%.3f'))
# ax[1].yaxis.set_major_formatter(FormatStrFormatter('%.3f'))
# ax[1].set_xlabel("Longitude")
# ax[1].set_ylabel("Latitude")
# plt.show()
'''
蚁群算法(好慢)
'''
aca = ACA_TSP(func=getTotalDistance,
              n_dim=NUM_POINT,
              size_pop=50,
              max_iter=200,
              distance_matrix=distanceMatrix)
best_points, best_distance = aca.run()
print('\n蚁群算法\n')
print('best_points:', best_points, '\nbest_distance', best_distance)
'''
免疫优化算法(也好慢)
'''
ia_tsp = IA_TSP(func=getTotalDistance,
                n_dim=NUM_POINT,
                size_pop=500,
                max_iter=800,
                prob_mut=0.2,
                T=0.7,
                alpha=0.95)
    '''
    num_points, = routine.shape
    return sum([
        distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]]
        for i in range(num_points)
    ])


from sko.ACA import ACA_TSP

# size_pop * max_iter
aca_tsp = ACA_TSP(
    func=cal_total_distance,
    n_dim=num_points,
    size_pop=100,
    max_iter=300,
    distance_matrix=distance_matrix,
    alpha=0.01,
    beta=14,
    rho=0.1,
)

best_points, best_distance = aca_tsp.run()

X = data_cities[best_points, 1]
Y = data_cities[best_points, 2]

plt.figure(figsize=(12, 8))
# plt.title('TSP Graph')
plt.title('ACO: ' + str(best_distance))
plt.xlabel('X')
plt.ylabel('Y')
예제 #4
0
                                         points_coordinate,
                                         metric='euclidean')


def cal_total_distance(routine):
    num_points, = routine.shape
    return sum([
        distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]]
        for i in range(num_points)
    ])


# %% Do ACA
from sko.ACA import ACA_TSP

aca = ACA_TSP(func=cal_total_distance,
              n_dim=num_points,
              size_pop=50,
              max_iter=200,
              distance_matrix=distance_matrix)

best_x, best_y = aca.run()

# %% Plot
fig, ax = plt.subplots(1, 2)
best_points_ = np.concatenate([best_x, [best_x[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r')
pd.DataFrame(aca.y_best_history).cummin().plot(ax=ax[1])
plt.show()
예제 #5
0
def cal_total_distance(routine):
    num_points, = routine.shape
    return sum([
        distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]]
        for i in range(num_points)
    ])


# test:
points = np.arange(num_points)  # generate index of points
cal_total_distance(points)

# %% Do ACA
from sko.ACA import ACA_TSP

aca = ACA_TSP(func=cal_total_distance,
              n_dim=8,
              size_pop=10,
              max_iter=20,
              distance_matrix=distance_matrix)

best_x, best_y = aca.run()

# %% Plot
fig, ax = plt.subplots(1, 1)
best_points_ = np.concatenate([best_x, [best_x[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r')
plt.show()