cirq-core 1.5.0.dev20250403060241__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.dev20250403060241.dist-info → cirq_core-1.5.0.dev20250403142851.dist-info}/METADATA +1 -1
  103. {cirq_core-1.5.0.dev20250403060241.dist-info → cirq_core-1.5.0.dev20250403142851.dist-info}/RECORD +106 -105
  104. {cirq_core-1.5.0.dev20250403060241.dist-info → cirq_core-1.5.0.dev20250403142851.dist-info}/LICENSE +0 -0
  105. {cirq_core-1.5.0.dev20250403060241.dist-info → cirq_core-1.5.0.dev20250403142851.dist-info}/WHEEL +0 -0
  106. {cirq_core-1.5.0.dev20250403060241.dist-info → cirq_core-1.5.0.dev20250403142851.dist-info}/top_level.txt +0 -0
@@ -104,7 +104,7 @@ def test_is_measurement():
104
104
 
105
105
  @property
106
106
  def qubits(self):
107
- return cirq.LineQubit.range(2)
107
+ return cirq.LineQubit.range(2) # pragma: no cover
108
108
 
109
109
  assert not cirq.is_measurement(NotImplementedOperation())
110
110
 
@@ -123,27 +123,27 @@ def test_measurement_without_key():
123
123
  def test_non_measurement_with_key():
124
124
  class NonMeasurementGate(cirq.Gate):
125
125
  def _is_measurement_(self):
126
- return False
126
+ return False # pragma: no cover
127
127
 
128
128
  def _decompose_(self, qubits):
129
129
  # Decompose should not be called by `is_measurement`
130
- assert False
130
+ assert False # pragma: no cover
131
131
 
132
132
  def _measurement_key_name_(self):
133
133
  # `measurement_key_name`` should not be called by `is_measurement`
134
- assert False
134
+ assert False # pragma: no cover
135
135
 
136
136
  def _measurement_key_names_(self):
137
137
  # `measurement_key_names`` should not be called by `is_measurement`
138
- assert False
138
+ assert False # pragma: no cover
139
139
 
140
140
  def _measurement_key_obj_(self):
141
141
  # `measurement_key_obj`` should not be called by `is_measurement`
142
- assert False
142
+ assert False # pragma: no cover
143
143
 
144
144
  def _measurement_key_objs_(self):
145
145
  # `measurement_key_objs`` should not be called by `is_measurement`
146
- assert False
146
+ assert False # pragma: no cover
147
147
 
148
148
  def num_qubits(self) -> int:
149
149
  return 2 # pragma: no cover
@@ -286,7 +286,7 @@ def test_unitary_from_apply_unitary():
286
286
 
287
287
  class UnknownType:
288
288
  def _apply_unitary_(self, args):
289
- assert False
289
+ assert False # pragma: no cover
290
290
 
291
291
  class ApplyGateNotUnitary(cirq.Gate):
292
292
  def num_qubits(self):
cirq/qis/channels_test.py CHANGED
@@ -51,15 +51,6 @@ def compute_choi(channel: cirq.SupportsKraus) -> np.ndarray:
51
51
  return c
52
52
 
53
53
 
