def get_coefs(self, X, Y, inds): from sko.SA import SA_TSP X_train, X_valid, Y_train, Y_valid = train_test_split(X, Y, test_size=0.3) self.fit(X_train, Y_train, inds, search=False) def goal(coefs): self.coefs = coefs.reshape((self.n_estimators, self.n_classes_)) return self.score(X_valid, Y_valid) sa_tsp = SA_TSP(func=goal, x0=self.init_coefs.ravel(), T_max=100, T_min=1, L=10) best_points, _ = sa_tsp.run() return best_points.reshape((self.n_estimators, self.n_classes_))
模拟退火算法 ''' sa = SA(func=func3, x0=[1, 1, 1], T_max=1, T_min=1e-9, L=300, max_stay_counter=150) best_x, best_y = sa.run() print('\n模拟退火算法用于多元函数优化\n') print('best_x:', best_x, 'best_y', best_y) # plt.plot(pd.DataFrame(sa.best_y_history).cummin(axis=0)) # plt.show() sa_tsp = SA_TSP(func=getTotalDistance, x0=range(NUM_POINT), T_max=100, T_min=1, L=10 * NUM_POINT) best_points, best_distance = sa_tsp.run() print('\n模拟退火算法解决TSP问题(旅行商问题)\n') print(best_points, '\nBest Distance:', best_distance) # from matplotlib.ticker import FormatStrFormatter # fig, ax = plt.subplots(1, 2) # best_points_ = np.concatenate([best_points, [best_points[0]]]) # best_points_coordinate = pointsCoordinate[best_points_, :] # 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='-')
'''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.SA import SA_TSP sa_tsp = SA_TSP(func=cal_total_distance, x0=range(num_points), T_max=100, T_min=1, L=10 * num_points) best_points, best_distance = sa_tsp.run() print(best_points, best_distance, cal_total_distance(best_points)) # %% Plot the best routine from matplotlib.ticker import FormatStrFormatter 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(sa_tsp.best_y_history) ax[0].set_xlabel("Distance") ax[0].set_ylabel("Iteration")
distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean') print('distance_matrix is: \n', distance_matrix) 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) # %% print('-------------') print('starting SA for TSP problem ...') from sko.SA import SA_TSP sa_tsp = SA_TSP(func=cal_total_distance, x0=range(num_points)) best_points, best_distance = sa_tsp.fit() print(best_points, best_distance, cal_total_distance(best_points)) 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()
return totalDis problem_set = 'kroC100' tmax = 100 tmin = 1 setting = '%s_SA' % 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(1, 3) sa_tsp = SA_TSP(func=calculateTotalDis, x0=range(len(nodeDis)), T_max=tmax, T_min=tmin, L=10 * len(nodeDis)) best_points, best_distance = sa_tsp.run() best_points_ = np.concatenate([best_points, [best_points[0]]]) ax[0].plot([nodeMap[p][0] for p in best_points_], [nodeMap[p][1] for p in best_points_], 'o-r') ax[0].set_title('SA solution') finish = time.process_time() print('time cost', finish-start) ax[1].plot(sa_tsp.best_y_history) ax[1].set_title('Distance Curve') ax[2].plot([nodeMap[p][0] for p in opt], [nodeMap[p][1] for p in opt], 'o-r') ax[2].set_title('Optimal solution') fig.suptitle('Exp. %s' % setting) plt.savefig('figures/%s_tmax%dtmin%dtime%.1f.jpg' % (setting, tmax, tmin, finish-start)) plt.show()
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)]) from sko.SA import SA_TSP # L * np.log(Tmin/Tmax, decay_coe) tsp_obj = SA_TSP(func=cal_total_distance, x0=range(num_points), T_max=280, T_min=1e-3, L=100*num_points) tsp_obj.cool_down = MethodType(operators.cool_down, tsp_obj) tsp_obj.get_new_x = MethodType(operators.get_new_x, tsp_obj) best_points, best_distance = tsp_obj.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 load_data(f1=1, f2=1, f3=1, f4=1, f5=1, f6=1, f7=1): file_name = 'location_data.csv' data = np.loadtxt(file_name, delimiter=',') transport_data = [] if f1 == 1: transport_data.append(data[0]) if f2 == 1: transport_data.append(data[1]) if f3 == 1: transport_data.append(data[2]) if f4 == 1: transport_data.append(data[3]) if f5 == 1: transport_data.append(data[4]) if f6 == 1: transport_data.append(data[5]) if f7 == 1: transport_data.append(data[6]) points_coordinate = np.zeros((len(transport_data), 2)) volume = np.zeros((len(transport_data))) solids = np.zeros((len(transport_data))) cattle = np.zeros((len(transport_data))) pigs = np.zeros((len(transport_data))) chicken = np.zeros((len(transport_data))) truck_vol = 18 #truck has capacity of 18m3 for n in range(0, len(transport_data)): points_coordinate[n][0:2] = transport_data[n][0:2] volume[n] = transport_data[n][2] solids[n] = transport_data[n][3] cattle[n] = transport_data[n][4] pigs[n] = transport_data[n][5] chicken[n] = transport_data[n][6] max_vol = np.argmax(volume, axis=0) digestor_loc = [points_coordinate[max_vol]] num_points = points_coordinate.shape[0] distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean') distance_matrix = distance_matrix * 111 # 1 degree of lat/lon ~ = 111km print(distance_matrix) distance_home = spatial.distance.cdist( points_coordinate, digestor_loc, metric='euclidean') * 111 def cal_total_distance(routine): '''The objective function. input routine, return total distance. cal_total_distance(np.arange(num_points)) ''' num_points, = routine.shape trip_vol = 0 dist = 0 for i in range(num_points): trip_vol = trip_vol + volume[routine[i % num_points]] trips = 0 dist_home = 0 if trip_vol > truck_vol: trips = trip_vol // truck_vol trip_vol = trip_vol % truck_vol dist_home = dist_home + int( distance_home[routine[i % num_points]]) dist += distance_matrix[routine[i % num_points], routine[ (i + 1) % num_points]] + 2 * dist_home return dist sa_tsp = SA_TSP(func=cal_total_distance, x0=range(num_points), T_max=100, T_min=1, L=10 * num_points) best_points, best_distance = sa_tsp.run() def best_points_route(best_points, start): '''The objective function. input routine, return total distance. cal_total_distance(np.arange(num_points)) ''' num_points, = best_points.shape new_route = [start] trip_vol = 0 dist = 0 for i in range(num_points): trip_vol = trip_vol + volume[best_points[i % num_points]] trips = 0 dist_home = 0 new_route.append(best_points[i]) if best_points[i % num_points] == max_vol: trips = 0 trip_vol = 0 if (trip_vol > truck_vol) & (best_points[i % num_points] != max_vol): trips = trip_vol // truck_vol trip_vol = trip_vol % truck_vol dist_home = dist_home + int( distance_home[best_points[i % num_points]]) new_route.append(max_vol) new_route.append(best_points[i % num_points]) trips = 0 dist = dist + distance_matrix[ best_points[i % num_points], best_points[(i + 1) % num_points]] + 2 * dist_home return new_route final_best = best_points_route(best_points, max_vol) print(type(final_best)) #Total volumes (m3) are the daily volumes of all the farms per day total_volume = total_vol(volume) total_solids_perc = vol_breakdown(volume, solids) total_cattle_perc = vol_breakdown(volume, cattle) total_pig_perc = vol_breakdown(volume, pigs) total_chicken_perc = vol_breakdown(volume, chicken) manure_comp = [total_cattle_perc, total_pig_perc, total_chicken_perc] from matplotlib.ticker import FormatStrFormatter final_best.append(max_vol) best_points_ = np.array(final_best) best_points_coordinate = points_coordinate[best_points_, :] print("The best route is: " + str(final_best) + " and the distance on this route is " + str(best_distance)) print("Optimal location is area # " + str(max_vol) + " in radians for DIGESTOR is latitude: " + str(digestor_loc[0][0]) + " and longitude: " + str(digestor_loc[0][1])) print("Total daily distance from farms to digestor travelled is " + str(best_distance) + " km") print("Total VOLUME manure supplied per day is " + str(total_volume) + " m3") print("Weighted average solids percentage of the manure supplied is " + str(total_solids_perc * 100) + " %") print("Manure composition is CATTLE-PIGS-CHICKS is " + str(manure_comp)) fig, ax = plt.subplots(1, 2) 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='c', 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() return [best_distance, total_volume, total_solids_perc, manure_comp]
def load_data(f1=1,f2=1,f3=1,f4=1,f5=1,f6=1,f7=1,dict_total=dict_total, printt=False): #file_name = 'location_data.csv' #data = np.loadtxt(file_name, delimiter=',') Farm_data = dict_total["Farm_data"] transport_data = [] #Farm_name = [Longitude, Latitudem Volume_per_day, Solid_percentage, cattle_percentage, pig_percentage, poultry_percentrage] if f1==1: transport_data.append(np.array(Farm_data["Farm_1"])) if f2==1: transport_data.append(np.array(Farm_data["Farm_2"])) if f3==1: transport_data.append(np.array(Farm_data["Farm_3"])) if f4==1: transport_data.append(np.array(Farm_data["Farm_4"])) if f5==1: transport_data.append(np.array(Farm_data["Farm_5"])) if f6==1: transport_data.append(np.array(Farm_data["Farm_6"])) if f7==1: transport_data.append(np.array(Farm_data["Farm_7"])) points_coordinate = np.zeros((len(transport_data),2)) volume = np.zeros((len(transport_data))) solids = np.zeros((len(transport_data))) cattle = np.zeros((len(transport_data))) pigs = np.zeros((len(transport_data))) chicken = np.zeros((len(transport_data))) truck_vol = dict_total['V_per_truck'] #truck has capacity of 18m3 for n in range(0,len(transport_data)): points_coordinate[n][0:2]=transport_data[n][0:2] volume[n] = transport_data[n][2] solids[n] = transport_data[n][3] cattle[n] = transport_data[n][4] pigs[n] = transport_data[n][5] chicken[n] = transport_data[n][6] max_vol = np.argmax(volume, axis=0) digestor_loc, farm_digestor = optimal_loc(points_coordinate,volume, max_vol) num_points = points_coordinate.shape[0] distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean') distance_matrix = distance_matrix * 111 # 1 degree of lat/lon ~ = 111km #print(distance_matrix) distance_home = spatial.distance.cdist(points_coordinate, digestor_loc, metric='euclidean')*111 def cal_total_distance(routine): '''The objective function. input routine, return total distance. cal_total_distance(np.arange(num_points)) ''' num_points, = routine.shape trip_vol = 0 dist = 0 for i in range(num_points): trip_vol = trip_vol + volume[routine[i % num_points]] trips = 0 dist_home = 0 if trip_vol>truck_vol: trips = trip_vol // truck_vol trip_vol = trip_vol % truck_vol dist_home = dist_home + int(distance_home[routine[i % num_points]]) dist += distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] + 2*dist_home return dist if f1+f2+f3+f4+f5+f6+f7 >2: sa_tsp = SA_TSP(func=cal_total_distance, x0=range(num_points), T_max=100, T_min=1, L=10 * num_points) best_points, best_distance = sa_tsp.run() elif f1+f2+f3+f4+f5+f6+f7 ==2: if volume[1]>volume[0]: best_points = np.array([1,0]) else: best_points = np.array([0,1]) best_distance = cal_total_distance(best_points) elif f1+f2+f3+f4+f5+f6+f7 ==1: best_points = np.array([0]) best_distance = 0 def best_points_route(best_points, start): '''The objective function. input routine, return total distance. cal_total_distance(np.arange(num_points)) ''' num_points, = best_points.shape new_route = [start] trip_vol = 0 dist = 0 for i in range(num_points): trip_vol = trip_vol + volume[best_points[i % num_points]] trips = 0 dist_home = 0 new_route.append(best_points[i]) if best_points[i % num_points]==farm_digestor: trips = 0 trip_vol = 0 if (trip_vol>truck_vol) & (best_points[i % num_points]!=farm_digestor): trips = trip_vol // truck_vol trip_vol = trip_vol % truck_vol dist_home = dist_home + int(distance_home[best_points[i % num_points]]) new_route.append(farm_digestor) new_route.append(best_points[i % num_points]) trips = 0 dist = dist + distance_matrix[best_points[i % num_points], best_points[(i + 1) % num_points]] + 2*dist_home return new_route #print("BEST POINTS") best_points = np.delete(best_points,np.where(best_points==farm_digestor)) #print(best_points) #print(type(best_points)) final_best = best_points_route(best_points, farm_digestor) #Total volumes (m3) are the daily volumes of all the farms per day total_volume = total_vol(volume) total_solids_perc = vol_breakdown(volume, solids) total_cattle_perc = vol_breakdown(volume, cattle) total_pig_perc = vol_breakdown(volume, pigs) total_chicken_perc = vol_breakdown(volume, chicken) manure_comp = [total_cattle_perc, total_pig_perc, total_chicken_perc] from matplotlib.ticker import FormatStrFormatter if (final_best[-1])!=farm_digestor: final_best.append(farm_digestor) best_points_ = np.array(final_best) best_points_coordinate = points_coordinate[best_points_, :] #print(volume) if printt: print("The best route is: "+str(final_best)+" and the distance on this route is "+str(best_distance)) print("The route is as follow:") print(best_points_coordinate) print("Optimal location is area # "+str(farm_digestor)+" in radians for DIGESTOR is latitude: "+str(digestor_loc[0][0])+" and longitude: "+str(digestor_loc[0][1])) print("Total daily distance from farms to digestor travelled is "+str(best_distance)+" km") print("Total VOLUME manure supplied per day is "+str(total_volume)+" m3") print("Weighted average solids percentage of the manure supplied is "+str(total_solids_perc*100)+" %") print("Manure composition is CATTLE-PIGS-CHICKS is "+str(manure_comp)) #fig, ax = plt.subplots(1, 2) #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='c', 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() return [best_distance, total_volume, total_solids_perc, manure_comp,final_best]