Skip to content

Commit

Permalink
Merge pull request #1 from quantumlib/master
Browse files Browse the repository at this point in the history
updat with latest version
  • Loading branch information
shef4 authored Sep 28, 2023
2 parents 0e80fa5 + fd18da5 commit 0a68ee5
Show file tree
Hide file tree
Showing 93 changed files with 1,687 additions and 1,247 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
3 changes: 3 additions & 0 deletions cirq-core/cirq/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,9 @@ def _print(self, expr, **kwargs):
if isinstance(value, Dict):
return '{' + ','.join(f"{proper_repr(k)}: {proper_repr(v)}" for k, v in value.items()) + '}'

if hasattr(value, "__qualname__"):
return f"{value.__module__}.{value.__qualname__}"

return repr(value)


Expand Down
16 changes: 8 additions & 8 deletions cirq-core/cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1465,14 +1465,14 @@ def concat_ragged(
Beware that this method is *not* associative. For example:
>>> a, b = cirq.LineQubit.range(2)
>>> A = cirq.Circuit(cirq.H(a))
>>> B = cirq.Circuit(cirq.H(b))
>>> f = cirq.Circuit.concat_ragged
>>> f(f(A, B), A) == f(A, f(B, A))
False
>>> len(f(f(f(A, B), A), B)) == len(f(f(A, f(B, A)), B))
False
>>> a, b = cirq.LineQubit.range(2)
>>> A = cirq.Circuit(cirq.H(a))
>>> B = cirq.Circuit(cirq.H(b))
>>> f = cirq.Circuit.concat_ragged
>>> f(f(A, B), A) == f(A, f(B, A))
False
>>> len(f(f(f(A, B), A), B)) == len(f(f(A, f(B, A)), B))
False
Args:
*circuits: The circuits to concatenate.
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
12 changes: 7 additions & 5 deletions cirq-core/cirq/devices/noise_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import numpy as np

from cirq import ops, protocols, value
from cirq._compat import proper_repr

if TYPE_CHECKING:
import cirq
Expand Down Expand Up @@ -78,20 +79,21 @@ def __str__(self):
return f'{self.gate_type}{self.qubits}'

def __repr__(self) -> str:
fullname = f'{self.gate_type.__module__}.{self.gate_type.__qualname__}'
qubits = ', '.join(map(repr, self.qubits))
return f'cirq.devices.noise_utils.OpIdentifier({fullname}, {qubits})'
return f'cirq.devices.noise_utils.OpIdentifier({proper_repr(self.gate_type)}, {qubits})'

def _value_equality_values_(self) -> Any:
return (self.gate_type, self.qubits)

def _json_dict_(self) -> Dict[str, Any]:
gate_json = protocols.json_cirq_type(self._gate_type)
return {'gate_type': gate_json, 'qubits': self._qubits}
if hasattr(self.gate_type, '__name__'):
return {'gate_type': protocols.json_cirq_type(self._gate_type), 'qubits': self._qubits}
return {'gate_type': self._gate_type, 'qubits': self._qubits}

@classmethod
def _from_json_dict_(cls, gate_type, qubits, **kwargs) -> 'OpIdentifier':
gate_type = protocols.cirq_type_from_json(gate_type)
if isinstance(gate_type, str):
gate_type = protocols.cirq_type_from_json(gate_type)
return cls(gate_type, *qubits)


Expand Down
7 changes: 7 additions & 0 deletions cirq-core/cirq/devices/noise_utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ def test_op_id_swap():
assert cirq.CZ(q1, q0) in swap_id


def test_op_id_instance():
q0 = cirq.LineQubit.range(1)[0]
gate = cirq.SingleQubitCliffordGate.from_xz_map((cirq.X, False), (cirq.Z, False))
op_id = OpIdentifier(gate, q0)
cirq.testing.assert_equivalent_repr(op_id)


@pytest.mark.parametrize(
'decay_constant,num_qubits,expected_output',
[(0.01, 1, 1 - (0.99 * 1 / 2)), (0.05, 2, 1 - (0.95 * 3 / 4))],
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
78 changes: 40 additions & 38 deletions cirq-core/cirq/interop/quirk/url_to_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,39 +77,40 @@ def quirk_url_to_circuit(
a billion laughs attack in the form of nested custom gates.
Examples:
>>> print(cirq.quirk_url_to_circuit(
... 'http://algassert.com/quirk#circuit={"cols":[["H"],["•","X"]]}'
... ))
0: ───H───@───
1: ───────X───
>>> print(cirq.quirk_url_to_circuit(
... 'http://algassert.com/quirk#circuit={"cols":[["H"],["•","X"]]}',
... qubits=[cirq.NamedQubit('Alice'), cirq.NamedQubit('Bob')]
... ))
Alice: ───H───@───
Bob: ─────────X───
>>> print(cirq.quirk_url_to_circuit(
... 'http://algassert.com/quirk#circuit={"cols":[["iswap"]]}',
... extra_cell_makers={'iswap': cirq.ISWAP}))
0: ───iSwap───
1: ───iSwap───
>>> print(cirq.quirk_url_to_circuit(
... 'http://algassert.com/quirk#circuit={"cols":[["iswap"]]}',
... extra_cell_makers=[
... cirq.interop.quirk.cells.CellMaker(
... identifier='iswap',
... size=2,
... maker=lambda args: cirq.ISWAP(*args.qubits))
... ]))
0: ───iSwap───
>>> print(cirq.quirk_url_to_circuit(
... 'http://algassert.com/quirk#circuit={"cols":[["H"],["•","X"]]}'
... ))
0: ───H───@───
1: ───iSwap───
1: ───────X───
>>> print(cirq.quirk_url_to_circuit(
... 'http://algassert.com/quirk#circuit={"cols":[["H"],["•","X"]]}',
... qubits=[cirq.NamedQubit('Alice'), cirq.NamedQubit('Bob')]
... ))
Alice: ───H───@───
Bob: ─────────X───
>>> print(cirq.quirk_url_to_circuit(
... 'http://algassert.com/quirk#circuit={"cols":[["iswap"]]}',
... extra_cell_makers={'iswap': cirq.ISWAP}))
0: ───iSwap───
1: ───iSwap───
>>> print(cirq.quirk_url_to_circuit(
... 'http://algassert.com/quirk#circuit={"cols":[["iswap"]]}',
... extra_cell_makers=[
... cirq.interop.quirk.cells.CellMaker(
... identifier='iswap',
... size=2,
... maker=lambda args: cirq.ISWAP(*args.qubits))
... ]))
0: ───iSwap───
1: ───iSwap───
Returns:
The parsed circuit.
Expand Down Expand Up @@ -172,12 +173,13 @@ def quirk_json_to_circuit(
a billion laughs attack in the form of nested custom gates.
Examples:
>>> print(cirq.quirk_json_to_circuit(
... {"cols":[["H"], ["•", "X"]]}
... ))
0: ───H───@───
1: ───────X───
>>> print(cirq.quirk_json_to_circuit(
... {"cols":[["H"], ["•", "X"]]}
... ))
0: ───H───@───
1: ───────X───
Returns:
The parsed circuit.
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
7 changes: 2 additions & 5 deletions cirq-core/cirq/ops/common_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,13 +400,10 @@ class GeneralizedAmplitudeDampingChannel(raw_types.Gate):
This channel evolves a density matrix via
$$
\rho \rightarrow M_0 \rho M_0^\dagger
+ M_1 \rho M_1^\dagger
+ M_2 \rho M_2^\dagger
+ M_3 \rho M_3^\dagger
\rho \rightarrow \sum_{i=0}^3 M_i \rho M_i^\dagger
$$
With
with
$$
\begin{aligned}
Expand Down
3 changes: 3 additions & 0 deletions cirq-core/cirq/ops/dense_pauli_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,9 @@ def copy(
def __str__(self) -> str:
return super().__str__() + ' (mutable)'

def _value_equality_values_(self):
return self.coefficient, tuple(PAULI_CHARS[p] for p in self.pauli_mask)

@classmethod
def inline_gaussian_elimination(cls, rows: 'List[MutableDensePauliString]') -> None:
if not rows:
Expand Down
Loading

0 comments on commit 0a68ee5

Please sign in to comment.