Skip to content

Commit 95d3bc2

Browse files
ammareltiganirht
authored andcommitted
changed mapping manager to use floyd warshall instead (quantumlib#5843)
1 parent ba2d9ab commit 95d3bc2

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

cirq-core/cirq/transformers/routing/mapping_manager.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from typing import Dict, Sequence, TYPE_CHECKING
1818
import networkx as nx
1919

20-
from cirq import protocols, value, _compat
20+
from cirq import protocols, value
2121

2222
if TYPE_CHECKING:
2323
import cirq
@@ -43,6 +43,7 @@ def __init__(
4343
device_graph: connectivity graph of qubits in the hardware device.
4444
initial_mapping: the initial mapping of logical (keys) to physical qubits (values).
4545
"""
46+
# make sure edge insertion order is the same amongst equivalent graphs.
4647
if nx.is_directed(device_graph):
4748
self.device_graph = nx.DiGraph()
4849
self.device_graph.add_nodes_from(sorted(list(device_graph.nodes(data=True))))
@@ -57,6 +58,9 @@ def __init__(
5758
self._map = initial_mapping.copy()
5859
self._inverse_map = {v: k for k, v in self._map.items()}
5960
self._induced_subgraph = nx.induced_subgraph(self.device_graph, self._map.values())
61+
self._predecessors, self._distances = nx.floyd_warshall_predecessor_and_distance(
62+
self._induced_subgraph
63+
)
6064

6165
@property
6266
def map(self) -> Dict['cirq.Qid', 'cirq.Qid']:
@@ -83,7 +87,7 @@ def dist_on_device(self, lq1: 'cirq.Qid', lq2: 'cirq.Qid') -> int:
8387
Returns:
8488
The shortest path distance.
8589
"""
86-
return len(self._physical_shortest_path(self._map[lq1], self._map[lq2])) - 1
90+
return self._distances[self._map[lq1]][self._map[lq2]]
8791

8892
def can_execute(self, op: 'cirq.Operation') -> bool:
8993
"""Finds whether the given operation acts on qubits that are adjacent on the device.
@@ -140,12 +144,10 @@ def shortest_path(self, lq1: 'cirq.Qid', lq2: 'cirq.Qid') -> Sequence['cirq.Qid'
140144
Returns:
141145
A sequence of logical qubits on the shortest path from lq1 to lq2.
142146
"""
143-
physical_shortest_path = self._physical_shortest_path(self._map[lq1], self._map[lq2])
144-
return [self._inverse_map[pq] for pq in physical_shortest_path]
145-
146-
@_compat.cached_method
147-
def _physical_shortest_path(self, pq1: 'cirq.Qid', pq2: 'cirq.Qid') -> Sequence['cirq.Qid']:
148-
return nx.shortest_path(self._induced_subgraph, pq1, pq2)
147+
return [
148+
self._inverse_map[pq]
149+
for pq in nx.reconstruct_path(self._map[lq1], self._map[lq2], self._predecessors)
150+
]
149151

150152
def _value_equality_values_(self):
151153
graph_equality = (

0 commit comments

Comments
 (0)