Skip to content

Commit

Permalink
added unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeremy Fan authored and Jason Necaise committed Dec 9, 2021
1 parent 2484c09 commit 87c18eb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion dwave_networkx/algorithms/tsp.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def traveling_salesperson_qubo(G, lagrange=None, weight='weight', missing_edge_p
missing_edge_weight=""

# default penalty format is sum
if missing_edge_penalty is "sum":
if missing_edge_penalty == "sum":
missing_edge_weight = sum(weight for _, _, weight in G.edges.data('weight', default=0))

# some input checking
Expand Down
35 changes: 35 additions & 0 deletions tests/test_tsp.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,41 @@ def test_k3(self):

self.assertEqual(ground_count, len(min_routes))

def test_k3_bidirectional(self):
G = nx.Graph()
G.add_weighted_edges_from([('a', 'b', 0.5),
('b', 'c', 1.0),
('a', 'c', 2.0),
('b', 'a', 0.5),
('c', 'b', 1.0),
('a', 'b', 0.5)])

Q = dnx.traveling_salesperson_qubo(G, lagrange=10)
bqm = dimod.BinaryQuadraticModel.from_qubo(Q)

# all routes are min weight
min_routes = list(itertools.permutations(G.nodes))

# get the min energy of the qubo
sampleset = dimod.ExactSolver().sample(bqm)
ground_energy = sampleset.first.energy

# all possible routes are equally good
for route in min_routes:
sample = {v: 0 for v in bqm.variables}
for idx, city in enumerate(route):
sample[(city, idx)] = 1
self.assertAlmostEqual(bqm.energy(sample), ground_energy)

# all min-energy solutions are valid routes
ground_count = 0
for sample, energy in sampleset.data(['sample', 'energy']):
if abs(energy - ground_energy) > .001:
break
ground_count += 1

self.assertEqual(ground_count, len(min_routes))

def test_k4_equal_weights(self):
# k5 with all equal weights so all paths are equally good
G = nx.Graph()
Expand Down

0 comments on commit 87c18eb

Please sign in to comment.