def kakak(): ga_tsp = GA_TSP(func=cal_total_weight, n_dim=flow_nums, size_pop=50, max_iter=200, prob_mut=0.06) best_goods, best_value = ga_tsp.run() print(best_goods, best_value) point2(ga_tsp)
def _GA_start(flows_len): if(flows_len%2!=0): flows_len=flows_len-1 len=flows_len ga_tsp = GA_TSP(func=_GA_Fit, n_dim=len, size_pop=len, max_iter=200,prob_mut=0.06) best_goods, best_value = ga_tsp.run() print(best_goods, best_value) #point2(ga_tsp) return best_goods
def GA_go(self): ga_tsp = GA_TSP(func=self.cal_total_weight, points=self.flow, pop=50, max_iter=100, Pm=0.01) best_goods, best_value = ga_tsp.fit() print(best_goods, best_value) Y_history = pd.DataFrame(ga_tsp.FitV_history) fig, ax = plt.subplots(2, 1) ax[0].plot(Y_history.index, Y_history.values, '.', color='red') Y_history.min(axis=1).cummin().plot(kind='line') plt.show()
def kaka(self): ga_tsp = GA_TSP(func=cal_total_weight, n_dim=flow_nums, size_pop=flow_nums, max_iter=500, prob_mut=0.01) best_goods, best_value = ga_tsp.run() print(best_goods, best_value) fit_history = pd.DataFrame(ga_tsp.all_history_Y) fig, ax = plt.subplots(2, 1) ax[0].plot(fit_history.index, fit_history.values, '.', color='red') plt_min = fit_history.min(axis=1) ax[1].plot(plt_min.index, plt_min, Label='min') ax[1].plot(plt_min.index, plt_min.cummin()) # fit_history.max(axis=1).cummin().plot(kind='line') plt.show()
def Get_Data(_num_points=20): num_points = _num_points points_coordinate = np.random.rand(num_points, 2) * 10 # generate coordinate of points distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean') def cal_total_distance(routine): '''The objective function. input routine, return total distance. cal_total_distance(np.arange(num_points)) ''' num_points, = routine.shape return sum([ distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points) ]) # %% do GA ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=50, max_iter=500, prob_mut=1) best_points, best_distance = ga_tsp.run() return points_coordinate.tolist(), best_points, best_distance
def find_path(dist_mat, num_points, max_iter=1000): distance_matrix = dist_mat 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) ]) ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=200, max_iter=max_iter, prob_mut=0.4) return ga_tsp
# 目标函数,输入路径 返回总距离 # 使用方式:compute_distance(np.arange(num_points)) def compute_distance(routine): num_points, = routine.shape #print(routine) #print(routine.shape) # 求和 return sum([ distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points) ]) # 遗传算法 from sko.GA import GA_TSP # prob_mut 种群的新成员由变异而非交叉得来的概率 ga_tsp = GA_TSP(func=compute_distance, n_dim=num_points, size_pop=50, max_iter=500, prob_mut=0.2) best_points, best_distance = ga_tsp.run() # 画图 fig, ax = plt.subplots(1, 2) best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') ax[1].plot(ga_tsp.generation_best_Y) plt.show()
distanceMatrix = spatial.distance.cdist(pointsCoordinate, pointsCoordinate, metric='euclidean') def getTotalDistance(routine): num_points, = routine.shape return sum([ distanceMatrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points) ]) ga_tsp = GA_TSP(func=getTotalDistance, n_dim=NUM_POINT, size_pop=50, max_iter=500, prob_mut=1) best_points, best_distance = ga_tsp.run() print('\n遗传旅行商\n') print(best_points, '\nbest Distance:', best_distance) # fig, ax = plt.subplots(1, 2) # best_points_ = np.concatenate([best_points, [best_points[0]]]) # best_points_coordinate = pointsCoordinate[best_points_, :] # ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') # ax[1].plot(ga_tsp.generation_best_Y) # plt.show() ''' 粒子群算法 '''
'''The objective function. input routine, return total distance. cal_total_distance(np.arange(num_points)) ''' 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.GA import GA_TSP # 3 * size_pop * max_iter ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=100, max_iter=2400, prob_mut=0.07) ga_tsp.register(operator_name='crossover', operator=operators.crossover_ox) best_points, best_distance = ga_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('GA: ' + str(best_distance)) plt.xlabel('X') plt.ylabel('Y') plt.scatter(X, Y, s=140)
def cal_total_distance(routine): '''The objective function. input routine, return total distance. cal_total_distance(np.arange(num_points)) ''' num_points, = routine.shape return sum([ distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points) ]) # %% do GA from sko.GA import GA_TSP ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=300, max_iter=800, Pm=0.3) best_points, best_distance = ga_tsp.run() # %% plot fig, ax = plt.subplots(1, 1) best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') plt.show()
def runGA(): ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=8, max_iter=10, prob_mut=0.1) return ga_tsp.run()
# demo: GA for TSP with UDF(user defined functions) import numpy as np # step1: randomly generate the data from sko.demo_func import function_for_TSP num_points, points_coordinate, distance_matrix, cal_total_distance = function_for_TSP( num_points=15) # %%step2: DO GA with UDF from sko.GA import GA_TSP from sko.operators import ranking, selection, crossover, mutation ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=50, max_iter=100, prob_mut=1) ga_tsp.register('selection', selection.selection_tournament, tourn_size=3). \ register('mutation', mutation.mutation_reverse) best_points, best_distance = ga_tsp.run() print('best routine:', best_points, 'best_distance:', best_distance) # %% # step3: plot import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') plt.show()
# 距离矩阵 distance_matrix = spatial.distance.cdist(points_coordinate, 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) ]) ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=50, max_iter=500, prob_mut=1) best_points, best_distance = ga_tsp.run() print('best_points:', best_points) print('best_distance:', best_distance) fig, ax = plt.subplots(1, 2) # 连接两个矩阵 best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') ax[1].plot(ga_tsp.generation_best_Y) plt.show()
np.random.seed(2021) start = pd.Timestamp.now() dim = 10 # initial number of breweries from which to start incr = 5 # increment by this number of breweries best_distance = 0 # Find out optimal number dims (breweries) while best_distance < MAX_DISTANCE: dim += incr ga_tsp = GA_TSP(func=cal_total_distance, n_dim=dim, size_pop=num_points, max_iter=200, prob_mut=0.7) best_points, best_distance = ga_tsp.run() # Retrain final result with more iterations dim -= 5 ga_tsp = GA_TSP(func=cal_total_distance, n_dim=dim, size_pop=num_points, max_iter=500, prob_mut=0.7) best_points, best_distance = ga_tsp.run() # reorder the whole route so that start and end is at HOME (index 0) ls = list(best_points)
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sko.demo_func import function_for_TSP num_points, points_coordinate, distance_matrix, cal_total_distance = function_for_TSP( num_points=50) # %% from sko.GA import GA_TSP ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, pop=500, max_iter=2000, Pm=0.3) best_points, best_distance = ga_tsp.fit() # %% fig, ax = plt.subplots(1, 1) best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') plt.show() #%% # import matplotlib.pyplot as plt # # Y_history = ga_tsp.all_history_Y
''' problem_set = 'kroC100' size_pop = 30 prob_mut = 0.5 setting = '%s_A2' % problem_set start = time.process_time() nodeMap, nodeDis = readData('tsp_data/%s.tsp' % problem_set) opt = readOpt('tsp_data/%s.opt.tour' % problem_set) opt_distance = calculateTotalDis(opt) opt = np.concatenate([opt, [opt[0]]]) fig, ax = plt.subplots(2, 2) ga_tsp = GA_TSP(func=calculateTotalDis, n_dim=len(nodeDis), size_pop=size_pop, max_iter=2000, prob_mut=prob_mut) best_points, best_distance = ga_tsp.run(1) best_points_ = np.concatenate([best_points, [best_points[0]]]) ax[0][0].plot([nodeMap[p][0] for p in best_points_], [nodeMap[p][1] for p in best_points_], 'o-r') ax[0][0].set_title('GA Initial solution') for itr in range(100): best_points, best_distance = ga_tsp.run(100) best_points_ = np.concatenate([best_points, [best_points[0]]]) # ax[itr].plot([nodeMap[p][0] for p in best_points_], [nodeMap[p][1] for p in best_points_], 'o-r') print('itr', itr * 100, '. distance %.2f' % best_distance, 'dif to opt %.2f' % (best_distance - opt_distance)) if best_distance < opt_distance + 0.01: break
cal_total_distance(np.arange(num_points)) ''' num_points, = routine.shape return sum([ distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points) ]) # %% do GA from sko.GA import GA_TSP start = time.time() ga_tsp = GA_TSP(func=cal_total_distance, n_dim=distance_matrix.shape[0], size_pop=50, max_iter=500, prob_mut=0.2) best_points, best_distance = ga_tsp.run() end = time.time() print(best_points) print(best_distance) print("程序的运行时间是:%s" % (end - start)) np.save('../data/all_feature/all_feature_sequence.npy', best_points) # 读入feature.name文件 162 f_name = [] with open('../data/feature.name', 'r') as f_name_file: for line in f_name_file: f_name.append(line.strip())
c += 1 else: capacity = max(capacity, c + 1) c = 0 capacity = max(capacity, c + 1) return capacity - max_capacity # %% from sko.GA import GA_TSP ga_tsp = GA_TSP( func=cal_total_distance, n_dim=num_customers, size_pop=50, max_iter=500, prob_mut=1, ) # The index of customers range from 1 to num_customers: ga_tsp.Chrom = np.concatenate([ np.zeros(shape=(ga_tsp.size_pop, num_vehicle - 1), dtype=np.int), ga_tsp.Chrom + 1 ], axis=1) ga_tsp.has_constraint = True ga_tsp.constraint_ueq = [constraint_capacity] best_points, best_distance = ga_tsp.run() # %%
# demo: GA for TSP with UDF(user defined functions) import numpy as np # step1: randomly generate the data from sko.demo_func import function_for_TSP num_points, points_coordinate, distance_matrix, cal_total_distance = function_for_TSP( num_points=15) # step2: DO GA with UDF from sko.GA import GA_TSP from sko.GA import selection_tournament, mutation_TSP_1 ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=500, max_iter=800, Pm=0.2) ga_tsp.register('selection', selection_tournament, tourn_size=3). \ register('mutation', mutation_TSP_1) best_points, best_distance = ga_tsp.fit() print('best routine:', best_points, 'best_distance:', best_distance) # %% # step3: plot import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') plt.show()