Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
eliottrosenberg authored Sep 18, 2023
2 parents 9f005f7 + b630298 commit b4ce5db
Show file tree
Hide file tree
Showing 23 changed files with 622 additions and 314 deletions.
4 changes: 2 additions & 2 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

cirq-google/**/*.* @wcourtney @quantumlib/cirq-maintainers @vtomole @cduck @verult

cirq-ionq/**/*.* @dabacon @ColemanCollins @nakardo @gmauricio @Cynocracy @quantumlib/cirq-maintainers @vtomole @cduck
cirq-ionq/**/*.* @dabacon @ColemanCollins @nakardo @gmauricio @Cynocracy @quantumlib/cirq-maintainers @vtomole @cduck @splch

cirq-aqt/**/*.* @ma5x @pschindler @alfrisch @quantumlib/cirq-maintainers @vtomole @cduck

Expand All @@ -37,7 +37,7 @@ docs/**/*.* @aasfaw @rmlarose @quantumlib/cirq-maintainers @vtomole @cduck
docs/google/**/*.* @wcourtney @aasfaw @rmlarose @quantumlib/cirq-maintainers @vtomole @cduck @verult
docs/tutorials/google/**/*.* @wcourtney @aasfaw @rmlarose @quantumlib/cirq-maintainers @vtomole @cduck @verult

docs/hardware/ionq/**/*.* @dabacon @ColemanCollins @nakardo @gmauricio @aasfaw @rmlarose @Cynocracy @quantumlib/cirq-maintainers @vtomole @cduck
docs/hardware/ionq/**/*.* @dabacon @ColemanCollins @nakardo @gmauricio @aasfaw @rmlarose @Cynocracy @quantumlib/cirq-maintainers @vtomole @cduck @splch

docs/hardware/aqt/**/*.* @ma5x @pschindler @alfrisch @aasfaw @rmlarose @quantumlib/cirq-maintainers @vtomole @cduck

Expand Down
4 changes: 3 additions & 1 deletion cirq-core/cirq/contrib/svg/svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@
from typing import TYPE_CHECKING, List, Tuple, cast, Dict

import matplotlib.textpath
import matplotlib.font_manager


if TYPE_CHECKING:
import cirq

QBLUE = '#1967d2'
FONT = "Arial"
FONT = matplotlib.font_manager.FontProperties(family="Arial")
EMPTY_MOMENT_COLWIDTH = float(21) # assumed default column width


Expand Down
22 changes: 21 additions & 1 deletion cirq-core/cirq/devices/insertion_noise_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

import dataclasses
from typing import TYPE_CHECKING, Dict, List, Optional, Sequence
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence

from cirq import devices
from cirq.devices import noise_utils
Expand Down Expand Up @@ -74,3 +74,23 @@ def noisy_moment(
if self.prepend:
return [*noise_steps.moments, moment]
return [moment, *noise_steps.moments]

def __repr__(self) -> str:
return (
f'cirq.devices.InsertionNoiseModel(ops_added={self.ops_added},'
+ f' prepend={self.prepend},'
+ f' require_physical_tag={self.require_physical_tag})'
)

def _json_dict_(self) -> Dict[str, Any]:
return {
'ops_added': list(self.ops_added.items()),
'prepend': self.prepend,
'require_physical_tag': self.require_physical_tag,
}

@classmethod
def _from_json_dict_(cls, ops_added, prepend, require_physical_tag, **kwargs):
return cls(
ops_added=dict(ops_added), prepend=prepend, require_physical_tag=require_physical_tag
)
6 changes: 6 additions & 0 deletions cirq-core/cirq/devices/insertion_noise_model_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ def test_insertion_noise():
moment_3 = cirq.Moment(cirq.Z(q0), cirq.X(q1))
assert model.noisy_moment(moment_3, system_qubits=[q0, q1]) == [moment_3]

cirq.testing.assert_equivalent_repr(model)


def test_colliding_noise_qubits():
# Check that noise affecting other qubits doesn't cause issues.
Expand All @@ -61,6 +63,8 @@ def test_colliding_noise_qubits():
cirq.Moment(cirq.CNOT(q1, q2)),
]

