cirq-core 1.5.0.dev20250403051212__py3-none-any.whl → 1.5.0.dev20250403142851__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of cirq-core might be problematic. Click here for more details.

Files changed (106) hide show
  1. cirq/_import.py +1 -1
  2. cirq/_version.py +1 -1
  3. cirq/_version_test.py +1 -1
  4. cirq/circuits/circuit.py +2 -2
  5. cirq/circuits/circuit_test.py +0 -13
  6. cirq/circuits/insert_strategy_test.py +1 -0
  7. cirq/circuits/optimization_pass.py +3 -3
  8. cirq/circuits/qasm_output.py +1 -1
  9. cirq/circuits/qasm_output_test.py +5 -0
  10. cirq/circuits/text_diagram_drawer.py +1 -1
  11. cirq/contrib/acquaintance/bipartite_test.py +11 -0
  12. cirq/contrib/acquaintance/devices_test.py +5 -0
  13. cirq/contrib/acquaintance/executor_test.py +1 -0
  14. cirq/contrib/acquaintance/inspection_utils_test.py +5 -0
  15. cirq/contrib/acquaintance/shift.py +1 -1
  16. cirq/contrib/custom_simulators/custom_state_simulator_test.py +6 -4
  17. cirq/contrib/graph_device/graph_device.py +3 -3
  18. cirq/contrib/paulistring/pauli_string_optimize.py +3 -1
  19. cirq/contrib/paulistring/pauli_string_optimize_test.py +0 -1
  20. cirq/contrib/paulistring/recombine_test.py +1 -1
  21. cirq/contrib/qcircuit/qcircuit_pdf.py +11 -8
  22. cirq/contrib/qcircuit/qcircuit_pdf_test.py +21 -0
  23. cirq/contrib/qcircuit/qcircuit_test.py +1 -1
  24. cirq/contrib/quantum_volume/quantum_volume.py +1 -6
  25. cirq/contrib/quimb/mps_simulator.py +2 -2
  26. cirq/contrib/quimb/mps_simulator_test.py +5 -0
  27. cirq/contrib/routing/greedy_test.py +3 -1
  28. cirq/contrib/svg/svg.py +1 -1
  29. cirq/contrib/svg/svg_test.py +3 -2
  30. cirq/devices/unconstrained_device_test.py +6 -0
  31. cirq/experiments/qubit_characterizations.py +4 -2
  32. cirq/experiments/random_quantum_circuit_generation.py +2 -3
  33. cirq/experiments/readout_confusion_matrix.py +4 -4
  34. cirq/linalg/combinators_test.py +3 -0
  35. cirq/linalg/decompositions_test.py +0 -5
  36. cirq/linalg/predicates.py +1 -1
  37. cirq/ops/clifford_gate.py +5 -14
  38. cirq/ops/common_gates.py +8 -8
  39. cirq/ops/common_gates_test.py +5 -0
  40. cirq/ops/control_values.py +1 -1
  41. cirq/ops/controlled_gate.py +1 -1
  42. cirq/ops/controlled_operation.py +1 -1
  43. cirq/ops/controlled_operation_test.py +6 -2
  44. cirq/ops/dense_pauli_string.py +1 -1
  45. cirq/ops/eigen_gate.py +1 -1
  46. cirq/ops/fourier_transform.py +0 -2
  47. cirq/ops/gate_operation.py +1 -1
  48. cirq/ops/gate_operation_test.py +1 -0
  49. cirq/ops/gateset_test.py +7 -0
  50. cirq/ops/greedy_qubit_manager_test.py +5 -0
  51. cirq/ops/kraus_channel_test.py +1 -0
  52. cirq/ops/mixed_unitary_channel_test.py +1 -0
  53. cirq/ops/op_tree_test.py +4 -0
  54. cirq/ops/pauli_measurement_gate_test.py +1 -0
  55. cirq/ops/pauli_string.py +3 -80
  56. cirq/ops/pauli_string_test.py +46 -0
  57. cirq/ops/phased_x_gate.py +1 -1
  58. cirq/ops/random_gate_channel_test.py +0 -6
  59. cirq/ops/raw_types.py +1 -1
  60. cirq/ops/raw_types_test.py +26 -1
  61. cirq/protocols/decompose_protocol_test.py +1 -1
  62. cirq/protocols/has_unitary_protocol_test.py +8 -7
  63. cirq/protocols/json_serialization_test.py +7 -6
  64. cirq/protocols/kraus_protocol.py +2 -2
  65. cirq/protocols/measurement_key_protocol_test.py +7 -7
  66. cirq/protocols/unitary_protocol_test.py +1 -1
  67. cirq/qis/channels_test.py +0 -9
  68. cirq/qis/measures.py +2 -1
  69. cirq/qis/measures_test.py +7 -0
  70. cirq/qis/states.py +1 -1
  71. cirq/sim/clifford/clifford_simulator.py +2 -1
  72. cirq/sim/clifford/clifford_simulator_test.py +32 -9
  73. cirq/sim/density_matrix_simulator.py +2 -1
  74. cirq/sim/density_matrix_simulator_test.py +10 -2
  75. cirq/sim/simulation_state.py +1 -1
  76. cirq/sim/simulation_state_test.py +1 -1
  77. cirq/sim/simulator_test.py +1 -1
  78. cirq/sim/sparse_simulator.py +2 -1
  79. cirq/sim/sparse_simulator_test.py +10 -2
  80. cirq/sim/state_vector_simulation_state_test.py +1 -1
  81. cirq/study/resolver.py +0 -4
  82. cirq/study/resolver_test.py +10 -1
  83. cirq/study/sweeps_test.py +18 -0
  84. cirq/testing/circuit_compare_test.py +6 -6
  85. cirq/testing/consistent_pauli_expansion_test.py +1 -1
  86. cirq/testing/consistent_qasm.py +1 -1
  87. cirq/testing/equals_tester.py +1 -1
  88. cirq/testing/equals_tester_test.py +5 -5
  89. cirq/testing/gate_features_test.py +5 -0
  90. cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py +1 -1
  91. cirq/transformers/gauge_compiling/gauge_compiling_test_utils_test.py +1 -1
  92. cirq/transformers/qubit_management_transformers.py +1 -1
  93. cirq/transformers/transformer_api_test.py +8 -0
  94. cirq/transformers/transformer_primitives_test.py +2 -2
  95. cirq/value/condition.py +1 -1
  96. cirq/value/duration.py +1 -1
  97. cirq/value/periodic_value_test.py +5 -0
  98. cirq/value/value_equality_attr_test.py +1 -1
  99. cirq/vis/heatmap_test.py +1 -1
  100. cirq/work/observable_settings.py +2 -1
  101. cirq/work/observable_settings_test.py +1 -0
  102. {cirq_core-1.5.0.dev20250403051212.dist-info → cirq_core-1.5.0.dev20250403142851.dist-info}/METADATA +1 -1
  103. {cirq_core-1.5.0.dev20250403051212.dist-info → cirq_core-1.5.0.dev20250403142851.dist-info}/RECORD +106 -105
  104. {cirq_core-1.5.0.dev20250403051212.dist-info → cirq_core-1.5.0.dev20250403142851.dist-info}/LICENSE +0 -0
  105. {cirq_core-1.5.0.dev20250403051212.dist-info → cirq_core-1.5.0.dev20250403142851.dist-info}/WHEEL +0 -0
  106. {cirq_core-1.5.0.dev20250403051212.dist-info → cirq_core-1.5.0.dev20250403142851.dist-info}/top_level.txt +0 -0