54
- def compute_superoperator(channel: cirq.SupportsKraus) -> np.ndarray:
55
- ks = cirq.kraus(channel)
56
- d_out, d_in = ks[0].shape
57
- m = np.zeros((d_out * d_out, d_in * d_in), dtype=np.complex128)
58
- for k, e_in in enumerate(generate_standard_operator_basis(d_in, d_in)):
59
- m[:, k] = np.reshape(apply_channel(channel, e_in), d_out * d_out)
60
- return m
61
-
62
-
63
54
  @pytest.mark.parametrize(
64
55
  'kraus_operators, expected_choi',
65
56
  (
cirq/qis/measures.py CHANGED
@@ -247,7 +247,8 @@ def _fidelity_state_vectors_or_density_matrices(state1: np.ndarray, state2: np.n
247
247
  eigs = linalg.eigvalsh(state1_sqrt @ state2 @ state1_sqrt)
248
248
  trace = np.sum(np.sqrt(np.abs(eigs)))
249
249
  return trace**2
250
- raise ValueError(
250
+ # matrix is reshaped before this point
251
+ raise ValueError( # pragma: no cover
251
252
  'The given arrays must be one- or two-dimensional. '
252
253
  f'Got shapes {state1.shape} and {state2.shape}.'
253
254
  )
cirq/qis/measures_test.py CHANGED
@@ -34,6 +34,13 @@ def test_fidelity_symmetric():
34
34
  )
35
35
 
36
36
 
37
+ def test_bad_fidelity():
38
+ arr = np.asarray([[[1j, 0], [0, 0]], [[0, 0], [0, 0]]])
39
+ assert arr.ndim > 2
40
+ assert arr.dtype.kind == 'c'
41
+ _ = cirq.fidelity(arr, arr)
42
+
43
+
37
44
  def test_fidelity_between_zero_and_one():
38
45
  assert 0 <= cirq.fidelity(VEC1, VEC2) <= 1
39
46
  assert 0 <= cirq.fidelity(VEC1, MAT1) <= 1
cirq/qis/states.py CHANGED
@@ -845,7 +845,7 @@ def _qudit_values_to_state_tensor(
845
845
  )
846
846
 
847
847
  if state_vector.dtype.kind[0] not in '?bBiu':
848
- raise ValueError(
848
+ raise ValueError( # pragma: no cover
849
849
  f'Expected a bool or int entry for each qudit in '
850
850
  f'`state`, because len(state) == len(qid_shape), '
851
851
  f'but got dtype {state_vector.dtype}.'
@@ -90,7 +90,8 @@ class CliffordSimulator(
90
90
  StabilizerChFormSimulationState for the circuit.
91
91
  """
92
92
  if isinstance(initial_state, clifford.StabilizerChFormSimulationState):
93
- return initial_state
93
+ # Instances of SimulationStateBase usually returned before this point
94
+ return initial_state # pragma: no cover
94
95
 
95
96
  return clifford.StabilizerChFormSimulationState(
96
97
  prng=self._prng,
@@ -1,4 +1,16 @@
1
- # pylint: disable=wrong-or-nonexistent-copyright-notice
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.
2
14
  import itertools
3
15
 
4
16
  import numpy as np
@@ -91,12 +103,17 @@ def test_simulate_initial_state():
91
103
  circuit.append(cirq.X(q1))
92
104
  circuit.append(cirq.measure(q0, q1))
93
105
 
94
- result = simulator.simulate(circuit, initial_state=1)
95
- expected_state = np.zeros(shape=(2, 2))
96
- expected_state[b0][1 - b1] = 1.0
97
- np.testing.assert_almost_equal(
98
- result.final_state.to_numpy(), np.reshape(expected_state, 4)
99
- )
106
+ for initial_state in [
107
+ cirq.StabilizerChFormSimulationState(
108
+ qubits=cirq.LineQubit.range(2), initial_state=1
109
+ )
110
+ ]:
111
+ result = simulator.simulate(circuit, initial_state=initial_state)
112
+ expected_state = np.zeros(shape=(2, 2))
113
+ expected_state[b0][1 - b1] = 1.0
114
+ np.testing.assert_almost_equal(
115
+ result.final_state.to_numpy(), np.reshape(expected_state, 4)
116
+ )
100
117
 
101
118
 
102
119
  def test_simulation_state():
@@ -208,6 +225,8 @@ def test_clifford_state_initial_state():
208
225
  state = cirq.CliffordState(qubit_map={q0: 0}, initial_state=1)
209
226
  np.testing.assert_allclose(state.state_vector(), [0, 1])
210
227
 
228
+ assert state.copy() == state
229
+
211
230
 
212
231
  def test_clifford_trial_result_repr():
213
232
  q0 = cirq.LineQubit(0)
@@ -476,10 +495,10 @@ def test_is_supported_operation():
476
495
  raise NotImplementedError()
477
496
 
478
497
  def _has_unitary_(self):
479
- return True
498
+ return True # pragma: no cover
480
499
 
481
500
  def _unitary_(self):
482
- assert False
501
+ assert False # pragma: no cover
483
502
 
484
503
  q1, q2 = cirq.LineQubit.range(2)
485
504
  assert cirq.CliffordSimulator.is_supported_operation(cirq.X(q1))
@@ -548,6 +567,10 @@ def test_valid_apply_measurement():
548
567
  q0 = cirq.LineQubit(0)
549
568
  state = cirq.CliffordState(qubit_map={q0: 0}, initial_state=1)
550
569
  measurements = {}
570
+ _ = state.apply_measurement(
571
+ cirq.measure(q0), measurements, np.random.RandomState(), collapse_state_vector=False
572
+ )
573
+ assert measurements == {'q(0)': [1]}
551
574
  state.apply_measurement(cirq.measure(q0), measurements, np.random.RandomState())
552
575
  assert measurements == {'q(0)': [1]}
553
576
 
@@ -168,7 +168,8 @@ class DensityMatrixSimulator(
168
168
  DensityMatrixSimulationState for the circuit.
169
169
  """
170
170
  if isinstance(initial_state, density_matrix_simulation_state.DensityMatrixSimulationState):
171
- return initial_state
171
+ # Instances of SimulationStateBase usually returned before this point
172
+ return initial_state # pragma: no cover
172
173
 
173
174
  return density_matrix_simulation_state.DensityMatrixSimulationState(
174
175
  qubits=qubits,
@@ -13,7 +13,7 @@
13
13
  # limitations under the License.
14
14
  import itertools
15
15
  import random
16
- from typing import Type
16
+ from typing import Type, Union
17
17
  from unittest import mock
18
18
 
19
19
  import numpy as np
@@ -584,7 +584,15 @@ def test_simulate_qudit_increments(dtype: Type[np.complexfloating], split: bool)
584
584
 
585
585
  @pytest.mark.parametrize('dtype', [np.complex64, np.complex128])
586
586
  @pytest.mark.parametrize('split', [True, False])
587
- def test_simulate_initial_state(dtype: Type[np.complexfloating], split: bool):
587
+ @pytest.mark.parametrize(
588
+ 'initial_state',
589
+ [1, cirq.DensityMatrixSimulationState(initial_state=1, qubits=cirq.LineQubit.range(2))],
590
+ )
591
+ def test_simulate_initial_state(
592
+ dtype: Type[np.complexfloating],
593
+ split: bool,
594
+ initial_state: Union[int, cirq.DensityMatrixSimulationState],
595
+ ):
588
596
  q0, q1 = cirq.LineQubit.range(2)
589
597
  simulator = cirq.DensityMatrixSimulator(dtype=dtype, split_untangled_states=split)
590
598
  for b0 in [0, 1]:
@@ -336,7 +336,7 @@ def strat_act_on_from_apply_decompose(
336
336
  curr_ancilla = tuple(q for q in operation.qubits if q not in args.qubits)
337
337
  args = args.add_qubits(curr_ancilla)
338
338
  if args is NotImplemented:
339
- return NotImplemented
339
+ return NotImplemented # pragma: no cover
340
340
  all_ancilla.update(curr_ancilla)
341
341
  protocols.act_on(operation, args)
342
342
  args = args.remove_qubits(tuple(all_ancilla))
@@ -66,7 +66,7 @@ class DelegatingAncillaZ(cirq.Gate):
66
66
 
67
67
  class Composite(cirq.Gate):
68
68
  def num_qubits(self) -> int:
69
- return 1
69
+ return 1 # pragma: no cover
70
70
 
71
71
  def _decompose_(self, qubits):
72
72
  yield cirq.X(*qubits)
@@ -50,7 +50,7 @@ class FakeStepResult(cirq.StepResult):
50
50
  self._final_state = final_state
51
51
 
52
52
  def _simulator_state(self):
53
- return self._final_state
53
+ return self._final_state # pragma: no cover
54
54
 
55
55
  def state_vector(self):
56
56
  pass
@@ -171,7 +171,8 @@ class Simulator(
171
171
  StateVectorSimulationState for the circuit.
172
172
  """
173
173
  if isinstance(initial_state, state_vector_simulation_state.StateVectorSimulationState):
174
- return initial_state
174
+ # Instances of SimulationStateBase usually returned before this point
175
+ return initial_state # pragma: no cover
175
176
 
176
177
  return state_vector_simulation_state.StateVectorSimulationState(
177
178
  qubits=qubits,
@@ -13,7 +13,7 @@
13
13
  # limitations under the License.
14
14
  import itertools
15
15
  import random
16
- from typing import Type
16
+ from typing import Type, Union
17
17
  from unittest import mock
18
18
 
19
19
  import numpy as np
@@ -446,7 +446,15 @@ def test_simulate_bit_flips(dtype: Type[np.complexfloating], split: bool):
446
446
 
447
447
  @pytest.mark.parametrize('dtype', [np.complex64, np.complex128])
448
448
  @pytest.mark.parametrize('split', [True, False])
449
- def test_simulate_initial_state(dtype: Type[np.complexfloating], split: bool):
449
+ @pytest.mark.parametrize(
450
+ 'initial_state',
451
+ [1, cirq.StateVectorSimulationState(initial_state=1, qubits=cirq.LineQubit.range(2))],
452
+ )
453
+ def test_simulate_initial_state(
454
+ dtype: Type[np.complexfloating],
455
+ split: bool,
456
+ initial_state: Union[int, cirq.StateVectorSimulationState],
457
+ ):
450
458
  q0, q1 = cirq.LineQubit.range(2)
451
459
  simulator = cirq.Simulator(dtype=dtype, split_untangled_states=split)
452
460
  for b0 in [0, 1]:
@@ -63,7 +63,7 @@ def test_shallow_copy_buffers():
63
63
  def test_decomposed_fallback():
64
64
  class Composite(cirq.Gate):
65
65
  def num_qubits(self) -> int:
66
- return 1
66
+ return 1 # pragma: no cover
67
67
 
68
68
  def _decompose_(self, qubits):
69
69
  yield cirq.X(*qubits)
cirq/study/resolver.py CHANGED
@@ -44,10 +44,6 @@ _NOT_FOUND = object()
44
44
  _RECURSION_FLAG = object()
45
45
 
46
46
 
47
- def _is_param_resolver_or_similar_type(obj: Any):
48
- return obj is None or isinstance(obj, (ParamResolver, dict))
49
-
50
-
51
47
  class ParamResolver:
52
48
  """Resolves parameters to actual values.
53
49
 
@@ -84,7 +84,7 @@ def _assert_consistent_resolution(v, resolved):
84
84
 
85
85
  # note: super().subs() doesn't resolve based on the param_dict properly
86
86
  # for some reason, that's why a delegate (self.symbol) is used instead
87
- def subs(self, *args, **kwargs):
87
+ def subs(self, *args, **kwargs): # pragma: no cover
88
88
  self.called = True
89
89
  return self.symbol.subs(*args, **kwargs)
90
90
 
@@ -93,6 +93,7 @@ def _assert_consistent_resolution(v, resolved):
93
93
  # symbol based resolution
94
94
  s = SubsAwareSymbol('a')
95
95
  assert r.value_of(s) == resolved, f"expected {resolved}, got {r.value_of(s)}"
96
+ assert r[s] == resolved, f"expected {resolved}, got {r.value_of(s)}"
96
97
  assert not s.called, f"For pass-through type {type(v)} sympy.subs shouldn't have been called."
97
98
  assert isinstance(
98
99
  r.value_of(s), type(resolved)
@@ -183,6 +184,14 @@ def test_recursive_evaluation():
183
184
  assert sympy.Eq(r.value_of(e), 0)
184
185
 
185
186
 
187
+ def test_resolution_of_unknown_formulas():
188
+ a = sympy.Symbol('a')
189
+ b = sympy.Symbol('b')
190
+
191
+ r = cirq.ParamResolver({a: b - 2})
192
+ assert r.value_of(sympy.sin(a), recursive=False) == sympy.sin(b - 2)
193
+
194
+
186
195
  def test_unbound_recursion_halted():
187
196
  a = sympy.Symbol('a')
188
197
  b = sympy.Symbol('b')
cirq/study/sweeps_test.py CHANGED
@@ -111,7 +111,9 @@ def test_zip_longest_compatibility():
111
111
 
112
112
 
113
113
  def test_empty_zip():
114
+ assert len(cirq.Zip()) == 0
114
115
  assert len(cirq.ZipLongest()) == 0
116
+ assert str(cirq.Zip()) == 'Zip()'
115
117
  with pytest.raises(ValueError, match='non-empty'):
116
118
  _ = cirq.ZipLongest(cirq.Points('e', []), cirq.Points('a', [1, 2, 3]))
117
119
 
@@ -142,10 +144,26 @@ def test_product():
142
144
  assert _values(sweep, 'a') == [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
143
145
  assert _values(sweep, 'b') == [4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7]
144
146
 
147
+ sweep = cirq.Points('a', [1, 2]) * (cirq.Points('b', [3, 4]) * cirq.Points('c', [5, 6]))
148
+ assert len(sweep) == 8
149
+ assert _values(sweep, 'a') == [1, 1, 1, 1, 2, 2, 2, 2]
150
+ assert _values(sweep, 'b') == [3, 3, 4, 4, 3, 3, 4, 4]
151
+ assert _values(sweep, 'c') == [5, 6, 5, 6, 5, 6, 5, 6]
152
+
153
+
154
+ def test_zip_addition():
155
+ zip_sweep = cirq.Zip(cirq.Points('a', [1, 2]), cirq.Points('b', [3, 4]))
156
+ zip_sweep2 = cirq.Points('c', [5, 6]) + zip_sweep
157
+ assert len(zip_sweep2) == 2
158
+ assert _values(zip_sweep2, 'a') == [1, 2]
159
+ assert _values(zip_sweep2, 'b') == [3, 4]
160
+ assert _values(zip_sweep2, 'c') == [5, 6]
161
+
145
162
 
146
163
  def test_empty_product():
147
164
  sweep = cirq.Product()
148
165
  assert len(sweep) == len(list(sweep)) == 1
166
+ assert str(sweep) == 'Product()'
149
167
 
150
168
 
151
169
  def test_slice_access_error():
@@ -333,7 +333,7 @@ def test_assert_has_consistent_apply_unitary():
333
333
  return args.available_buffer
334
334
 
335
335
  def _unitary_(self):
336
- return np.eye(2)
336
+ return np.eye(2) # pragma: no cover
337
337
 
338
338
  def _num_qubits_(self):
339
339
  return 1
@@ -366,7 +366,7 @@ def test_assert_has_consistent_apply_unitary():
366
366
  return args.available_buffer
367
367
 
368
368
  def _unitary_(self):
369
- return np.array([[0, 1], [1, 0]])
369
+ return np.array([[0, 1], [1, 0]]) # pragma: no cover
370
370
 
371
371
  def _num_qubits_(self):
372
372
  return 1
@@ -483,7 +483,7 @@ def test_assert_has_consistent_qid_shape():
483
483
 
484
484
  class ConsistentOp(cirq.Operation):
485
485
  def with_qubits(self, *qubits):
486
- raise NotImplementedError # pragma: no cover
486
+ raise NotImplementedError
487
487
 
488
488
  @property
489
489
  def qubits(self):
@@ -500,7 +500,7 @@ def test_assert_has_consistent_qid_shape():
500
500
  # the three methods before finding an inconsistency and throwing an error.
501
501
  class InconsistentOp1(cirq.Operation):
502
502
  def with_qubits(self, *qubits):
503
- raise NotImplementedError # pragma: no cover
503
+ raise NotImplementedError
504
504
 
505
505
  @property
506
506
  def qubits(self):
@@ -514,7 +514,7 @@ def test_assert_has_consistent_qid_shape():
514
514
 
515
515
  class InconsistentOp2(cirq.Operation):
516
516
  def with_qubits(self, *qubits):
517
- raise NotImplementedError # pragma: no cover
517
+ raise NotImplementedError
518
518
 
519
519
  @property
520
520
  def qubits(self):
@@ -528,7 +528,7 @@ def test_assert_has_consistent_qid_shape():
528
528
 
529
529
  class InconsistentOp3(cirq.Operation):
530
530
  def with_qubits(self, *qubits):
531
- raise NotImplementedError # pragma: no cover
531
+ raise NotImplementedError
532
532
 
533
533
  @property
534
534
  def qubits(self):
@@ -32,7 +32,7 @@ class GoodGateExplicitPauliExpansion(cirq.testing.SingleQubitGate):
32
32
 
33
33
  class GoodGateNoPauliExpansion(cirq.Gate):
34
34
  def num_qubits(self) -> int:
35
- return 4
35
+ return 4 # pragma: no cover
36
36
 
37
37
 
38
38
  class GoodGateNoUnitary(cirq.testing.SingleQubitGate):
@@ -47,7 +47,7 @@ def assert_qasm_is_consistent_with_unitary(val: Any):
47
47
  qid_shape = protocols.qid_shape(val)
48
48
  remaining_shape = list(qid_shape)
49
49
  controls = getattr(val, 'control_qubits', None)
50
- if controls is not None:
50
+ if controls is not None: # pragma: no cover
51
51
  for i, q in zip(reversed(range(len(controls))), reversed(controls)):
52
52
  if q is not None:
53
53
  remaining_shape.pop(i)
@@ -141,7 +141,7 @@ class _ClassUnknownToSubjects:
141
141
  return not self == other
142
142
 
143
143
  def __hash__(self):
144
- return hash(_ClassUnknownToSubjects)
144
+ return hash(_ClassUnknownToSubjects) # pragma: no cover
145
145
 
146
146
 
147
147
  class _TestsForNotImplemented:
@@ -118,7 +118,7 @@ def test_fails_when_forgot_type_check():
118
118
  return not self == other
119
119
 
120
120
  def __hash__(self):
121
- return hash(self.x)
121
+ return hash(self.x) # pragma: no cover
122
122
 
123
123
  with pytest.raises(AttributeError, match="has no attribute 'x'"):
124
124
  eq.add_equality_group(NoTypeCheckEqualImplementation())
@@ -194,14 +194,14 @@ def test_fails_when_ne_is_inconsistent_due_to_not_implemented():
194
194
 
195
195
  def __eq__(self, other):
196
196
  if not isinstance(other, type(self)):
197
- return NotImplemented
197
+ return NotImplemented # pragma: no cover
198
198
  return self.x == other.x
199
199
 
200
200
  def __ne__(self, other):
201
201
  return NotImplemented
202
202
 
203
203
  def __hash__(self):
204
- return hash(self.x)
204
+ return hash(self.x) # pragma: no cover
205
205
 
206
206
  with pytest.raises(AssertionError, match='inconsistent'):
207
207
  eq.make_equality_group(InconsistentNeImplementation)
@@ -216,7 +216,7 @@ def test_fails_when_not_reflexive():
216
216
 
217
217
  def __eq__(self, other):
218
218
  if other is not self:
219
- return NotImplemented
219
+ return NotImplemented # pragma: no cover
220
220
  return False
221
221
 
222
222
  def __ne__(self, other):
@@ -235,7 +235,7 @@ def test_fails_when_not_commutative():
235
235
 
236
236
  def __eq__(self, other):
237
237
  if not isinstance(other, type(self)):
238
- return NotImplemented
238
+ return NotImplemented # pragma: no cover
239
239
  return self.x <= other.x
240
240
 
241
241
  def __ne__(self, other):
@@ -78,3 +78,8 @@ def test_three_qubit_gate_validate():
78
78
  g.validate_args([a, b])
79
79
  with pytest.raises(ValueError):
80
80
  g.validate_args([a, b, c, d])
81
+
82
+
83
+ def test_does_not_support_serialization_gate():
84
+ g = cirq.testing.DoesNotSupportSerializationGate(n_qubits=4)
85
+ assert g.num_qubits() == 4
@@ -426,7 +426,7 @@ def _single_qubit_matrices_with_sqrt_iswap(
426
426
  for can_decompose, decomposer in decomposers:
427
427
  if can_decompose(kak.interaction_coefficients, weyl_tol=atol / 10):
428
428
  return decomposer(kak, atol)
429
- assert False, 'The final can_decompose should always returns True'
429
+ assert False, 'The final can_decompose should always returns True' # pragma: no cover
430
430
 
431
431
 
432
432
  def _in_0_region(
@@ -31,7 +31,7 @@ class ExampleSweepGate(cirq.testing.TwoQubitGate):
31
31
  unitary = cirq.unitary(cirq.CZ)
32
32
 
33
33
  def _unitary_(self) -> np.ndarray:
34
- return self.unitary
34
+ return self.unitary # pragma: no cover
35
35
 
36
36
 
37
37
  _EXAMPLE_TARGET = ExampleGate()
@@ -169,7 +169,7 @@ def map_clean_and_borrowable_qubits(
169
169
  # one from the original system qubits.
170
170
  allocated_map[q] = qm.qborrow(1)[0]
171
171
  else:
172
- assert False, f"Unknown temporary qubit type {q}"
172
+ assert False, f"Unknown temporary qubit type {q}" # pragma: no cover
173
173
 
174
174
  # Return the transformed operation / decomposed op-tree.
175
175
  return op.transform_qubits({**allocated_map, **trivial_map})
@@ -257,6 +257,14 @@ def test_transformer_stats_logger_show_levels(capfd):
257
257
  assert all(line not in out for line in [info_line, debug_line, warning_line])
258
258
 
259
259
 
260
+ def test_noop_logger():
261
+ logger = cirq.transformers.transformer_api.NoOpTransformerLogger()
262
+ logger.register_initial(cirq.Circuit(), "test")
263
+ logger.log("stuff")
264
+ logger.register_final(cirq.Circuit(), "test")
265
+ logger.show()
266
+
267
+
260
268
  def test_transformer_stats_logger_linear_and_nested(capfd):
261
269
  q = cirq.LineQubit.range(2)
262
270
  circuit = cirq.Circuit(cirq.H.on_each(*q), cirq.CNOT(*q))
@@ -586,7 +586,7 @@ def test_merge_moments_empty_moment_as_intermediate_step():
586
586
 
587
587
  def test_merge_moments_empty_circuit():
588
588
  def fail_if_called_func(*_):
589
- assert False
589
+ assert False # pragma: no cover
590
590
 
591
591
  c = cirq.Circuit()
592
592
  assert cirq.merge_moments(c, fail_if_called_func) is c
@@ -601,7 +601,7 @@ def test_merge_operations_raises():
601
601
 
602
602
  def test_merge_operations_nothing_to_merge():
603
603
  def fail_if_called_func(*_):
604
- assert False
604
+ assert False # pragma: no cover
605
605
 
606
606
  # Empty Circuit.
607
607
  c = cirq.Circuit()
cirq/value/condition.py CHANGED
@@ -239,7 +239,7 @@ class BitMaskKeyCondition(Condition):
239
239
 
240
240
  @property
241
241
  def qasm(self):
242
- raise NotImplementedError() # pragma: no cover
242
+ raise NotImplementedError()
243
243
 
244
244
 
245
245
  @dataclasses.dataclass(frozen=True)
cirq/value/duration.py CHANGED
@@ -165,7 +165,7 @@ class Duration:
165
165
  if other_duration is not None:
166
166
  return self.total_picos() / other_duration.total_picos()
167
167
 
168
- return NotImplemented
168
+ return NotImplemented # pragma: no cover
169
169
 
170
170
  def __eq__(self, other):
171
171
  other = _attempt_duration_like_to_duration(other)
@@ -42,6 +42,11 @@ def test_periodic_value_approx_eq_basic():
42
42
  assert not cirq.approx_eq(cirq.PeriodicValue(1.0, 2.0), cirq.PeriodicValue(1.0, 2.2), atol=0.1)
43
43
  assert not cirq.approx_eq(cirq.PeriodicValue(1.0, 2.0), cirq.PeriodicValue(1.2, 2.2), atol=0.3)
44
44
  assert not cirq.approx_eq(cirq.PeriodicValue(1.0, 2.0), cirq.PeriodicValue(1.2, 2.2), atol=0.1)
45
+ assert cirq.approx_eq(
46
+ cirq.PeriodicValue(sympy.Symbol('t'), 2.0),
47
+ cirq.PeriodicValue(sympy.Symbol('t'), 2.0),
48
+ atol=0.1,
49
+ )
45
50
 
46
51
 
47
52
  def test_periodic_value_approx_eq_normalized():
@@ -94,7 +94,7 @@ class UnhashableD:
94
94
  self.x = x
95
95
 
96
96
  def _value_equality_values_(self):
97
- return self.x
97
+ return self.x # pragma: no cover
98
98
 
99
99
 
100
100
  class UnhashableCa(UnhashableC):
cirq/vis/heatmap_test.py CHANGED
@@ -245,7 +245,7 @@ def test_non_float_values(ax, format_string):
245
245
  for artist in ax.get_children():
246
246
  if isinstance(artist, mpl.text.Text):
247
247
  col, row = artist.get_position()
248
- if (row, col) in test_value_map:
248
+ if (row, col) in test_value_map: # pragma: no cover
249
249
  foo = test_value_map[(row, col)]
250
250
  actual_text = artist.get_text()
251
251
  expected_text = format(foo, format_string)
@@ -149,7 +149,8 @@ def _fix_precision(val: Union[value.Scalar, sympy.Expr], precision) -> Union[int
149
149
  raise ValueError(f'Cannot convert {val} to fixed precision in observable settings')
150
150
  if isinstance(val, (complex, numbers.Complex)):
151
151
  return int(val.real * precision), int(val.imag * precision)
152
- return int(val * precision)
152
+ # Pretty much all numbers are instances of numbers.Complex
153
+ return int(val * precision) # pragma: no cover
153
154
 
154
155
 
155
156
  def _hashable_param(