cirq.testing.assert_equivalent_repr(model)


def test_prepend():
q0, q1 = cirq.LineQubit.range(2)
Expand Down Expand Up @@ -106,3 +110,5 @@ def test_supertype_matching():

moment_1 = cirq.Moment(cirq.Y(q0))
assert model.noisy_moment(moment_1, system_qubits=[q0]) == [moment_1, cirq.Moment(cirq.T(q0))]

cirq.testing.assert_equivalent_repr(model)
2 changes: 1 addition & 1 deletion cirq-core/cirq/devices/named_topologies.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def _node_and_coordinates(


def draw_gridlike(
graph: nx.Graph, ax: plt.Axes = None, tilted: bool = True, **kwargs
graph: nx.Graph, ax: Optional[plt.Axes] = None, tilted: bool = True, **kwargs
) -> Dict[Any, Tuple[int, int]]:
"""Draw a grid-like graph using Matplotlib.
Expand Down
11 changes: 6 additions & 5 deletions cirq-core/cirq/experiments/qubit_characterizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@
import dataclasses
import itertools

from typing import Any, Iterator, List, Optional, Sequence, Tuple, TYPE_CHECKING
from typing import Any, cast, Iterator, List, Optional, Sequence, Tuple, TYPE_CHECKING
import numpy as np

from matplotlib import pyplot as plt

# this is for older systems with matplotlib <3.2 otherwise 3d projections fail
from mpl_toolkits import mplot3d # pylint: disable=unused-import
from mpl_toolkits import mplot3d
from cirq import circuits, ops, protocols

if TYPE_CHECKING:
Expand Down Expand Up @@ -89,8 +89,9 @@ def plot(self, ax: Optional[plt.Axes] = None, **plot_kwargs: Any) -> plt.Axes:
"""
show_plot = not ax
if not ax:
fig, ax = plt.subplots(1, 1, figsize=(8, 8))
ax.set_ylim([0, 1])
fig, ax = plt.subplots(1, 1, figsize=(8, 8)) # pragma: no cover
ax = cast(plt.Axes, ax) # pragma: no cover
ax.set_ylim((0.0, 1.0)) # pragma: no cover
ax.plot(self._num_cfds_seq, self._gnd_state_probs, 'ro-', **plot_kwargs)
ax.set_xlabel(r"Number of Cliffords")
ax.set_ylabel('Ground State Probability')
Expand Down Expand Up @@ -541,7 +542,7 @@ def _find_inv_matrix(mat: np.ndarray, mat_sequence: np.ndarray) -> int:
def _matrix_bar_plot(
mat: np.ndarray,
z_label: str,
ax: plt.Axes,
ax: mplot3d.axes3d.Axes3D,
kets: Optional[Sequence[str]] = None,
title: Optional[str] = None,
ylim: Tuple[int, int] = (-1, 1),
Expand Down
2 changes: 2 additions & 0 deletions cirq-core/cirq/json_resolver_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ def _class_resolver_dictionary() -> Dict[str, ObjectFactory]:
import pandas as pd
import numpy as np
from cirq.devices.noise_model import _NoNoiseModel
from cirq.devices import InsertionNoiseModel
from cirq.experiments import GridInteractionLayer
from cirq.experiments.grid_parallel_two_qubit_xeb import GridParallelXEBMetadata

Expand Down Expand Up @@ -147,6 +148,7 @@ def _symmetricalqidpair(qids):
'ISwapPowGate': cirq.ISwapPowGate,
'IdentityGate': cirq.IdentityGate,
'InitObsSetting': cirq.work.InitObsSetting,
'InsertionNoiseModel': InsertionNoiseModel,
'KeyCondition': cirq.KeyCondition,
'KrausChannel': cirq.KrausChannel,
'LinearDict': cirq.LinearDict,
Expand Down
11 changes: 6 additions & 5 deletions cirq-core/cirq/linalg/decompositions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from typing import (
Any,
Callable,
cast,
Iterable,
List,
Optional,
Expand All @@ -33,7 +34,7 @@
import matplotlib.pyplot as plt

# this is for older systems with matplotlib <3.2 otherwise 3d projections fail
from mpl_toolkits import mplot3d # pylint: disable=unused-import
from mpl_toolkits import mplot3d
import numpy as np

from cirq import value, protocols
Expand Down Expand Up @@ -554,7 +555,7 @@ def scatter_plot_normalized_kak_interaction_coefficients(
interactions: Iterable[Union[np.ndarray, 'cirq.SupportsUnitary', 'KakDecomposition']],
*,
include_frame: bool = True,
ax: Optional[plt.Axes] = None,
ax: Optional[mplot3d.axes3d.Axes3D] = None,
**kwargs,
):
r"""Plots the interaction coefficients of many two-qubit operations.
Expand Down Expand Up @@ -633,13 +634,13 @@ def scatter_plot_normalized_kak_interaction_coefficients(
show_plot = not ax
if not ax:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax = cast(mplot3d.axes3d.Axes3D, fig.add_subplot(1, 1, 1, projection='3d'))

def coord_transform(
pts: Union[List[Tuple[int, int, int]], np.ndarray]
) -> Tuple[Iterable[float], Iterable[float], Iterable[float]]:
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
if len(pts) == 0:
return [], [], []
return np.array([]), np.array([]), np.array([])
xs, ys, zs = np.transpose(pts)
return xs, zs, ys

Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/fsim_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class FSimGate(gate_features.InterchangeableQubitsGate, raw_types.Gate):
$$
$$
c = e^{i \phi}
c = e^{-i \phi}
$$
Note the difference in sign conventions between FSimGate and the
Expand Down
91 changes: 91 additions & 0 deletions cirq-core/cirq/protocols/json_test_data/InsertionNoiseModel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
[
{
"cirq_type": "InsertionNoiseModel",
"ops_added": [
[
{
"cirq_type": "OpIdentifier",
"gate_type": "XPowGate",
"qubits": [
{
"cirq_type": "LineQubit",
"x": 0
}
]
},
{
"cirq_type": "GateOperation",
"gate": {
"cirq_type": "BitFlipChannel",
"p": 0.2
},
"qubits": [
{
"cirq_type": "LineQubit",
"x": 0
}
]
}
]
],
"prepend": false,
"require_physical_tag": false
},
{
"cirq_type": "InsertionNoiseModel",
"ops_added": [
[
{
"cirq_type": "OpIdentifier",
"gate_type": "XPowGate",
"qubits": [
{
"cirq_type": "LineQubit",
"x": 0
}
]
},
{
"cirq_type": "GateOperation",
"gate": {
"cirq_type": "BitFlipChannel",
"p": 0.2
},
"qubits": [
{
"cirq_type": "LineQubit",
"x": 0
}
]
}
],
[
{
"cirq_type": "OpIdentifier",
"gate_type": "HPowGate",
"qubits": [
{
"cirq_type": "LineQubit",
"x": 1
}
]
},
{
"cirq_type": "GateOperation",
"gate": {
"cirq_type": "BitFlipChannel",
"p": 0.1
},
"qubits": [
{
"cirq_type": "LineQubit",
"x": 1
}
]
}
]
],
"prepend": false,
"require_physical_tag": false
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[
cirq.devices.InsertionNoiseModel(ops_added={cirq.devices.noise_utils.OpIdentifier(cirq.ops.common_gates.XPowGate, cirq.LineQubit(0)): cirq.bit_flip(p=0.2).on(cirq.LineQubit(0))}, prepend=False, require_physical_tag=False),
cirq.devices.InsertionNoiseModel(ops_added={cirq.devices.noise_utils.OpIdentifier(cirq.ops.common_gates.XPowGate, cirq.LineQubit(0)): cirq.bit_flip(p=0.2).on(cirq.LineQubit(0)), cirq.devices.noise_utils.OpIdentifier(cirq.ops.common_gates.HPowGate, cirq.LineQubit(1)): cirq.bit_flip(p=0.1).on(cirq.LineQubit(1))}, prepend=False, require_physical_tag=False)
]
11 changes: 7 additions & 4 deletions cirq-core/cirq/vis/heatmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from dataclasses import astuple, dataclass
from typing import (
Any,
cast,
Dict,
List,
Mapping,
Expand Down Expand Up @@ -217,7 +218,7 @@ def _plot_colorbar(
)
position = self._config['colorbar_position']
orien = 'vertical' if position in ('left', 'right') else 'horizontal'
colorbar = ax.figure.colorbar(
colorbar = cast(plt.Figure, ax.figure).colorbar(
mappable, colorbar_ax, ax, orientation=orien, **self._config.get("colorbar_options", {})
)
colorbar_ax.tick_params(axis='y', direction='out')
Expand All @@ -230,15 +231,15 @@ def _write_annotations(
ax: plt.Axes,
) -> None:
"""Writes annotations to the center of cells. Internal."""
for (center, annotation), facecolor in zip(centers_and_annot, collection.get_facecolors()):
for (center, annotation), facecolor in zip(centers_and_annot, collection.get_facecolor()):
# Calculate the center of the cell, assuming that it is a square
# centered at (x=col, y=row).
if not annotation:
continue
x, y = center
face_luminance = vis_utils.relative_luminance(facecolor)
face_luminance = vis_utils.relative_luminance(facecolor) # type: ignore
text_color = 'black' if face_luminance > 0.4 else 'white'
text_kwargs = dict(color=text_color, ha="center", va="center")
text_kwargs: Dict[str, Any] = dict(color=text_color, ha="center", va="center")
text_kwargs.update(self._config.get('annotation_text_kwargs', {}))
ax.text(x, y, annotation, **text_kwargs)

Expand Down Expand Up @@ -295,6 +296,7 @@ def plot(
show_plot = not ax
if not ax:
fig, ax = plt.subplots(figsize=(8, 8))
ax = cast(plt.Axes, ax)
original_config = copy.deepcopy(self._config)
self.update_config(**kwargs)
collection = self._plot_on_axis(ax)
Expand Down Expand Up @@ -381,6 +383,7 @@ def plot(
show_plot = not ax
if not ax:
fig, ax = plt.subplots(figsize=(8, 8))
ax = cast(plt.Axes, ax)
original_config = copy.deepcopy(self._config)
self.update_config(**kwargs)
qubits = set([q for qubits in self._value_map.keys() for q in qubits])
Expand Down
10 changes: 10 additions & 0 deletions cirq-core/cirq/vis/heatmap_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ def ax():
return figure.add_subplot(111)


def test_default_ax():
row_col_list = ((0, 5), (8, 1), (7, 0), (13, 5), (1, 6), (3, 2), (2, 8))
test_value_map = {
grid_qubit.GridQubit(row, col): np.random.random() for (row, col) in row_col_list
}
_, _ = heatmap.Heatmap(test_value_map).plot()


@pytest.mark.parametrize('tuple_keys', [True, False])
def test_cells_positions(ax, tuple_keys):
row_col_list = ((0, 5), (8, 1), (7, 0), (13, 5), (1, 6), (3, 2), (2, 8))
Expand Down Expand Up @@ -61,6 +69,8 @@ def test_two_qubit_heatmap(ax):
title = "Two Qubit Interaction Heatmap"
heatmap.TwoQubitInteractionHeatmap(value_map, title=title).plot(ax)
assert ax.get_title() == title
# Test default axis
heatmap.TwoQubitInteractionHeatmap(value_map, title=title).plot()


def test_invalid_args():
Expand Down
Loading

0 comments on commit b4ce5db

Please sign in to comment.