Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created routing utilities subdirectory in cirq-core/transformers and added MappingManager module #5823

Merged
merged 14 commits into from
Aug 15, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions cirq-core/cirq/transformers/routing/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Copyright 2022 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Routing utilities in Cirq."""

from cirq.transformers.routing.mapping_manager import MappingManager
113 changes: 113 additions & 0 deletions cirq-core/cirq/transformers/routing/mapping_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Copyright 2022 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
from typing import Dict, TYPE_CHECKING
import networkx as nx

from cirq import ops, protocols

if TYPE_CHECKING:
import cirq


class MappingManager:
"""Class that keeps track of the mapping of logical to physical qubits and provides
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
convenience methods for distance queries on the physical qubits.

Qubit variables with the characer 'p' preppended to them are physical and qubits with the
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
character 'l' preppended to them are logical qubits.
"""

def __init__(self, device_graph: nx.Graph, initial_mapping: Dict[ops.Qid, ops.Qid]) -> None:
"""Initializes MappingManager.

Args:
device_graph: connectivity graph of qubits in the hardware device.
circuit_graph: connectivity graph of the qubits in the input circuit.
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
initial_mapping: the initial mapping of logical (keys) to physical qubits (values).
"""
self.device_graph = device_graph
self._map = initial_mapping.copy()
self._inverse_map = {v: k for k, v in self._map.items()}
self._induced_subgraph = nx.induced_subgraph(self.device_graph, self._map.values())
self._shortest_paths_matrix = dict(nx.all_pairs_shortest_path(self._induced_subgraph))
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved

@property
def map(self) -> Dict[ops.Qid, ops.Qid]:
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
"""The mapping of logical qubits (keys) to physical qubits (values)."""
return self._map

@property
def inverse_map(self) -> Dict[ops.Qid, ops.Qid]:
"""The mapping of physical qubits (keys) to logical qubits (values)."""
return self._inverse_map

@property
def induced_subgraph(self) -> nx.Graph:
"""The device_graph induced on the physical qubits that are mapped to."""
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
return self._induced_subgraph

def dist_on_device(self, lq1: ops.Qid, lq2: ops.Qid) -> int:
"""Finds shortest path distance path between the corresponding physical qubits for logical
qubits q1 and q2 on the device.
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved

Args:
lq1: the first logical qubit.
lq2: the second logical qubit.

Returns:
The shortest path distance.
"""
return len(self._shortest_paths_matrix[self._map[lq1]][self._map[lq2]]) - 1

def can_execute(self, op: ops.Operation) -> bool:
"""Finds whether the given operation can be executed on the device.
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved

Args:
op: an operation on logical qubits.

Returns:
Whether the given operation is executable on the device.
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
"""
return protocols.num_qubits(op) < 2 or self.dist_on_device(*op.qubits) == 1

def apply_swap(self, lq1: ops.Qid, lq2: ops.Qid) -> None:
"""Swaps two logical qubits in the map and in the inverse map.
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved

Args:
lq1: the first logical qubit.
lq2: the second logical qubit.
"""
self._map[lq1], self._map[lq2] = self._map[lq2], self._map[lq1]

pq1 = self._map[lq1]
pq2 = self._map[lq2]
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
self._inverse_map[pq1], self._inverse_map[pq2] = (
self._inverse_map[pq2],
self._inverse_map[pq1],
)

def mapped_op(self, op: ops.Operation) -> ops.Operation:
"""Transforms the given operation with the qubits in self._map.

Args:
op: an operation on logical qubits.