cirq/_import.py CHANGED
@@ -132,7 +132,7 @@ def wrap_module_executions(
132
132
 
133
133
  def wrap(finder: Any) -> Any:
134
134
  if not hasattr(finder, 'find_spec'):
135
- return finder
135
+ return finder # pragma: no cover
136
136
  return InstrumentedFinder(finder, module_name, wrap_func, after_exec)
137
137
 
138
138
  new_meta_path = [wrap(finder) for finder in sys.meta_path]
cirq/_version.py CHANGED
@@ -28,4 +28,4 @@ if sys.version_info < (3, 10, 0): # pragma: no cover
28
28
  'of cirq (e.g. "python -m pip install cirq==1.1.*")'
29
29
  )
30
30
 
31
- __version__ = "1.5.0.dev20250403051212"
31
+ __version__ = "1.5.0.dev20250403142851"
cirq/_version_test.py CHANGED
@@ -3,4 +3,4 @@ import cirq
3
3
 
4
4
 
5
5
  def test_version():
6
- assert cirq.__version__ == "1.5.0.dev20250403051212"
6
+ assert cirq.__version__ == "1.5.0.dev20250403142851"
cirq/circuits/circuit.py CHANGED
@@ -1316,7 +1316,7 @@ class AbstractCircuit(abc.ABC):
1316
1316
  changed = True
