[Bug]: `MappingManager.shortest_path` raises unhandled `KeyError` on unreachable qubits and returns empty list for self-paths
Describe the issue
In cirq.transformers.routing.MappingManager.shortest_path:
-
Unhandled
KeyErroron unreachable qubits: Whenshortest_path(lq1, lq2)is called between two logical qubits where no path exists (such as on directed device coupling graphs or disconnected components),nx.reconstruct_pathfails with an unhandled, rawKeyError: np.int64(...)leaking from internal NetworkX data structures. This is currently noted as an unresolved# TODOincirq/transformers/routing/mapping_manager_test.py:# path from 2 to 0 does not exist # TODO: raise ValueError with informative message with pytest.raises(Exception): mm.shortest_path(q_int[2], q_int[0])Instead of leaking an internal
KeyError,MappingManager.shortest_pathshould raise a clean, descriptiveValueErrorinforming the caller that no path exists between the specified logical qubits. -
Self-path edge case returns empty list: When
lq1 == lq2,shortest_path(lq1, lq1)currently returns an empty list[]. Following standard graph theory and NetworkX conventions (nx.shortest_path(G, u, u) == [u]), the shortest path from a node to itself should consist of the node itself[lq1], rather than an empty sequence of length 0.
Explain how to reproduce the bug or problem
import cirq
import networkx as nx
# Directed topology: 0 -> 1 -> 2 (no path exists from 2 to 0)
g = nx.DiGraph([(0, 1), (1, 2)])
q = cirq.LineQubit.range(3)
mapping = {q[i]: i for i in range(3)}
mm = cirq.MappingManager(g, mapping)
# 1. Unhandled internal KeyError when no path exists
try:
mm.shortest_path(2, 0)
except Exception as e:
print(f"Raised: {type(e).__name__}: {e}")
# 2. Path to self returns empty list instead of [0]
print("Path from 0 to 0:", mm.shortest_path(0, 0))
Traceback for unreachable qubits
Traceback (most recent call last):
File "<string>", line 12, in <module>
mm.shortest_path(2, 0)
File "cirq/transformers/routing/mapping_manager.py", line 226, in shortest_path
nx.reconstruct_path(*self.logical_to_physical[[lq1, lq2]], predecessors)
File "networkx/algorithms/shortest_paths/dense.py", line 391, in reconstruct_path
prev = predecessors[source]
KeyError: np.int64(2)
Cirq version
1.7.0
I would like to submit a PR to fix this if you could assign this to me?
@SteveSonyJacob Thank you for the report and your interest in working on it!
@mhucka Could you please check the PR i have linked?