Exemplo n.º 1
0
 def Two_Opt_solver(self, G_prime, G_prime_nodes, start_index,
                    cluster_center_drop_off):
     tsp = TSP()
     tsp.read_mat(nx.adjacency_matrix(G_prime).todense())
     two_opt = TwoOpt_solver(initial_tour='NN', iter_num=100)
     best_tour = tsp.get_approx_solution(two_opt)
     center_tour = [G_prime_nodes[node] for node in best_tour]
     if (center_tour.count(start_index) == 1):
         start_loc = center_tour.index(start_index)
         center_tour = center_tour[start_loc:] + center_tour[:start_loc] + [
             start_index
         ]
     tour = [(center_tour[i], center_tour[i + 1])
             for i in range(len(center_tour) - 1)]
     rao_tour_1 = compute_tour_paths(self.G, tour)
     rao_tour_1 = [
         rao_tour_1[i] for i in range(len(rao_tour_1) - 1)
         if rao_tour_1[i] != rao_tour_1[i + 1]
     ] + [start_index]
     cost_1 = self.faster_cost_solution(rao_tour_1, cluster_center_drop_off)
     return rao_tour_1, cost_1
def make_path(X, D):
    tsp = TSP()
    # Using the data matrix
    tsp.read_data(X)

    # Using the distance matrix
    tsp.read_mat(D)

    from tspy.solvers import TwoOpt_solver
    two_opt = TwoOpt_solver(initial_tour='NN', iter_num=10000)
    two_opt_tour = tsp.get_approx_solution(two_opt)

    #tsp.plot_solution('TwoOpt_solver')

    best_tour = tsp.get_best_solution()
    return best_tour
Exemplo n.º 3
0
    def solve(self):
        self.FloydWarshall()
        tsp = TSP()
        tsp.read_mat(np.array(self.dist, dtype=np.float64))
        two_opt = TwoOpt_solver(initial_tour='NN', iter_num=1000000)
        tsp.get_approx_solution(two_opt)
        path = tsp.get_best_solution()
        path = path[1:]  # Trim the start vertex
        start_idx = path.index(self.start)

        # Make sure the path starts and ends at Soda
        path = path[start_idx:] + path[:start_idx] + [self.start]

        changed = True
        # Not the most efficient, but oh well
        while changed:
            changed = False
            for i in range(len(path) - 1):
                u, v = path[i], path[i + 1]
                if self.adj[u][v] == Solver.INF:
                    # This isn't an edge in the graph, so splice in the shortest path
                    path[i:i + 2] = self.path[u][v]
                    changed = True
                    break

        # check all cycles along path to see if compression is better
        path = self.compressCycles(path)
        # try to remove dropoff locations
        path = self.removeDropoffLocations(path)
        # try to compress dropoff pairs
        path = self.compressDropoffPairs(path)

        self.finalPath = path

        # calculate final energy
        _, totalDist = self.calcDropoffsAndDist(path)

        return totalDist
Exemplo n.º 4
0
from tspy import TSP
import matplotlib.pyplot as plt
from tspy.solvers import TwoOpt_solver
from tspy.lower_bounds import Held_Karp
from tspy.lower_bounds import Connected_LP_bound
import numpy as np

a = TSP()
N = 100
a.read_data(np.random.rand(N, 2))
sol = TwoOpt_solver('NN')
a.get_approx_solution(sol)
plt.figure(figsize=(5, 5))
a.plot_solution('TwoOpt_solver')

a.get_lower_bound(Connected_LP_bound())
a.get_lower_bound(
    Held_Karp(n_iter=1000, batch_size=50, alp_factor=1, start_alp=0.001))
Exemplo n.º 5
0
from tspy import TSP
from tspy.lower_bounds import Simple_LP_bound
from tspy.lower_bounds import Connected_LP_bound
from tspy.lower_bounds import MinCut_LP_bound
from tspy.solvers import TwoOpt_solver
from tspy.solvers import NN_solver
import numpy as np

a = TSP()
N = 20
print(N)
a.read_data(np.random.rand(N, 2))
a.get_approx_solution(TwoOpt_solver('NN'))
a.get_approx_solution(NN_solver())

bounds = [Simple_LP_bound(), Connected_LP_bound(), MinCut_LP_bound()]

for b in bounds:
    a.get_lower_bound(b)

print(a.lower_bounds)

a.get_best_solution()
a.get_best_lower_bound()
Exemplo n.º 6
0
graph['fake'][start_node] = 1
for node in graph.keys():
    if node in ['fake', start_node]:
        continue
    graph[node]['fake'] = 1

# Create distance matrix:
M = np.ndarray(shape=(N, N), dtype=float)

for i, adr in enumerate(addresses):
    for j, adr2 in enumerate(addresses):
        if i == j:
            M[i, j] = np.inf
        else:
            M[i, j] = graph[adr][adr2]

tsp = TSP()
tsp.read_mat(M)

print("Solving using 2-opt heuristic for TSP:")
two_opt = TwoOpt_solver(initial_tour='NN', iter_num=100)
two_opt_tour = tsp.get_approx_solution(two_opt)

for idx in range(len(two_opt_tour) - 1):
    a = addresses[two_opt_tour[idx]]
    b = addresses[two_opt_tour[idx + 1]]
    print(f'From: {a}')
    print(f'To..: {b}')
    print('Time: {} min'.format(graph[a][b]))
    print('')
Exemplo n.º 7
0
from tspy import TSP
from tspy.solvers import NN_solver
from tspy.solvers import TwoOpt_solver
import numpy as np

a = TSP()
N = 150
a.read_data(np.random.rand(N, 2))

sol = NN_solver()
a.get_approx_solution(sol)

a.plot_solution('NN_solver')

sol = TwoOpt_solver(list(a.tours.values())[0], 500)
a.get_approx_solution(sol)
a.plot_solution('TwoOpt_solver')