Returns:
The same operation on corresponding physical qubits."""
return op.transform_qubits(self._map)

def shortest_path(self, lq1: ops.Qid, lq2: ops.Qid):
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
"""Find that shortest path between two logical qubits on the device given their mapping."""
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
return self._shortest_paths_matrix[self._map[lq1]][self._map[lq2]]
100 changes: 100 additions & 0 deletions cirq-core/cirq/transformers/routing/mapping_manager_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Copyright 2022 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import networkx as nx
from networkx.utils.misc import graphs_equal

import cirq


def test_mapping_manager():
ammareltigani marked this conversation as resolved.
Show resolved Hide resolved
device_graph = nx.Graph(
[
(cirq.NamedQubit("a"), cirq.NamedQubit("b")),
(cirq.NamedQubit("b"), cirq.NamedQubit("c")),
(cirq.NamedQubit("c"), cirq.NamedQubit("d")),
(cirq.NamedQubit("a"), cirq.NamedQubit("e")),
(cirq.NamedQubit("e"), cirq.NamedQubit("d")),
]
)
q = cirq.LineQubit.range(5)
initial_mapping = {
q[1]: cirq.NamedQubit("a"),
q[3]: cirq.NamedQubit("b"),
q[2]: cirq.NamedQubit("c"),
q[4]: cirq.NamedQubit("d"),
}
mm = cirq.transformers.routing.MappingManager(device_graph, initial_mapping)

# test correct induced subgraph
expected_induced_subgraph = nx.Graph(
[
(cirq.NamedQubit("a"), cirq.NamedQubit("b")),
(cirq.NamedQubit("b"), cirq.NamedQubit("c")),
(cirq.NamedQubit("c"), cirq.NamedQubit("d")),
]
)
assert graphs_equal(mm.induced_subgraph, expected_induced_subgraph)

# test mapped_op
mapped_one_three = mm.mapped_op(cirq.CNOT(q[1], q[3]))
assert mapped_one_three.qubits == (cirq.NamedQubit("a"), cirq.NamedQubit("b"))

# adjacent qubits have distance 1 and are thus executable
assert mm.dist_on_device(q[1], q[3]) == 1
assert mm.can_execute(cirq.CNOT(q[1], q[3]))

# non-adjacent qubits with distance > 1 are not executable
assert mm.dist_on_device(q[1], q[2]) == 2
assert mm.can_execute(cirq.CNOT(q[1], q[2])) is False

# 'dist_on_device' does not use cirq.NamedQubit("e") to find shorter shortest path
assert mm.dist_on_device(q[1], q[4]) == 3

# after swapping q[2] and q[3], qubits adjacent to q[2] are now adjacent to q[3] and vice-versa
mm.apply_swap(q[3], q[2])
assert mm.dist_on_device(q[1], q[2]) == 1
assert mm.can_execute(cirq.CNOT(q[1], q[2]))
assert mm.dist_on_device(q[1], q[3]) == 2
assert mm.can_execute(cirq.CNOT(q[1], q[3])) is False
# the swapped qubits are still executable
assert mm.can_execute(cirq.CNOT(q[2], q[3]))
# distance between other qubits doesn't change
assert mm.dist_on_device(q[1], q[4]) == 3
# test applying swaps to inverse map is correct
assert mm.inverse_map == {v: k for k, v in mm.map.items()}
# test mapped_op after switching qubits
mapped_one_two = mm.mapped_op(cirq.CNOT(q[1], q[2]))
assert mapped_one_two.qubits == (cirq.NamedQubit("a"), cirq.NamedQubit("b"))

# apply same swap and test shortest path for a couple pairs
mm.apply_swap(q[3], q[2])
assert mm.shortest_path(q[1], q[2]) == [
cirq.NamedQubit("a"),
cirq.NamedQubit("b"),
cirq.NamedQubit("c"),
]
assert mm.shortest_path(q[2], q[3]) == [cirq.NamedQubit("c"), cirq.NamedQubit("b")]
assert mm.shortest_path(q[1], q[3]) == [cirq.NamedQubit("a"), cirq.NamedQubit("b")]

shortest_one_to_four = [
cirq.NamedQubit("a"),
cirq.NamedQubit("b"),
cirq.NamedQubit("c"),
cirq.NamedQubit("d"),
]
assert mm.shortest_path(q[1], q[4]) == shortest_one_to_four

# shortest path on symmetric qubit reverses the list
assert mm.shortest_path(q[4], q[1]) == shortest_one_to_four[::-1]