From f39bb8a355029ce5ac368d6549747d00f6a366de Mon Sep 17 00:00:00 2001 From: Aria Date: Fri, 12 Aug 2022 03:35:28 +0530 Subject: [PATCH] Add nodes_to_linequbits method to LineTopology (#5821) Resolves #4710 Co-authored-by: Pavol Juhas --- cirq-core/cirq/devices/named_topologies.py | 12 ++++++++++-- cirq-core/cirq/devices/named_topologies_test.py | 5 +++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/cirq-core/cirq/devices/named_topologies.py b/cirq-core/cirq/devices/named_topologies.py index 43321767186..68384e1bc02 100644 --- a/cirq-core/cirq/devices/named_topologies.py +++ b/cirq-core/cirq/devices/named_topologies.py @@ -142,6 +142,14 @@ def draw(self, ax=None, tilted: bool = True, **kwargs) -> Dict[Any, Tuple[int, i g2 = nx.relabel_nodes(self.graph, {n: (n, 1) for n in self.graph.nodes}) return draw_gridlike(g2, ax=ax, tilted=tilted, **kwargs) + def nodes_to_linequbits(self, offset: int = 0) -> Dict[int, 'cirq.LineQubit']: + """Return a mapping from graph nodes to `cirq.LineQubit` + + Args: + offset: Offset integer positions of the resultant LineQubits by this amount. + """ + return dict(enumerate(LineQubit.range(offset, offset + self.n_nodes))) + def _json_dict_(self) -> Dict[str, Any]: return dataclass_json_dict(self) @@ -240,8 +248,8 @@ def nodes_to_gridqubits(self, offset=(0, 0)) -> Dict[Tuple[int, int], 'cirq.Grid """Return a mapping from graph nodes to `cirq.GridQubit` Args: - offset: Offest row and column indices of the resultant GridQubits by this amount. - The offest positions the top-left node in the `draw(tilted=False)` frame. + offset: Offset row and column indices of the resultant GridQubits by this amount. + The offset positions the top-left node in the `draw(tilted=False)` frame. """ return {(r, c): GridQubit(r, c) + offset for r, c in self.graph.nodes} diff --git a/cirq-core/cirq/devices/named_topologies_test.py b/cirq-core/cirq/devices/named_topologies_test.py index de6e370f5e5..7494cd255d0 100644 --- a/cirq-core/cirq/devices/named_topologies_test.py +++ b/cirq-core/cirq/devices/named_topologies_test.py @@ -85,6 +85,11 @@ def test_line_topology(): assert LineTopology(2).n_nodes == 2 assert LineTopology(2).graph.number_of_nodes() == 2 + mapping = topo.nodes_to_linequbits(offset=3) + assert sorted(mapping.keys()) == list(range(n)) + assert all(isinstance(q, cirq.LineQubit) for q in mapping.values()) + assert all(mapping[x] == cirq.LineQubit(x + 3) for x in mapping) + cirq.testing.assert_equivalent_repr(topo)