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

Change GridDeviceMetadata qubit type to GridQubit #5633

Merged
merged 6 commits into from
Jun 30, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
23 changes: 16 additions & 7 deletions cirq-core/cirq/devices/grid_device_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.
"""Metadata subtype for 2D Homogenous devices."""

from typing import TYPE_CHECKING, Optional, FrozenSet, Iterable, Tuple, Dict
from typing import TYPE_CHECKING, cast, Optional, FrozenSet, Iterable, Tuple, Dict

import networkx as nx
from cirq import value
Expand All @@ -29,21 +29,21 @@ class GridDeviceMetadata(device.DeviceMetadata):

def __init__(
self,
qubit_pairs: Iterable[Tuple['cirq.Qid', 'cirq.Qid']],
qubit_pairs: Iterable[Tuple['cirq.GridQubit', 'cirq.GridQubit']],
gateset: 'cirq.Gateset',
gate_durations: Optional[Dict['cirq.GateFamily', 'cirq.Duration']] = None,
all_qubits: Optional[Iterable['cirq.Qid']] = None,
all_qubits: Optional[Iterable['cirq.GridQubit']] = None,
compilation_target_gatesets: Iterable['cirq.CompilationTargetGateset'] = (),
):
"""Create a GridDeviceMetadata object.

Create a GridDevice which has a well defined set of couplable
Create a grid device which has a well defined set of couplable
qubit pairs that have the same two qubit gates available in
both coupling directions. Gate times (if provided) are expected
to be uniform across all qubits on the device.

Args:
qubit_pairs: Iterable of pairs of `cirq.Qid`s representing
qubit_pairs: Iterable of pairs of `cirq.GridQubit`s representing
bi-directional couplings.
gateset: `cirq.Gateset` indicating gates supported
everywhere on the device.
Expand Down Expand Up @@ -114,7 +114,16 @@ def __init__(
self._gate_durations = gate_durations

@property
def qubit_pairs(self) -> FrozenSet[FrozenSet['cirq.Qid']]:
def qubit_set(self) -> FrozenSet['cirq.GridQubit']:
"""Returns the set of grid qubits on the device.

Returns:
Frozenset of qubits on device.
"""
return cast(FrozenSet['cirq.GridQubit'], super().qubit_set)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wait, why do we need a cast here? Is it because you want to call super() instead of returning frozenset(self.qubits)?

Copy link
Collaborator Author

@verult verult Jun 29, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. self.qubits doesn't exist, and I wasn't sure about adding a self._qubits attribute just for this when it's already accessible from the superclass but just with a more general type.

edit: I tried it without the cast and actually mypy didn't complain locally. Will push it and see if it passes presubmits.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope that didn't work, reverting back


@property
def qubit_pairs(self) -> FrozenSet[FrozenSet['cirq.GridQubit']]:
"""Returns the set of all couple-able qubits on the device.

Each element in the outer frozenset is a 2-element frozenset representing a bidirectional
Expand All @@ -123,7 +132,7 @@ def qubit_pairs(self) -> FrozenSet[FrozenSet['cirq.Qid']]:
return self._qubit_pairs

@property
def isolated_qubits(self) -> FrozenSet['cirq.Qid']:
def isolated_qubits(self) -> FrozenSet['cirq.GridQubit']:
"""Returns the set of all isolated qubits on the device (if appliable)."""
return self._isolated_qubits

Expand Down
23 changes: 15 additions & 8 deletions cirq-google/cirq_google/devices/serializable_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,22 @@ def __init__(
self.qubits = qubits
self.gate_definitions = gate_definitions
has_subcircuit_support: bool = cirq.FrozenCircuit in gate_definitions

self._metadata = cirq.GridDeviceMetadata(
qubit_pairs=[
(pair[0], pair[1])
for gate_defs in gate_definitions.values()
for gate_def in gate_defs
if gate_def.number_of_qubits == 2
for pair in gate_def.target_set
if len(pair) == 2 and pair[0] < pair[1]
],
qubit_pairs=cast(
List[Tuple[cirq.GridQubit, cirq.GridQubit]],
[
(pair[0], pair[1])
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

put the cast here so you're casting less things? Like it still can infer the List[Tuple[... part; you need to cast the qubits themselves. Although with the isinstance checks I'm sad that that's necessary, see below.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried that at first, but mypy still complained (don't remember the exact error message, though)

for gate_defs in gate_definitions.values()
for gate_def in gate_defs
if gate_def.number_of_qubits == 2
for pair in gate_def.target_set
if len(pair) == 2
and pair[0] < pair[1]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this was already here, but does this mean if you order your qubits "backwards" in target_set the metadata will report that there are no pairs?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah good catch. This was added when GridDeviceMetadata required the pair to be ordered but missed this call site when it was changed to be order-agnostic. Will fix separately.

and isinstance(pair[0], cirq.GridQubit)
and isinstance(pair[1], cirq.GridQubit)
Comment on lines +116 to +117
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

doesn't this obviate the need for the cast? Usually mypy can use if isinstance(...) checks to infer variable types

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was hoping for that too, but unfortunately mypy complained (that the type is List[Tuple[Qid, Qid]])

],
),
gateset=cirq.Gateset(
*(g for g in gate_definitions.keys() if issubclass(g, cirq.Gate)),
cirq.GlobalPhaseGate,
Expand Down
4 changes: 2 additions & 2 deletions cirq-google/cirq_google/line/placement/anneal.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import cast, Callable, List, Optional, Tuple, Set, Any, TYPE_CHECKING
from typing import Callable, List, Optional, Tuple, Set, Any, TYPE_CHECKING

import numpy as np

Expand All @@ -37,7 +37,7 @@ def __init__(self, device: 'cirq_google.GridDevice', seed=None) -> None:
device: Chip description.
seed: Optional seed value for random number generator.
"""
self._c = cast(Set[cirq.GridQubit], device.metadata.qubit_set)
self._c = device.metadata.qubit_set
self._c_adj = chip_as_adjacency_list(device)
self._rand = np.random.RandomState(seed)

Expand Down
4 changes: 2 additions & 2 deletions cirq-google/cirq_google/line/placement/chip.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import cast, Dict, List, Set, Tuple, TYPE_CHECKING
from typing import Dict, List, Tuple, TYPE_CHECKING

import cirq

Expand Down Expand Up @@ -86,7 +86,7 @@ def chip_as_adjacency_list(
Map from nodes to list of qubits which represent all the neighbours of
given qubit.
"""
c_set = cast(Set[cirq.GridQubit], device.metadata.qubit_set)
c_set = device.metadata.qubit_set
c_adj: Dict[cirq.GridQubit, List[cirq.GridQubit]] = {}
for n in c_set:
c_adj[n] = []
Expand Down
4 changes: 2 additions & 2 deletions cirq-google/cirq_google/line/placement/greedy.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import cast, Dict, List, Optional, Set, TYPE_CHECKING
from typing import Dict, List, Optional, Set, TYPE_CHECKING

import abc
import collections
Expand Down Expand Up @@ -304,7 +304,7 @@ def place_line(self, device: 'cirq_google.GridDevice', length: int) -> GridQubit
if not device.metadata.qubit_set:
return GridQubitLineTuple()

start: GridQubit = cast(GridQubit, min(device.metadata.qubit_set))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

start: GridQubit = min(device.metadata.qubit_set)
sequences: List[LineSequence] = []
greedy_search: Dict[str, List[GreedySequenceSearch]] = {
'minimal_connectivity': [_PickFewestNeighbors(device, start)],
Expand Down