Exemple #1
0
    def test_dimod_vs_list(self):
        G = nx.complete_graph(4)
        for u, v in G.edges():
            G[u][v]['weight'] = 1

        route = dnx.traveling_salesperson(G, dimod.ExactSolver())
        route = dnx.traveling_salesperson(G, dimod.SimulatedAnnealingSampler())
Exemple #2
0
    def calculate(self, G, cost_matrix, starting_node):

        sapi_token = ''
        dwave_url = 'https://cloud.dwavesys.com/sapi'


        dnx.traveling_salesperson(G, dimod.ExactSolver(), start=0) # doctest: +SKIP


        #nx.draw_networkx(G, node_color=colors, node_size=400, alpha=.8, ax=default_axes, pos=pos)
        # Test with https://docs.ocean.dwavesys.com/en/latest/docs_dnx/reference/algorithms/tsp.html
        route = dnx.traveling_salesperson(G, dimod.ExactSolver(), start=starting_node)

        return route
Exemple #3
0
    def test_weighted_complete_graph(self):
        G = nx.Graph()
        G.add_weighted_edges_from({(0, 1, 1), (0, 2, 2), (0, 3, 3), (1, 2, 3),
                                   (1, 3, 4), (2, 3, 5)})
        route = dnx.traveling_salesperson(G, dimod.ExactSolver(), lagrange=10)

        self.assertEqual(len(route), len(G))
Exemple #4
0
    def test_weighted_complete_digraph(self):
        G = nx.DiGraph()
        G.add_weighted_edges_from([
            (0, 1, 2),
            (1, 0, 1),
            (0, 2, 2),
            (2, 0, 2),
            (0, 3, 1),
            (3, 0, 2),
            (1, 2, 2),
            (2, 1, 1),
            (1, 3, 2),
            (3, 1, 2),
            (2, 3, 2),
            (3, 2, 1),
        ])

        route = dnx.traveling_salesperson(G, dimod.ExactSolver(), start=1)

        self.assertEqual(len(route), len(G))
        self.assertListEqual(route, [1, 0, 3, 2])

        cost = path_weight(G, route)

        self.assertEqual(cost, 4)
Exemple #5
0
    def test_start(self):
        G = nx.Graph()
        G.add_weighted_edges_from(
            (u, v, .5) for u, v in itertools.combinations(range(3), 2))

        route = dnx.traveling_salesperson(G, dimod.ExactSolver(), start=2)

        self.assertEqual(route[0], 2)
Exemple #6
0
    def test_TSP_basic(self):
        """Runs the function on some small and simple graphs, just to make
        sure it works in basic functionality.
        """
        G = nx.complete_graph(4)
        for u, v in G.edges():
            G[u][v]['weight'] = 1
        route = dnx.traveling_salesperson(G, dimod.ExactSolver())
        self.assertTrue(dnx.is_hamiltonian_path(G, route))

        G = nx.complete_graph(4)
        for u, v in G.edges():
            G[u][v]['weight'] = u + v
        route = dnx.traveling_salesperson(G,
                                          dimod.ExactSolver(),
                                          lagrange=10.0)
        self.assertTrue(dnx.is_hamiltonian_path(G, route))
Exemple #7
0
    def calculate(self, G, cost_matrix, starting_node):

        #if(len(G.nodes) > 9):
        #    print("Dwave 2000Q systems can only embed up to 9 nodes on the lattice with current algorithm")
        #    return []

        # Different tests to make it happen!
        #Q = dnx.algorithms.traveling_salesman_qubo(G)
        #bqm = dimod.BinaryQuadraticModel.from_networkx_graph(G, 'BINARY', edge_attribute_name='weight')
        #response = EmbeddingComposite(DWaveSampler(solver='DW_2000Q_6')).sample(bqm, chain_strength=300, num_reads=1000)
        #print(response)

        #sampler = AutoEmbeddingComposite(DWaveSampler(solver='DW_2000Q_6'))
        sampler = AutoEmbeddingComposite(
            DWaveSampler(solver='Advantage_system1.1'))
        #sampleset = dimod.SimulatedAnnealingSampler().sample_qubo(Q)
        result = dnx.traveling_salesperson(G,
                                           sampler,
                                           start=starting_node,
                                           lagrange=90.0,
                                           weight='weight')

        return result
Exemple #8
0
 def hybrid_tsp(self):
     sampler = LeapHybridSampler()
     return dnx.traveling_salesperson(self.G, sampler, start=self.start)
Exemple #9
0
from collections import defaultdict
import networkx as nx

# ------- Set up our graph -------
# Create empty graph
G = nx.complete_graph(4)
G.add_weighted_edges_from({(0, 1, .1), (0, 2, .5), (0, 3, .1), (1, 2, .1),
                           (1, 3, .5), (2, 3, .1)})

from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite
import dimod
import dwave_networkx as dnx

ans = dnx.traveling_salesperson(G, sampler=dimod.ExactSolver(), start=0)
print("ExactSolver [0 1 2 3] ")
print(ans)  #Calculated by Electronic computer

# ------- Set up our QUBO dictionary -------
Q = defaultdict(int)  # Initialize our Q matrix
# Update Q matrix for every edge in the graph
for i, j in G.edges:
    Q[(i, i)] += -1
    Q[(j, j)] += -1
    Q[(i, j)] += 2

# ------- Run our QUBO on the QPU -------
# Set up QPU parameters
chainstrength = 1.0
numruns = 100
Q = dnx.traveling_salesperson_qubo(G)
params = pd.read_csv(Data_name, header=None)
params.columns = ['x', 'y']
nodes = int(input('Enter number of nodes to use: '))
cities = params[:nodes][:]

cost_matrix = get_distance_matrix(cities)

routes = nx.Graph()
for i in range(len(cities)):
    for j in range(i + 1, len(cities)):
        routes.add_weighted_edges_from({(i, j, cost_matrix[i][j]),
                                        (j, i, cost_matrix[j][i])})

#choose sampler
sampler = LeapHybridSampler()

start_time = time.time()

#Test routes on quantum chip
bqm = dnx.traveling_salesperson(routes, sampler)

#Verify path is valid (all locations visited once) and result is in the list of routes
if (set(bqm) == set(routes)):
    print('Solution took ', round(time.time() - start_time, 3),
          's for cities = ', str(len(cities)))
    print('Best route: ' + str(bqm))
    print("Cost:", calculate_cost(cost_matrix, bqm))
else:
    print('Valid path not found')