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

Add GridDeviceMetadata. #4839

Merged
merged 5 commits into from
Jan 14, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions cirq-core/cirq/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
ConstantQubitNoiseModel,
Device,
DeviceMetadata,
GridDeviceMetadata,
GridQid,
GridQubit,
LineQid,
Expand Down
4 changes: 4 additions & 0 deletions cirq-core/cirq/devices/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
GridQubit,
)

from cirq.devices.griddevice_metadata import (
GridDeviceMetadata,
)

from cirq.devices.line_qubit import (
LineQubit,
LineQid,
Expand Down
10 changes: 9 additions & 1 deletion cirq-core/cirq/devices/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,15 @@
# limitations under the License.

import abc
from typing import TYPE_CHECKING, Optional, AbstractSet, cast, FrozenSet, Iterator, Iterable
from typing import (
TYPE_CHECKING,
Optional,
AbstractSet,
cast,
FrozenSet,
Iterator,
Iterable,
)

import networkx as nx
from cirq import value
Expand Down
137 changes: 137 additions & 0 deletions cirq-core/cirq/devices/griddevice_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# 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.
"""Metadata subtype for 2D Homogenous devices."""

from typing import (
TYPE_CHECKING,
Optional,
FrozenSet,
Iterable,
Tuple,
Dict,
)

import networkx as nx
from cirq import value
from cirq.devices import device

if TYPE_CHECKING:
import cirq


@value.value_equality
class GridDeviceMetadata(device.DeviceMetadata):
"""Hardware metadata for homogenous 2d symmetric grid devices."""

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

Create a GridDevice which has a well defined set of couplable
qubit pairs that have the same two qubit gates available in
both coupling directions.

Args:
qubit_pairs: Iterable of pairs of `cirq.Qid`s representing
bi-directional couplings.
supported_gates: `cirq.Gateset` indicating gates supported
everywhere on the device.
gate_durations: Optional dictionary of `cirq.Gateset`
instances mapping to `cirq.Duration` instances for
gate timing metadata information. If provided,
must match all entries in supported_gates.

Raises:
ValueError: if the union of gateset keys in gate_durations,
do not represent an identical gateset to supported_gates.
"""
qubit_pairs = list(qubit_pairs)
flat_pairs = [q for pair in qubit_pairs for q in pair]
# Keep lexigraphically smaller tuples for undirected edges.
sorted_pairs = sorted(qubit_pairs)
pair_set = set()
for a, b in sorted_pairs:
if (b, a) not in pair_set:
pair_set.add((a, b))

connectivity = nx.Graph()
connectivity.add_edges_from(sorted(pair_set), directed=False)
super().__init__(flat_pairs, connectivity)
self._qubit_pairs = frozenset(pair_set)
self._supported_gates = supported_gates

if gate_durations is not None:
working_gatefamilies = frozenset(
g for gset in gate_durations.keys() for g in gset.gates
)
if working_gatefamilies != supported_gates.gates:
missing_items = working_gatefamilies.difference(supported_gates.gates)
raise ValueError(
"Supplied gate_durations contains gates not present"
f" in supported_gates. {missing_items} in supported_gates"
" is False."
)

self._gate_durations = gate_durations

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

@property
def gateset(self) -> 'cirq.Gateset':
"""Returns the `cirq.Gateset` of supported gates on this device."""
return self._supported_gates

@property
def gate_durations(self) -> Optional[Dict['cirq.Gateset', 'cirq.Duration']]:
"""Get a dictionary mapping from gateset to duration for gates."""
return self._gate_durations

def _value_equality_values_(self):
duration_equality = ''
if self._gate_durations is not None:
duration_equality = sorted(self._gate_durations.items(), key=lambda x: repr(x[0]))

return (
tuple(sorted(self._qubit_pairs)),
self._supported_gates,
tuple(duration_equality),
)

def __repr__(self) -> str:
return (
f'cirq.GridDeviceMetadata({repr(self._qubit_pairs)},'
f' {repr(self._supported_gates)}, {repr(self._gate_durations)})'
)

def _json_dict_(self):
duration_payload = None
if self._gate_durations is not None:
duration_payload = sorted(self._gate_durations.items(), key=lambda x: repr(x[0]))

return {
'qubit_pairs': sorted(list(self._qubit_pairs)),
'supported_gates': self._supported_gates,
'gate_durations': duration_payload,
}

@classmethod
def _from_json_dict_(cls, qubit_pairs, supported_gates, gate_durations, **kwargs):
return cls(qubit_pairs, supported_gates, dict(gate_durations))
114 changes: 114 additions & 0 deletions cirq-core/cirq/devices/griddevice_metadata_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# 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.
"""Tests for GridDevicemetadata."""

import pytest
import cirq
import networkx as nx


def test_griddevice_metadata():
qubits = cirq.GridQubit.rect(2, 3)
qubit_pairs = [(a, b) for a in qubits for b in qubits if a != b and a.is_adjacent(b)]

gateset = cirq.Gateset(cirq.XPowGate, cirq.YPowGate, cirq.ZPowGate, cirq.CZ)
metadata = cirq.GridDeviceMetadata(qubit_pairs, gateset)

expected_pairings = frozenset(
{
(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)),
(cirq.GridQubit(0, 1), cirq.GridQubit(0, 2)),
(cirq.GridQubit(0, 1), cirq.GridQubit(1, 1)),
(cirq.GridQubit(0, 2), cirq.GridQubit(1, 2)),
(cirq.GridQubit(1, 0), cirq.GridQubit(1, 1)),
(cirq.GridQubit(1, 1), cirq.GridQubit(1, 2)),
(cirq.GridQubit(0, 0), cirq.GridQubit(1, 0)),
}
)
assert metadata.qubit_set == frozenset(qubits)
assert metadata.qubit_pairs == expected_pairings
assert metadata.gateset == gateset
expected_graph = nx.Graph()
expected_graph.add_edges_from(sorted(list(expected_pairings)), directed=False)
assert metadata.nx_graph.edges() == expected_graph.edges()
assert metadata.nx_graph.nodes() == expected_graph.nodes()
assert metadata.gate_durations is None


def test_griddevice_metadata_bad_durations():
qubits = tuple(cirq.GridQubit.rect(1, 2))

gateset = cirq.Gateset(cirq.XPowGate, cirq.YPowGate)
invalid_duration = {
cirq.Gateset(cirq.XPowGate): cirq.Duration(nanos=1),
cirq.Gateset(cirq.ZPowGate): cirq.Duration(picos=1),
}
with pytest.raises(ValueError, match="ZPowGate"):
cirq.GridDeviceMetadata([qubits], gateset, gate_durations=invalid_duration)


def test_griddevice_json_load():
qubits = cirq.GridQubit.rect(2, 3)
qubit_pairs = [(a, b) for a in qubits for b in qubits if a != b and a.is_adjacent(b)]
gateset = cirq.Gateset(cirq.XPowGate, cirq.YPowGate, cirq.ZPowGate)
duration = {
cirq.Gateset(cirq.XPowGate): cirq.Duration(nanos=1),
cirq.Gateset(cirq.YPowGate): cirq.Duration(picos=2),
cirq.Gateset(cirq.ZPowGate): cirq.Duration(picos=3),
}
metadata = cirq.GridDeviceMetadata(qubit_pairs, gateset, gate_durations=duration)
rep_str = cirq.to_json(metadata)
assert metadata == cirq.read_json(json_text=rep_str)


def test_griddevice_metadata_equality():
qubits = cirq.GridQubit.rect(2, 3)
qubit_pairs = [(a, b) for a in qubits for b in qubits if a != b and a.is_adjacent(b)]
gateset = cirq.Gateset(cirq.XPowGate, cirq.YPowGate, cirq.ZPowGate)
duration = {
cirq.Gateset(cirq.XPowGate): cirq.Duration(nanos=1),
cirq.Gateset(cirq.YPowGate): cirq.Duration(picos=3),
cirq.Gateset(cirq.ZPowGate): cirq.Duration(picos=2),
}
duration2 = {
cirq.Gateset(cirq.XPowGate): cirq.Duration(nanos=10),
cirq.Gateset(cirq.YPowGate): cirq.Duration(picos=13),
cirq.Gateset(cirq.ZPowGate): cirq.Duration(picos=12),
}
metadata = cirq.GridDeviceMetadata(qubit_pairs, gateset, gate_durations=duration)
metadata2 = cirq.GridDeviceMetadata(qubit_pairs[:2], gateset, gate_durations=duration)
metadata3 = cirq.GridDeviceMetadata(qubit_pairs, gateset, gate_durations=None)
metadata4 = cirq.GridDeviceMetadata(qubit_pairs, gateset, gate_durations=duration2)
metadata5 = cirq.GridDeviceMetadata(reversed(qubit_pairs), gateset, gate_durations=duration)

eq = cirq.testing.EqualsTester()
eq.add_equality_group(metadata)
eq.add_equality_group(metadata2)
eq.add_equality_group(metadata3)
eq.add_equality_group(metadata4)

assert metadata == metadata5


def test_repr():
qubits = cirq.GridQubit.rect(2, 3)
qubit_pairs = [(a, b) for a in qubits for b in qubits if a != b and a.is_adjacent(b)]
gateset = cirq.Gateset(cirq.XPowGate, cirq.YPowGate, cirq.ZPowGate)
duration = {
cirq.Gateset(cirq.XPowGate): cirq.Duration(nanos=1),
cirq.Gateset(cirq.YPowGate): cirq.Duration(picos=3),
cirq.Gateset(cirq.ZPowGate): cirq.Duration(picos=2),
}
metadata = cirq.GridDeviceMetadata(qubit_pairs, gateset, gate_durations=duration)
cirq.testing.assert_equivalent_repr(metadata)
1 change: 1 addition & 0 deletions cirq-core/cirq/json_resolver_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ def _parallel_gate_op(gate, qubits):
'GeneralizedAmplitudeDampingChannel': cirq.GeneralizedAmplitudeDampingChannel,
'GlobalPhaseGate': cirq.GlobalPhaseGate,
'GlobalPhaseOperation': cirq.GlobalPhaseOperation,
'GridDeviceMetadata': cirq.GridDeviceMetadata,
'GridInteractionLayer': GridInteractionLayer,
'GridParallelXEBMetadata': GridParallelXEBMetadata,
'GridQid': cirq.GridQid,
Expand Down
Loading