17
17
from typing import Dict , Sequence , TYPE_CHECKING
18
18
import networkx as nx
19
19
20
- from cirq import protocols , value , _compat
20
+ from cirq import protocols , value
21
21
22
22
if TYPE_CHECKING :
23
23
import cirq
@@ -43,6 +43,7 @@ def __init__(
43
43
device_graph: connectivity graph of qubits in the hardware device.
44
44
initial_mapping: the initial mapping of logical (keys) to physical qubits (values).
45
45
"""
46
+ # make sure edge insertion order is the same amongst equivalent graphs.
46
47
if nx .is_directed (device_graph ):
47
48
self .device_graph = nx .DiGraph ()
48
49
self .device_graph .add_nodes_from (sorted (list (device_graph .nodes (data = True ))))
@@ -57,6 +58,9 @@ def __init__(
57
58
self ._map = initial_mapping .copy ()
58
59
self ._inverse_map = {v : k for k , v in self ._map .items ()}
59
60
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
+ )
60
64
61
65
@property
62
66
def map (self ) -> Dict ['cirq.Qid' , 'cirq.Qid' ]:
@@ -83,7 +87,7 @@ def dist_on_device(self, lq1: 'cirq.Qid', lq2: 'cirq.Qid') -> int:
83
87
Returns:
84
88
The shortest path distance.
85
89
"""
86
- return len ( self ._physical_shortest_path ( self ._map [lq1 ], self ._map [lq2 ])) - 1
90
+ return self ._distances [ self ._map [lq1 ]][ self ._map [lq2 ]]
87
91
88
92
def can_execute (self , op : 'cirq.Operation' ) -> bool :
89
93
"""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'
140
144
Returns:
141
145
A sequence of logical qubits on the shortest path from lq1 to lq2.
142
146
"""
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
+ ]
149
151
150
152
def _value_equality_values_ (self ):
151
153
graph_equality = (
0 commit comments