1317
1317
  resolved_moments.append(resolved_moment)
1318
1318
  if not changed:
1319
- return self
1319
+ return self # pragma: no cover
1320
1320
  return self._from_moments(resolved_moments)
1321
1321
 
1322
1322
  def _qasm_(self, args: Optional['cirq.QasmArgs'] = None) -> str:
@@ -2317,7 +2317,7 @@ class Circuit(AbstractCircuit):
2317
2317
  frontier = defaultdict(lambda: 0)
2318
2318
  flat_ops = tuple(ops.flatten_to_ops(operations))
2319
2319
  if not flat_ops:
2320
- return frontier
2320
+ return frontier # pragma: no cover
2321
2321
  qubits = set(q for op in flat_ops for q in op.qubits)
2322
2322
  if any(frontier[q] > start for q in qubits):
2323
2323
  raise ValueError(
@@ -55,19 +55,6 @@ if TYPE_CHECKING:
55
55
  q0, q1, q2, q3 = cirq.LineQubit.range(4)
56
56
 
57
57
 
58
- class _MomentAndOpTypeValidatingDeviceType(cirq.Device):
59
- def validate_operation(self, operation):
60
- if not isinstance(operation, cirq.Operation):
61
- raise ValueError(f'not isinstance({operation!r}, {cirq.Operation!r})')
62
-
63
- def validate_moment(self, moment):
64
- if not isinstance(moment, cirq.Moment):
65
- raise ValueError(f'not isinstance({moment!r}, {cirq.Moment!r})')
66
-
67
-
68
- moment_and_op_type_validating_device = _MomentAndOpTypeValidatingDeviceType()
69
-
70
-
71
58
  def test_from_moments():
72
59
  a, b, c, d = cirq.LineQubit.range(4)
73
60
  moment = cirq.Moment(cirq.Z(a), cirq.Z(b))
@@ -21,6 +21,7 @@ import cirq
21
21
 
22
22
  def test_repr():
23
23
  assert repr(cirq.InsertStrategy.NEW) == 'cirq.InsertStrategy.NEW'
24
+ assert str(cirq.InsertStrategy.NEW) == 'NEW'
24
25
 
25
26
 
26
27
  @pytest.mark.parametrize(
@@ -137,14 +137,14 @@ class PointOptimizer:
137
137
 
138
138
  # Skip if an optimization removed the circuit underneath us.
139
139
  if i >= len(circuit):
140
- continue
140
+ continue # pragma: no cover
141
141
  # Skip if an optimization removed the op we're considering.
142
142
  if op not in circuit[i].operations:
143
- continue
143
+ continue # pragma: no cover
144
144
  opt = self.optimization_at(circuit, i, op)
145
145
  # Skip if the optimization did nothing.
146
146
  if opt is None:
147
- continue
147
+ continue # pragma: no cover
148
148
 
149
149
  # Clear target area, and insert new operations.
150
150
  circuit.clear_operations_touching(
@@ -349,7 +349,7 @@ class QasmOutput:
349
349
  return NotImplemented
350
350
 
351
351
  if len(op.qubits) == 1:
352
- return QasmUGate.from_matrix(mat).on(*op.qubits)
352
+ return QasmUGate.from_matrix(mat).on(*op.qubits) # pragma: no cover
353
353
  return QasmTwoQubitGate.from_matrix(mat).on(*op.qubits)
354
354
 
355
355
  def on_stuck(bad_op):
@@ -53,6 +53,11 @@ def test_qasm_u_qubit_gate_unitary():
53
53
 
54
54
  cirq.testing.assert_implements_consistent_protocols(g)
55
55
 
56
+ u = cirq.unitary(cirq.Y)
57
+ g = QasmUGate.from_matrix(u)
58
+ cirq.testing.assert_allclose_up_to_global_phase(cirq.unitary(g), u, atol=1e-7)
59
+ cirq.testing.assert_implements_consistent_protocols(g)
60
+
56
61
 
57
62
  def test_qasm_two_qubit_gate_unitary():
58
63
  u = cirq.testing.random_unitary(4)
@@ -135,7 +135,7 @@ class TextDiagramDrawer:
135
135
 
136
136
  # Horizontal line?
137
137
  if any(line_y == y and x1 < x < x2 for line_y, x1, x2, _, _ in self.horizontal_lines):
138
- return True
138
+ return True # pragma: no cover
139
139
 
140
140
  return False
141
141
 
@@ -339,3 +339,14 @@ def test_decomposition_permutation_consistency(part_size, subgraph):
339
339
  cca.update_mapping(mapping, gate._decompose_(qubits))
340
340
  permutation = gate.permutation()
341
341
  assert {qubits[i]: j for i, j in permutation.items()} == mapping
342
+
343
+
344
+ def test_bad_number_of_qubits():
345
+ gate = cca.BipartiteSwapNetworkGate(cca.BipartiteGraphType.COMPLETE, 6)
346
+ qubits = cirq.LineQubit.range(6)
347
+ mapping = {q: i for i, q in enumerate(qubits)}
348
+ with pytest.raises(ValueError, match='len'):
349
+ cca.update_mapping(mapping, gate._decompose_(qubits))
350
+ gate.part_size = 5
351
+ with pytest.raises(ValueError, match='qubit_count'):
352
+ gate.permutation()
@@ -27,3 +27,8 @@ def test_acquaintance_device():
27
27
  swap_network = cca.SwapNetworkGate((1, 2, 1))
28
28
  cca.UnconstrainedAcquaintanceDevice.validate_operation(cca.acquaint(*qubits[:2]))
29
29
  cca.UnconstrainedAcquaintanceDevice.validate_operation(swap_network(*qubits))
30
+
31
+
32
+ def test_not_operation():
33
+ with pytest.raises(TypeError):
34
+ _ = cca.get_acquaintance_size(cirq.LineQubit(1))
@@ -48,6 +48,7 @@ def test_executor_explicit():
48
48
  }
49
49
  initial_mapping = {q: i for i, q in enumerate(sorted(qubits))}
50
50
  execution_strategy = cca.GreedyExecutionStrategy(gates, initial_mapping)
51
+ assert execution_strategy.device == cirq.UNCONSTRAINED_DEVICE
51
52
 
52
53
  with pytest.raises(ValueError):
53
54
  executor = cca.StrategyExecutorTransformer(None)
@@ -18,6 +18,7 @@ import pytest
18
18
 
19
19
  import cirq
20
20
  import cirq.contrib.acquaintance as cca
21
+ import cirq.contrib.acquaintance.inspection_utils as inspection_utils
21
22
 
22
23
 
23
24
  @pytest.mark.parametrize('n_qubits, acquaintance_size', product(range(2, 6), range(2, 5)))
@@ -27,3 +28,7 @@ def test_get_logical_acquaintance_opportunities(n_qubits, acquaintance_size):
27
28
  initial_mapping = {q: i for i, q in enumerate(qubits)}
28
29
  opps = cca.get_logical_acquaintance_opportunities(acquaintance_strategy, initial_mapping)
29
30
  assert opps == set(frozenset(s) for s in combinations(range(n_qubits), acquaintance_size))
31
+
32
+
33
+ def test_device():
34
+ assert inspection_utils.LogicalAnnotator({}).device == cirq.UNCONSTRAINED_DEVICE
@@ -60,7 +60,7 @@ class CircularShiftGate(PermutationGate):
60
60
 
61
61
  def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs') -> Tuple[str, ...]:
62
62
  if args.known_qubit_count is None:
63
- return NotImplemented
63
+ return NotImplemented # pragma: no cover
64
64
  direction_symbols = ('╲', '╱') if args.use_unicode_characters else ('\\', '/')
65
65
  wire_symbols = tuple(
66
66
  direction_symbols[int(i >= self.shift)]
@@ -26,7 +26,7 @@ class ComputationalBasisState(cirq.qis.QuantumStateRepresentation):
26
26
  self.basis = initial_state
27
27
 
28
28
  def copy(self, deep_copy_buffers: bool = True) -> 'ComputationalBasisState':
29
- return ComputationalBasisState(self.basis)
29
+ return ComputationalBasisState(self.basis) # pragma: no cover
30
30
 
31
31
  def measure(self, axes: Sequence[int], seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None):
32
32
  return [self.basis[i] for i in axes]
@@ -149,11 +149,13 @@ class ComputationalBasisProductState(cirq.qis.QuantumStateRepresentation):
149
149
  def factor(
150
150
  self, axes: Sequence[int], *, validate=True, atol=1e-07
151
151
  ) -> Tuple['ComputationalBasisProductState', 'ComputationalBasisProductState']:
152
- extracted = ComputationalBasisProductState([self.basis[i] for i in axes])
152
+ extracted = ComputationalBasisProductState(
153
+ [self.basis[i] for i in axes]
154
+ ) # pragma: no cover
153
155
  remainder = ComputationalBasisProductState(
154
156
  [self.basis[i] for i in range(len(self.basis)) if i not in axes]
155
- )
156
- return extracted, remainder
157
+ ) # pragma: no cover
158
+ return extracted, remainder # pragma: no cover
157
159
 
158
160
  def reindex(self, axes: Sequence[int]) -> 'ComputationalBasisProductState':
159
161
  return ComputationalBasisProductState([self.basis[i] for i in axes])
@@ -28,11 +28,11 @@ class UndirectedGraphDeviceEdge(metaclass=abc.ABCMeta):
28
28
 
29
29
  @abc.abstractmethod
30
30
  def duration_of(self, operation: ops.Operation) -> value.Duration:
31
- pass # pragma: no cover
31
+ pass
32
32
 
33
33
  @abc.abstractmethod
34
34
  def validate_operation(self, operation: ops.Operation) -> None:
35
- pass # pragma: no cover
35
+ pass
36
36
 
37
37
 
38
38
  @value.value_equality
@@ -60,7 +60,7 @@ class _UnconstrainedUndirectedGraphDeviceEdge(UndirectedGraphDeviceEdge):
60
60
  return value.Duration(picos=0)
61
61
 
62
62
  def validate_operation(self, operation: ops.Operation) -> None:
63
- pass # pragma: no cover
63
+ pass
64
64
 
65
65
  def __eq__(self, other):
66
66
  return self.__class__ == other.__class__
@@ -46,7 +46,9 @@ def pauli_string_optimized_circuit(
46
46
  def assert_no_multi_qubit_pauli_strings(circuit: circuits.Circuit) -> None:
47
47
  for op in circuit.all_operations():
48
48
  if isinstance(op, PauliStringGateOperation):
49
- assert len(op.pauli_string) == 1, 'Multi qubit Pauli string left over'
49
+ assert (
50
+ len(op.pauli_string) == 1
51
+ ), 'Multi qubit Pauli string left over' # pragma: no cover
50
52
 
51
53
 
52
54
  def merge_equal_strings(string_dag: circuitdag.CircuitDag) -> None:
@@ -12,7 +12,6 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
-
16
15
  import cirq
17
16
  from cirq.contrib.paulistring import CliffordTargetGateset, pauli_string_optimized_circuit
18
17
 
@@ -23,7 +23,7 @@ from cirq.contrib.paulistring import (
23
23
  def _assert_no_multi_qubit_pauli_strings(circuit: cirq.Circuit) -> None:
24
24
  for op in circuit.all_operations():
25
25
  if isinstance(op, cirq.PauliStringGateOperation):
26
- assert len(op.pauli_string) == 1
26
+ assert len(op.pauli_string) == 1 # pragma: no cover
27
27
 
28
28
 
29
29
  def test_move_non_clifford_into_clifford():
@@ -12,7 +12,6 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- # pragma: no cover
16
15
 
17
16
  import errno
18
17
  import os
@@ -30,6 +29,7 @@ def circuit_to_pdf_using_qcircuit_via_tex(
30
29
  qcircuit_kwargs=None,
31
30
  clean_ext=('dvi', 'ps'),
32
31
  documentclass='article',
32
+ prepare_only=False,
33
33
  ):
34
34
  """Compiles the QCircuit-based latex diagram of the given circuit.
35
35
 
@@ -43,6 +43,8 @@ def circuit_to_pdf_using_qcircuit_via_tex(
43
43
  default, latexmk is used with the '-pdfps' flag, which produces
44
44
  intermediary dvi and ps files.
45
45
  documentclass: The documentclass of the latex file.
46
+ prepare_only: If True, only prepare the document, do not generate PDF.
47
+ Used only for testing.
46
48
 
47
49
  Raises:
48
50
  OSError, IOError: If cleanup fails.
@@ -59,10 +61,11 @@ def circuit_to_pdf_using_qcircuit_via_tex(
59
61
  doc.packages.append(Package('qcircuit'))
60
62
  doc.preamble.append(Package('inputenc', options=['utf8']))
61
63
  doc.append(NoEscape(tex))
62
- doc.generate_pdf(filepath, **pdf_kwargs)
63
- for ext in clean_ext:
64
- try:
65
- os.remove(filepath + '.' + ext)
66
- except (OSError, IOError) as e:
67
- if e.errno != errno.ENOENT:
68
- raise
64
+ if not prepare_only: # pragma: nocover
65
+ doc.generate_pdf(filepath, **pdf_kwargs)
66
+ for ext in clean_ext:
67
+ try:
68
+ os.remove(filepath + '.' + ext)
69
+ except (OSError, IOError) as e:
70
+ if e.errno != errno.ENOENT:
71
+ raise
@@ -0,0 +1,21 @@
1
+ # Copyright 2025 The Cirq Developers
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import cirq
16
+ import cirq.contrib.qcircuit.qcircuit_pdf as qcircuit_pdf
17
+
18
+
19
+ def test_qcircuit_pdf_prepare_only():
20
+ circuit = cirq.Circuit(cirq.X(cirq.q(0)), cirq.CZ(cirq.q(0), cirq.q(1)))
21
+ qcircuit_pdf.circuit_to_pdf_using_qcircuit_via_tex(circuit, "/tmp/test_file", prepare_only=True)
@@ -53,7 +53,7 @@ def test_fallback_diagram():
53
53
  self._qubits = qubits
54
54
 
55
55
  def with_qubits(self, *new_qubits):
56
- return MagicOp(*new_qubits)
56
+ return MagicOp(*new_qubits) # pragma: no cover
57
57
 
58
58
  @property
59
59
  def qubits(self):
@@ -4,7 +4,7 @@ https://arxiv.org/abs/1811.12926.
4
4
  """
5
5
 
6
6
  from dataclasses import dataclass
7
- from typing import Any, Callable, Dict, List, Optional, Set, Tuple
7
+ from typing import Callable, Dict, List, Optional, Set, Tuple
8
8
 
9
9
  import networkx as nx
10
10
  import numpy as np
@@ -416,11 +416,6 @@ def execute_circuits(
416
416
  return results
417
417
 
418
418
 
419
- def _get_device_graph(device_or_qubits: Any):
420
- qubits = device_or_qubits if isinstance(device_or_qubits, list) else device_or_qubits.qubits
421
- return ccr.gridqubits_to_graph_device(qubits)
422
-
423
-
424
419
  def calculate_quantum_volume(
425
420
  *,
426
421
  num_qubits: int,
@@ -103,7 +103,7 @@ class MPSSimulator(
103
103
  MPSState args for simulating the Circuit.
104
104
  """
105
105
  if isinstance(initial_state, MPSState):
106
- return initial_state
106
+ return initial_state # pragma: no cover
107
107
 
108
108
  return MPSState(
109
109
  qubits=qubits,
@@ -460,7 +460,7 @@ class _MPSHandler(qis.QuantumStateRepresentation):
460
460
  raise ValueError('Can only handle 1 and 2 qubit operations')
461
461
  return True
462
462
 
463
- def estimation_stats(self):
463
+ def estimation_stats(self): # pragma: no cover
464
464
  """Returns some statistics about the memory usage and quality of the approximation."""
465
465
 
466
466
  num_coefs_used = sum([Mi.data.size for Mi in self._M])
@@ -479,6 +479,11 @@ def test_simulation_state_initializer():
479
479
  )
480
480
  assert s.qubits == (cirq.LineQubit(0),)
481
481
  assert s.classical_data == expected_classical_data
482
+ assert s.estimation_stats() == {
483
+ 'estimated_fidelity': 1.0,
484
+ 'memory_bytes': 16,
485
+ 'num_coefs_used': 2,
486
+ }
482
487
 
483
488
 
484
489
  def test_act_on_gate():
@@ -45,7 +45,9 @@ def create_circuit_and_device():
45
45
 
46
46
  def create_hanging_routing_instance(circuit, device_graph):
47
47
  """Create a test problem instance."""
48
- route_circuit_greedily(circuit, device_graph, max_search_radius=2, random_state=1)
48
+ route_circuit_greedily( # pragma: no cover
49
+ circuit, device_graph, max_search_radius=2, random_state=1
50
+ )
49
51
 
50
52
 
51
53
  def test_router_hanging():
cirq/contrib/svg/svg.py CHANGED
@@ -199,7 +199,7 @@ def tdd_to_svg(
199
199
  # qubits start at far left and their wires shall be blue
200
200
  stroke = QBLUE
201
201
  else:
202
- stroke = 'black'
202
+ stroke = 'black' # pragma: no cover
203
203
  t += f'<line x1="{x1}" x2="{x2}" y1="{y}" y2="{y}" stroke="{stroke}" stroke-width="1" />'
204
204
 
205
205
  for xi, yi1, yi2, _, _ in tdd.vertical_lines:
@@ -4,7 +4,7 @@ import numpy as np
4
4
  import pytest
5
5
 
6
6
  import cirq
7
- from cirq.contrib.svg import circuit_to_svg
7
+ from cirq.contrib.svg import circuit_to_svg, SVGCircuit
8
8
 
9
9
 
10
10
  def test_svg():
@@ -82,7 +82,8 @@ def test_gate_with_less_greater_str(symbol, svg_symbol):
82
82
  return cirq.CircuitDiagramInfo(wire_symbols=[symbol])
83
83
 
84
84
  circuit = cirq.Circuit(CustomGate().on(cirq.LineQubit(0)))
85
- svg = circuit_to_svg(circuit)
85
+ svg_circuit = SVGCircuit(circuit)
86
+ svg = svg_circuit._repr_svg_()
86
87
 
87
88
  _ = IPython.display.SVG(svg)
88
89
  assert svg_symbol in svg
@@ -23,3 +23,9 @@ def test_infinitely_fast():
23
23
  assert cirq.UNCONSTRAINED_DEVICE.duration_of(cirq.X(cirq.NamedQubit('a'))) == cirq.Duration(
24
24
  picos=0
25
25
  )
26
+
27
+
28
+ def test_any_qubit_works():
29
+ moment = cirq.Moment([cirq.X(cirq.LineQubit(987654321))])
30
+ cirq.UNCONSTRAINED_DEVICE.validate_moment(moment)
31
+ cirq.UNCONSTRAINED_DEVICE.validate_circuit(cirq.Circuit(moment))
@@ -285,7 +285,9 @@ class TomographyResult:
285
285
  """
286
286
  return self._density_matrix
287
287
 
288
- def plot(self, axes: Optional[List[plt.Axes]] = None, **plot_kwargs: Any) -> List[plt.Axes]:
288
+ def plot(
289
+ self, axes: Optional[List[plt.Axes]] = None, **plot_kwargs: Any
290
+ ) -> List[plt.Axes]: # pragma: no cover
289
291
  """Plots the real and imaginary parts of the density matrix as two 3D bar plots.
290
292
 
291
293
  Args:
@@ -780,7 +782,7 @@ def _matrix_bar_plot(
780
782
  title: Optional[str] = None,
781
783
  ylim: Tuple[int, int] = (-1, 1),
782
784
  **bar3d_kwargs: Any,
783
- ) -> None:
785
+ ) -> None: # pragma: no cover
784
786
  num_rows, num_cols = mat.shape
785
787
  indices = np.meshgrid(range(num_cols), range(num_rows))
786
788
  x_indices = np.array(indices[1]).flatten()
@@ -541,9 +541,8 @@ def get_grid_interaction_layer_circuit(
541
541
  moments = []
542
542
  for layer in pattern:
543
543
  pairs = sorted(_get_active_pairs(device_graph, layer))
544
- if len(pairs) == 0:
545
- continue
546
- moments += [circuits.Moment(two_qubit_gate.on(*pair) for pair in pairs)]
544
+ if pairs:
545
+ moments += [circuits.Moment(two_qubit_gate.on(*pair) for pair in pairs)]
547
546
  return circuits.Circuit(moments)
548
547
 
549
548
 
@@ -344,10 +344,10 @@ class TensoredConfusionMatrices:
344
344
  try:
345
345
  idx = self.measure_qubits.index((qubit,))
346
346
  except: # pragma: no cover
347
- raise NotImplementedError( # pragma: no cover
348
- "The response matrix must be a tensor product of single-qu" # pragma: no cover
349
- + f"bit response matrices, including that of qubit {qubit}." # pragma: no cover
350
- ) # pragma: no cover
347
+ raise NotImplementedError(
348
+ "The response matrix must be a tensor product of single-qu"
349
+ + f"bit response matrices, including that of qubit {qubit}."
350
+ )
351
351
  cm_all.append(self.confusion_matrices[idx])
352
352
 
353
353
  # get the correction matrices, assuming uncorrelated readout:
@@ -104,6 +104,9 @@ def test_block_diag():
104
104
  ),
105
105
  )
106
106
 
107
+ with pytest.raises(ValueError, match='Blocks must be square'):
108
+ _ = cirq.block_diag(np.array([[1, 2, 3], [3, 4, 5]]))
109
+
107
110
 
108
111
  def test_block_diag_dtype():
109
112
  assert cirq.block_diag().dtype == np.complex128
@@ -39,11 +39,6 @@ def assert_kronecker_factorization_within_tolerance(matrix, g, f1, f2):
39
39
  assert np.allclose(restored, matrix), "Can't factor kronecker product."
40
40
 
41
41
 
42
- def assert_kronecker_factorization_not_within_tolerance(matrix, g, f1, f2):
43
- restored = g * cirq.linalg.combinators.kron(f1, f2)
44
- assert np.any(np.isnan(restored) or not np.allclose(restored, matrix))
45
-
46
-
47
42
  def assert_magic_su2_within_tolerance(mat, a, b):
48
43
  recon = cirq.linalg.combinators.dot(MAGIC_CONJ_T, cirq.linalg.combinators.kron(a, b), MAGIC)
49
44
  assert np.allclose(recon, mat), "Failed to decompose within tolerance."
cirq/linalg/predicates.py CHANGED
@@ -308,7 +308,7 @@ def slice_for_qubits_equal_to(
308
308
  else:
309
309
  if little_endian_qureg_value < 0 and not qid_shape_specified:
310
310
  # Allow negative binary numbers
311
- little_endian_qureg_value &= (1 << len(target_shape)) - 1
311
+ little_endian_qureg_value &= (1 << len(target_shape)) - 1 # pragma: no cover
312
312
  digits = value.big_endian_int_to_digits(little_endian_qureg_value, base=target_shape[::-1])[
313
313
  ::-1
314
314
  ]
cirq/ops/clifford_gate.py CHANGED
@@ -130,16 +130,6 @@ def _pad_tableau(
130
130
  return padded_tableau
131
131
 
132
132
 
133
- def _gate_tableau(num_qubits: int, gate: raw_types.Gate) -> 'cirq.CliffordTableau':
134
- qubits = devices.LineQubit.range(num_qubits)
135
- t = qis.CliffordTableau(num_qubits=num_qubits)
136
- args = sim.CliffordTableauSimulationState(
137
- tableau=t, qubits=qubits, prng=np.random.RandomState()
138
- )
139
- protocols.act_on(gate, args, qubits, allow_decompose=False)
140
- return args.tableau
141
-
142
-
143
133
  class CommonCliffordGateMetaClass(value.ABCMetaImplementAnyOneOf):
144
134
  """A metaclass used to lazy initialize several common Clifford Gate as class attributes."""
145
135
 
@@ -405,7 +395,7 @@ class CliffordGate(raw_types.Gate, CommonCliffordGates):
405
395
 
406
396
  def __pow__(self, exponent: float) -> 'CliffordGate':
407
397
  if exponent != int(exponent):
408
- return NotImplemented
398
+ return NotImplemented # pragma: no cover
409
399
  exponent = int(exponent)
410
400
 
411
401
  if exponent == -1:
@@ -448,7 +438,7 @@ class CliffordGate(raw_types.Gate, CommonCliffordGates):
448
438
  # )
449
439
  # For example: X.then(Z) and Z.then(X) both return same tableau
450
440
  # it is because Clifford tableau ignores the global phase information.
451
- return NotImplemented
441
+ return NotImplemented # pragma: no cover
452
442
 
453
443
  def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
454
444
  return transformers.analytical_decompositions.decompose_clifford_tableau_to_operations(
@@ -477,7 +467,7 @@ class CliffordGate(raw_types.Gate, CommonCliffordGates):
477
467
  # is aimed to fix that.
478
468
  return NotImplemented
479
469
 
480
- return NotImplemented
470
+ return NotImplemented # pragma: no cover
481
471
 
482
472
 
483
473
  @dataclass(frozen=True, init=False, eq=False, repr=False)
@@ -748,7 +738,8 @@ class SingleQubitCliffordGate(CliffordGate):
748
738
  def __pow__(self, exponent: float) -> 'SingleQubitCliffordGate':
749
739
  if int(exponent) == exponent:
750
740
  # The single qubit Clifford gates are a group of size 24
751
- ret_gate = super().__pow__(int(exponent) % 24)
741
+ exp = int(exponent) % 24
742
+ ret_gate = super().__pow__(exp if exp != 23 else -1)
752
743
  return SingleQubitCliffordGate.from_clifford_tableau(ret_gate.clifford_tableau)
753
744
  elif int(2 * exponent) == 2 * exponent:
754
745
  # If exponent = k/2 for integer k, then we compute the k-th power of the square root