Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
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: no cover
return InstrumentedFinder(finder, module_name, wrap_func, after_exec)

new_meta_path = [wrap(finder) for finder in sys.meta_path]
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
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: no cover
return self._from_moments(resolved_moments)

def _qasm_(self, args: Optional['cirq.QasmArgs'] = None) -> str:
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: no cover
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
13 changes: 0 additions & 13 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
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
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: no cover
# Skip if an optimization removed the op we're considering.
if op not in circuit[i].operations:
continue
continue # pragma: no cover
opt = self.optimization_at(circuit, i, op)
# Skip if the optimization did nothing.
if opt is None:
continue
continue # pragma: no cover

# 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: no cover
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: no cover

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: no cover
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: no cover

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,13 @@ 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: no cover
remainder = ComputationalBasisProductState(
[self.basis[i] for i in range(len(self.basis)) if i not in axes]
)
return extracted, remainder
) # pragma: no cover
return extracted, remainder # pragma: no cover

def reindex(self, axes: Sequence[int]) -> 'ComputationalBasisProductState':
return ComputationalBasisProductState([self.basis[i] for i in axes])
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/contrib/graph_device/graph_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ class UndirectedGraphDeviceEdge(metaclass=abc.ABCMeta):

@abc.abstractmethod
def duration_of(self, operation: ops.Operation) -> value.Duration:
pass # pragma: no cover
pass

@abc.abstractmethod
def validate_operation(self, operation: ops.Operation) -> None:
pass # pragma: no cover
pass


@value.value_equality
Expand Down Expand Up @@ -60,7 +60,7 @@ def duration_of(self, operation: ops.Operation) -> value.Duration:
return value.Duration(picos=0)

def validate_operation(self, operation: ops.Operation) -> None:
pass # pragma: no cover
pass

def __eq__(self, other):
return self.__class__ == other.__class__
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: no cover


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: no cover


def test_move_non_clifford_into_clifford():
Expand Down
19 changes: 11 additions & 8 deletions cirq-core/cirq/contrib/qcircuit/qcircuit_pdf.py
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.

# pragma: no cover

import errno
import os
Expand All @@ -30,6 +29,7 @@ def circuit_to_pdf_using_qcircuit_via_tex(
qcircuit_kwargs=None,
clean_ext=('dvi', 'ps'),
documentclass='article',
prepare_only=False,
):
"""Compiles the QCircuit-based latex diagram of the given circuit.

Expand All @@ -43,6 +43,8 @@ def circuit_to_pdf_using_qcircuit_via_tex(
default, latexmk is used with the '-pdfps' flag, which produces
intermediary dvi and ps files.
documentclass: The documentclass of the latex file.
prepare_only: If True, only prepare the document, do not generate PDF.
Used only for testing.

Raises:
OSError, IOError: If cleanup fails.
Expand All @@ -59,10 +61,11 @@ def circuit_to_pdf_using_qcircuit_via_tex(
doc.packages.append(Package('qcircuit'))
doc.preamble.append(Package('inputenc', options=['utf8']))
doc.append(NoEscape(tex))
doc.generate_pdf(filepath, **pdf_kwargs)
for ext in clean_ext:
try:
os.remove(filepath + '.' + ext)
except (OSError, IOError) as e:
if e.errno != errno.ENOENT:
raise
if not prepare_only: # pragma: nocover
doc.generate_pdf(filepath, **pdf_kwargs)
for ext in clean_ext:
try:
os.remove(filepath + '.' + ext)
except (OSError, IOError) as e:
if e.errno != errno.ENOENT:
raise
21 changes: 21 additions & 0 deletions cirq-core/cirq/contrib/qcircuit/qcircuit_pdf_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Copyright 2025 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.

import cirq
import cirq.contrib.qcircuit.qcircuit_pdf as qcircuit_pdf


def test_qcircuit_pdf_prepare_only():
circuit = cirq.Circuit(cirq.X(cirq.q(0)), cirq.CZ(cirq.q(0), cirq.q(1)))
qcircuit_pdf.circuit_to_pdf_using_qcircuit_via_tex(circuit, "/tmp/test_file", prepare_only=True)
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: no cover

@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
4 changes: 2 additions & 2 deletions cirq-core/cirq/contrib/quimb/mps_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def _create_partial_simulation_state(
MPSState args for simulating the Circuit.
"""
if isinstance(initial_state, MPSState):
return initial_state
return initial_state # pragma: no cover

return MPSState(
qubits=qubits,
Expand Down Expand Up @@ -460,7 +460,7 @@ def apply_op(self, op: Any, axes: Sequence[int], prng: np.random.RandomState):
raise ValueError('Can only handle 1 and 2 qubit operations')
return True

def estimation_stats(self):
def estimation_stats(self): # pragma: no cover
"""Returns some statistics about the memory usage and quality of the approximation."""

num_coefs_used = sum([Mi.data.size for Mi in self._M])
Expand Down
5 changes: 5 additions & 0 deletions cirq-core/cirq/contrib/quimb/mps_simulator_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,11 @@ def test_simulation_state_initializer():
)
assert s.qubits == (cirq.LineQubit(0),)
assert s.classical_data == expected_classical_data
assert s.estimation_stats() == {
'estimated_fidelity': 1.0,
'memory_bytes': 16,
'num_coefs_used': 2,
}


def test_act_on_gate():
Expand Down
4 changes: 3 additions & 1 deletion cirq-core/cirq/contrib/routing/greedy_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ def create_circuit_and_device():

def create_hanging_routing_instance(circuit, device_graph):
"""Create a test problem instance."""
route_circuit_greedily(circuit, device_graph, max_search_radius=2, random_state=1)
route_circuit_greedily( # pragma: no cover
circuit, device_graph, max_search_radius=2, random_state=1
)


def test_router_hanging():
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/svg/svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def tdd_to_svg(
# qubits start at far left and their wires shall be blue
stroke = QBLUE
else:
stroke = 'black'
stroke = 'black' # pragma: no cover
t += f'<line x1="{x1}" x2="{x2}" y1="{y}" y2="{y}" stroke="{stroke}" stroke-width="1" />'

for xi, yi1, yi2, _, _ in tdd.vertical_lines:
Expand Down
Loading
Loading