Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion cirq-core/cirq/_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def wrap_module_executions(

def wrap(finder: Any) -> Any:
if not hasattr(finder, 'find_spec'):
return finder
return finder # pragma: nocover
return InstrumentedFinder(finder, module_name, wrap_func, after_exec)

new_meta_path = [wrap(finder) for finder in sys.meta_path]
Expand Down
28 changes: 14 additions & 14 deletions cirq-core/cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def _from_moments(cls: Type[CIRCUIT_TYPE], moments: Iterable['cirq.Moment']) ->
@property
@abc.abstractmethod
def moments(self) -> Sequence['cirq.Moment']:
pass
pass # pragma: nocover

@abc.abstractmethod
def freeze(self) -> 'cirq.FrozenCircuit':
Expand Down Expand Up @@ -241,27 +241,27 @@ def _decompose_(self) -> 'cirq.OP_TREE':
# pylint: disable=function-redefined
@overload
def __getitem__(self, key: int) -> 'cirq.Moment':
pass
pass # pragma: nocover

@overload
def __getitem__(self, key: Tuple[int, 'cirq.Qid']) -> 'cirq.Operation':
pass
pass # pragma: nocover

@overload
def __getitem__(self, key: Tuple[int, Iterable['cirq.Qid']]) -> 'cirq.Moment':
pass
pass # pragma: nocover

@overload
def __getitem__(self, key: slice) -> Self:
pass
pass # pragma: nocover

@overload
def __getitem__(self, key: Tuple[slice, 'cirq.Qid']) -> Self:
pass
pass # pragma: nocover

@overload
def __getitem__(self, key: Tuple[slice, Iterable['cirq.Qid']]) -> Self:
pass
pass # pragma: nocover

def __getitem__(self, key):
if isinstance(key, slice):
Expand Down Expand Up @@ -1316,7 +1316,7 @@ def _resolve_parameters_(self, resolver: 'cirq.ParamResolver', recursive: bool)
changed = True
resolved_moments.append(resolved_moment)
if not changed:
return self
return self # pragma: nocover
return self._from_moments(resolved_moments)

def _qasm_(self, args: Optional['cirq.QasmArgs'] = None) -> str:
Expand Down Expand Up @@ -1634,7 +1634,7 @@ def _overlap_collision_time(
elif align == Alignment.FIRST:
upper_bound = min(len(c1), len(c2))
else:
raise NotImplementedError(f"Unrecognized alignment: {align}")
raise NotImplementedError(f"Unrecognized alignment: {align}") # pragma: nocover

t = 0
while t < upper_bound:
Expand Down Expand Up @@ -1903,11 +1903,11 @@ def copy(self) -> 'Circuit':
# pylint: disable=function-redefined
@overload
def __setitem__(self, key: int, value: 'cirq.Moment'):
pass
pass # pragma: nocover

@overload
def __setitem__(self, key: slice, value: Iterable['cirq.Moment']):
pass
pass # pragma: nocover

def __setitem__(self, key, value):
if isinstance(key, int) and not isinstance(value, Moment):
Expand Down Expand Up @@ -2317,7 +2317,7 @@ def insert_at_frontier(
frontier = defaultdict(lambda: 0)
flat_ops = tuple(ops.flatten_to_ops(operations))
if not flat_ops:
return frontier
return frontier # pragma: nocover
qubits = set(q for op in flat_ops for q in op.qubits)
if any(frontier[q] > start for q in qubits):
raise ValueError(
Expand Down Expand Up @@ -2796,14 +2796,14 @@ def _list_repr_with_indented_item_lines(items: Sequence[Any]) -> str:
def _group_until_different(
items: Iterable[_TIn], key: Callable[[_TIn], _TKey]
) -> Iterable[Tuple[_TKey, List[_TIn]]]:
pass
pass # pragma: nocover


@overload
def _group_until_different(
items: Iterable[_TIn], key: Callable[[_TIn], _TKey], val: Callable[[_TIn], _TOut]
) -> Iterable[Tuple[_TKey, List[_TOut]]]:
pass
pass # pragma: nocover


def _group_until_different(items: Iterable[_TIn], key: Callable[[_TIn], _TKey], val=lambda e: e):
Expand Down
17 changes: 2 additions & 15 deletions cirq-core/cirq/circuits/circuit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,6 @@ class _Foxy(ValidatingTestDevice):
q0, q1, q2, q3 = cirq.LineQubit.range(4)


class _MomentAndOpTypeValidatingDeviceType(cirq.Device):
def validate_operation(self, operation):
if not isinstance(operation, cirq.Operation):
raise ValueError(f'not isinstance({operation!r}, {cirq.Operation!r})')

def validate_moment(self, moment):
if not isinstance(moment, cirq.Moment):
raise ValueError(f'not isinstance({moment!r}, {cirq.Moment!r})')


moment_and_op_type_validating_device = _MomentAndOpTypeValidatingDeviceType()


def test_from_moments():
a, b, c, d = cirq.LineQubit.range(4)
moment = cirq.Moment(cirq.Z(a), cirq.Z(b))
Expand Down Expand Up @@ -4778,7 +4765,7 @@ def __init__(self, text: str):
self.text = text

def with_qubits(self, *new_qubits):
raise NotImplementedError()
raise NotImplementedError() # pragma: nocover

@property
def qubits(self):
Expand All @@ -4789,7 +4776,7 @@ def _circuit_diagram_info_(self, args) -> str:

class CustomOperationAnnotationNoInfo(cirq.Operation):
def with_qubits(self, *new_qubits):
raise NotImplementedError()
raise NotImplementedError() # pragma: nocover

@property
def qubits(self):
Expand Down
1 change: 1 addition & 0 deletions cirq-core/cirq/circuits/insert_strategy_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

def test_repr():
assert repr(cirq.InsertStrategy.NEW) == 'cirq.InsertStrategy.NEW'
assert str(cirq.InsertStrategy.NEW) == 'NEW'


@pytest.mark.parametrize(
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/circuits/moment.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,11 +547,11 @@ def __sub__(self, other: 'cirq.OP_TREE') -> 'cirq.Moment':
# pylint: disable=function-redefined
@overload
def __getitem__(self, key: raw_types.Qid) -> 'cirq.Operation':
pass
pass # pragma: nocover

@overload
def __getitem__(self, key: Iterable[raw_types.Qid]) -> 'cirq.Moment':
pass
pass # pragma: nocover

def __getitem__(self, key):
if isinstance(key, raw_types.Qid):
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/circuits/optimization_pass.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,14 @@ def optimize_circuit(self, circuit: 'cirq.Circuit'):

# Skip if an optimization removed the circuit underneath us.
if i >= len(circuit):
continue
continue # pragma: nocover
# Skip if an optimization removed the op we're considering.
if op not in circuit[i].operations:
continue
continue # pragma: nocover
opt = self.optimization_at(circuit, i, op)
# Skip if the optimization did nothing.
if opt is None:
continue
continue # pragma: nocover

# Clear target area, and insert new operations.
circuit.clear_operations_touching(
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/circuits/qasm_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ def fallback(op):
return NotImplemented

if len(op.qubits) == 1:
return QasmUGate.from_matrix(mat).on(*op.qubits)
return QasmUGate.from_matrix(mat).on(*op.qubits) # pragma: nocover
return QasmTwoQubitGate.from_matrix(mat).on(*op.qubits)

def on_stuck(bad_op):
Expand Down
5 changes: 5 additions & 0 deletions cirq-core/cirq/circuits/qasm_output_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ def test_qasm_u_qubit_gate_unitary():

cirq.testing.assert_implements_consistent_protocols(g)

u = cirq.unitary(cirq.Y)
g = QasmUGate.from_matrix(u)
cirq.testing.assert_allclose_up_to_global_phase(cirq.unitary(g), u, atol=1e-7)
cirq.testing.assert_implements_consistent_protocols(g)


def test_qasm_two_qubit_gate_unitary():
u = cirq.testing.random_unitary(4)
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/circuits/text_diagram_drawer.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def content_present(self, x: int, y: int) -> bool:

# Horizontal line?
if any(line_y == y and x1 < x < x2 for line_y, x1, x2, _, _ in self.horizontal_lines):
return True
return True # pragma: nocover

return False

Expand Down
11 changes: 11 additions & 0 deletions cirq-core/cirq/contrib/acquaintance/bipartite_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,14 @@ def test_decomposition_permutation_consistency(part_size, subgraph):
cca.update_mapping(mapping, gate._decompose_(qubits))
permutation = gate.permutation()
assert {qubits[i]: j for i, j in permutation.items()} == mapping


def test_bad_number_of_qubits():
gate = cca.BipartiteSwapNetworkGate(cca.BipartiteGraphType.COMPLETE, 6)
qubits = cirq.LineQubit.range(6)
mapping = {q: i for i, q in enumerate(qubits)}
with pytest.raises(ValueError, match='len'):
cca.update_mapping(mapping, gate._decompose_(qubits))
gate.part_size = 5
with pytest.raises(ValueError, match='qubit_count'):
gate.permutation()
5 changes: 5 additions & 0 deletions cirq-core/cirq/contrib/acquaintance/devices_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,8 @@ def test_acquaintance_device():
swap_network = cca.SwapNetworkGate((1, 2, 1))
cca.UnconstrainedAcquaintanceDevice.validate_operation(cca.acquaint(*qubits[:2]))
cca.UnconstrainedAcquaintanceDevice.validate_operation(swap_network(*qubits))


def test_not_operation():
with pytest.raises(TypeError):
_ = cca.get_acquaintance_size(cirq.LineQubit(1))
1 change: 1 addition & 0 deletions cirq-core/cirq/contrib/acquaintance/executor_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def test_executor_explicit():
}
initial_mapping = {q: i for i, q in enumerate(sorted(qubits))}
execution_strategy = cca.GreedyExecutionStrategy(gates, initial_mapping)
assert execution_strategy.device == cirq.UNCONSTRAINED_DEVICE

with pytest.raises(ValueError):
executor = cca.StrategyExecutorTransformer(None)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import cirq
import cirq.contrib.acquaintance as cca
import cirq.contrib.acquaintance.inspection_utils as inspection_utils


@pytest.mark.parametrize('n_qubits, acquaintance_size', product(range(2, 6), range(2, 5)))
Expand All @@ -27,3 +28,7 @@ def test_get_logical_acquaintance_opportunities(n_qubits, acquaintance_size):
initial_mapping = {q: i for i, q in enumerate(qubits)}
opps = cca.get_logical_acquaintance_opportunities(acquaintance_strategy, initial_mapping)
assert opps == set(frozenset(s) for s in combinations(range(n_qubits), acquaintance_size))


def test_device():
assert inspection_utils.LogicalAnnotator({}).device == cirq.UNCONSTRAINED_DEVICE
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/acquaintance/shift.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:

def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs') -> Tuple[str, ...]:
if args.known_qubit_count is None:
return NotImplemented
return NotImplemented # pragma: nocover
direction_symbols = ('╲', '╱') if args.use_unicode_characters else ('\\', '/')
wire_symbols = tuple(
direction_symbols[int(i >= self.shift)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def __init__(self, initial_state: List[int]):
self.basis = initial_state

def copy(self, deep_copy_buffers: bool = True) -> 'ComputationalBasisState':
return ComputationalBasisState(self.basis)
return ComputationalBasisState(self.basis) # pragma: nocover

def measure(self, axes: Sequence[int], seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None):
return [self.basis[i] for i in axes]
Expand Down Expand Up @@ -149,11 +149,11 @@ def kron(self, other: 'ComputationalBasisProductState') -> 'ComputationalBasisPr
def factor(
self, axes: Sequence[int], *, validate=True, atol=1e-07
) -> Tuple['ComputationalBasisProductState', 'ComputationalBasisProductState']:
extracted = ComputationalBasisProductState([self.basis[i] for i in axes])
extracted = ComputationalBasisProductState([self.basis[i] for i in axes]) # pragma: nocover
remainder = ComputationalBasisProductState(
[self.basis[i] for i in range(len(self.basis)) if i not in axes]
)
return extracted, remainder
) # pragma: nocover
return extracted, remainder # pragma: nocover

def reindex(self, axes: Sequence[int]) -> 'ComputationalBasisProductState':
return ComputationalBasisProductState([self.basis[i] for i in axes])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ def pauli_string_optimized_circuit(
def assert_no_multi_qubit_pauli_strings(circuit: circuits.Circuit) -> None:
for op in circuit.all_operations():
if isinstance(op, PauliStringGateOperation):
assert len(op.pauli_string) == 1, 'Multi qubit Pauli string left over'
assert (
len(op.pauli_string) == 1
), 'Multi qubit Pauli string left over' # pragma: nocover


def merge_equal_strings(string_dag: circuitdag.CircuitDag) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.


import cirq
from cirq.contrib.paulistring import CliffordTargetGateset, pauli_string_optimized_circuit

Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/paulistring/recombine_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
def _assert_no_multi_qubit_pauli_strings(circuit: cirq.Circuit) -> None:
for op in circuit.all_operations():
if isinstance(op, cirq.PauliStringGateOperation):
assert len(op.pauli_string) == 1
assert len(op.pauli_string) == 1 # pragma: nocover


def test_move_non_clifford_into_clifford():
Expand Down
15 changes: 8 additions & 7 deletions cirq-core/cirq/contrib/qcircuit/qcircuit_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# pragma: no cover

import errno
import os
import errno # pragma: nocover
import os # pragma: nocover

from pylatex import Document, NoEscape, Package
from pylatex import Document, NoEscape, Package # pragma: nocover

from cirq import circuits
from cirq.contrib.qcircuit.qcircuit_diagram import circuit_to_latex_using_qcircuit
from cirq import circuits # pragma: nocover
from cirq.contrib.qcircuit.qcircuit_diagram import (
circuit_to_latex_using_qcircuit, # pragma: nocover
)


def circuit_to_pdf_using_qcircuit_via_tex(
def circuit_to_pdf_using_qcircuit_via_tex( # pragma: nocover
circuit: circuits.Circuit,
filepath: str,
pdf_kwargs=None,
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/qcircuit/qcircuit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(self, *qubits):
self._qubits = qubits

def with_qubits(self, *new_qubits):
return MagicOp(*new_qubits)
return MagicOp(*new_qubits) # pragma: nocover

@property
def qubits(self):
Expand Down
7 changes: 1 addition & 6 deletions cirq-core/cirq/contrib/quantum_volume/quantum_volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"""

from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
from typing import Callable, Dict, List, Optional, Set, Tuple

import networkx as nx
import numpy as np
Expand Down Expand Up @@ -416,11 +416,6 @@ def execute_circuits(
return results


def _get_device_graph(device_or_qubits: Any):
qubits = device_or_qubits if isinstance(device_or_qubits, list) else device_or_qubits.qubits
return ccr.gridqubits_to_graph_device(qubits)


def calculate_quantum_volume(
*,
num_qubits: int,
Expand Down
Loading
Loading