cirq-core 1.6.0.dev20250515174529__py3-none-any.whl → 1.6.0.dev20250516154249__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.
- cirq/_compat.py +3 -0
- cirq/_doc.py +2 -0
- cirq/_import.py +2 -0
- cirq/_import_test.py +4 -2
- cirq/_version.py +1 -1
- cirq/_version_test.py +1 -1
- cirq/circuits/_block_diagram_drawer.py +2 -0
- cirq/circuits/_block_diagram_drawer_test.py +2 -0
- cirq/circuits/_box_drawing_character_data.py +2 -0
- cirq/circuits/_box_drawing_character_data_test.py +2 -0
- cirq/circuits/_bucket_priority_queue.py +2 -0
- cirq/circuits/_bucket_priority_queue_test.py +2 -0
- cirq/circuits/circuit_operation_test.py +3 -0
- cirq/circuits/circuit_test.py +2 -0
- cirq/circuits/frozen_circuit_test.py +2 -0
- cirq/circuits/insert_strategy_test.py +2 -0
- cirq/circuits/moment_test.py +2 -0
- cirq/circuits/optimization_pass_test.py +2 -0
- cirq/circuits/qasm_output_test.py +3 -0
- cirq/circuits/text_diagram_drawer_test.py +2 -0
- cirq/contrib/acquaintance/bipartite_test.py +2 -0
- cirq/contrib/acquaintance/devices_test.py +2 -0
- cirq/contrib/acquaintance/executor_test.py +2 -0
- cirq/contrib/acquaintance/inspection_utils_test.py +2 -0
- cirq/contrib/acquaintance/mutation_utils_test.py +2 -0
- cirq/contrib/acquaintance/optimizers_test.py +3 -0
- cirq/contrib/acquaintance/permutation_test.py +2 -0
- cirq/contrib/acquaintance/shift_swap_network_test.py +2 -0
- cirq/contrib/acquaintance/shift_test.py +2 -0
- cirq/contrib/acquaintance/strategies/cubic_test.py +2 -0
- cirq/contrib/acquaintance/strategies/quartic_paired_test.py +2 -0
- cirq/contrib/acquaintance/testing.py +2 -0
- cirq/contrib/acquaintance/topological_sort_test.py +2 -0
- cirq/contrib/bayesian_network/bayesian_network_gate_test.py +3 -0
- cirq/contrib/circuitdag/circuit_dag_test.py +2 -0
- cirq/contrib/graph_device/graph_device_test.py +2 -0
- cirq/contrib/graph_device/hypergraph_test.py +2 -0
- cirq/contrib/graph_device/uniform_graph_device.py +2 -0
- cirq/contrib/graph_device/uniform_graph_device_test.py +2 -0
- cirq/contrib/hacks/disable_validation.py +2 -0
- cirq/contrib/hacks/disable_validation_test.py +2 -0
- cirq/contrib/json.py +2 -0
- cirq/contrib/json_test.py +3 -0
- cirq/contrib/noise_models/noise_models_test.py +2 -0
- cirq/contrib/paulistring/clifford_optimize.py +2 -0
- cirq/contrib/paulistring/clifford_optimize_test.py +2 -0
- cirq/contrib/paulistring/clifford_target_gateset_test.py +2 -0
- cirq/contrib/paulistring/optimize.py +2 -0
- cirq/contrib/paulistring/optimize_test.py +2 -0
- cirq/contrib/paulistring/pauli_string_dag.py +2 -0
- cirq/contrib/paulistring/pauli_string_dag_test.py +2 -0
- cirq/contrib/paulistring/pauli_string_optimize.py +5 -1
- cirq/contrib/paulistring/pauli_string_optimize_test.py +2 -0
- cirq/contrib/paulistring/recombine.py +2 -0
- cirq/contrib/paulistring/recombine_test.py +2 -0
- cirq/contrib/paulistring/separate.py +2 -0
- cirq/contrib/paulistring/separate_test.py +2 -0
- cirq/contrib/qasm_import/_lexer.py +2 -0
- cirq/contrib/qasm_import/_lexer_test.py +2 -0
- cirq/contrib/qasm_import/_parser.py +2 -0
- cirq/contrib/qasm_import/_parser_test.py +2 -0
- cirq/contrib/qasm_import/exception.py +2 -0
- cirq/contrib/qasm_import/qasm.py +6 -2
- cirq/contrib/qasm_import/qasm_test.py +3 -0
- cirq/contrib/qcircuit/qcircuit_diagram_info.py +2 -0
- cirq/contrib/qcircuit/qcircuit_diagram_info_test.py +2 -0
- cirq/contrib/qcircuit/qcircuit_pdf.py +7 -2
- cirq/contrib/qcircuit/qcircuit_pdf_test.py +2 -0
- cirq/contrib/qcircuit/qcircuit_test.py +2 -0
- cirq/contrib/quantum_volume/quantum_volume.py +2 -0
- cirq/contrib/quantum_volume/quantum_volume_test.py +2 -0
- cirq/contrib/quimb/density_matrix_test.py +3 -0
- cirq/contrib/quimb/grid_circuits.py +2 -0
- cirq/contrib/quimb/grid_circuits_test.py +3 -0
- cirq/contrib/quimb/mps_simulator_test.py +3 -0
- cirq/contrib/quimb/state_vector_test.py +3 -0
- cirq/contrib/quirk/export_to_quirk.py +2 -0
- cirq/contrib/quirk/export_to_quirk_test.py +2 -0
- cirq/contrib/quirk/linearize_circuit.py +2 -0
- cirq/contrib/routing/device.py +2 -0
- cirq/contrib/routing/device_test.py +2 -0
- cirq/contrib/routing/greedy_test.py +2 -0
- cirq/contrib/routing/initialization_test.py +2 -0
- cirq/contrib/routing/router.py +4 -2
- cirq/contrib/routing/router_test.py +2 -0
- cirq/contrib/routing/swap_network_test.py +2 -0
- cirq/contrib/routing/utils_test.py +3 -0
- cirq/contrib/shuffle_circuits/shuffle_circuits_with_readout_benchmarking.py +4 -2
- cirq/contrib/shuffle_circuits/shuffle_circuits_with_readout_benchmarking_test.py +3 -0
- cirq/contrib/svg/svg_test.py +3 -0
- cirq/devices/device_test.py +3 -0
- cirq/devices/grid_device_metadata_test.py +3 -0
- cirq/interop/quirk/cells/parse_test.py +10 -10
- cirq/ops/pauli_string_phasor.py +1 -1
- cirq/testing/equals_tester_test.py +19 -17
- cirq/value/random_state_test.py +3 -3
- cirq/value/timestamp.py +4 -0
- cirq/value/timestamp_test.py +10 -10
- cirq/vis/density_matrix_test.py +17 -17
- cirq/work/collector_test.py +13 -10
- cirq/work/observable_measurement.py +14 -2
- cirq/work/observable_measurement_data.py +3 -3
- cirq/work/observable_measurement_test.py +43 -27
- cirq/work/observable_settings.py +2 -12
- cirq/work/observable_settings_test.py +7 -7
- cirq/work/pauli_sum_collector_test.py +7 -9
- cirq/work/sampler_test.py +25 -22
- {cirq_core-1.6.0.dev20250515174529.dist-info → cirq_core-1.6.0.dev20250516154249.dist-info}/METADATA +1 -1
- {cirq_core-1.6.0.dev20250515174529.dist-info → cirq_core-1.6.0.dev20250516154249.dist-info}/RECORD +112 -112
- {cirq_core-1.6.0.dev20250515174529.dist-info → cirq_core-1.6.0.dev20250516154249.dist-info}/WHEEL +0 -0
- {cirq_core-1.6.0.dev20250515174529.dist-info → cirq_core-1.6.0.dev20250516154249.dist-info}/licenses/LICENSE +0 -0
- {cirq_core-1.6.0.dev20250515174529.dist-info → cirq_core-1.6.0.dev20250516154249.dist-info}/top_level.txt +0 -0
cirq/value/timestamp_test.py
CHANGED
|
@@ -20,7 +20,7 @@ import cirq
|
|
|
20
20
|
from cirq import Duration, Timestamp
|
|
21
21
|
|
|
22
22
|
|
|
23
|
-
def test_init():
|
|
23
|
+
def test_init() -> None:
|
|
24
24
|
assert Timestamp().raw_picos() == 0
|
|
25
25
|
assert Timestamp(picos=513).raw_picos() == 513
|
|
26
26
|
assert Timestamp(picos=-5).raw_picos() == -5
|
|
@@ -33,13 +33,13 @@ def test_init():
|
|
|
33
33
|
assert isinstance(Timestamp(nanos=1.0).raw_picos(), float)
|
|
34
34
|
|
|
35
35
|
|
|
36
|
-
def test_str():
|
|
36
|
+
def test_str() -> None:
|
|
37
37
|
assert str(Timestamp(picos=1000, nanos=1000)) == 't=1001000'
|
|
38
38
|
assert str(Timestamp(nanos=5.0)) == 't=5000.0'
|
|
39
39
|
assert str(Timestamp(picos=-100)) == 't=-100'
|
|
40
40
|
|
|
41
41
|
|
|
42
|
-
def test_repr():
|
|
42
|
+
def test_repr() -> None:
|
|
43
43
|
a = Timestamp(picos=1000, nanos=1000)
|
|
44
44
|
cirq.testing.assert_equivalent_repr(a)
|
|
45
45
|
b = Timestamp(nanos=5.0)
|
|
@@ -48,14 +48,14 @@ def test_repr():
|
|
|
48
48
|
cirq.testing.assert_equivalent_repr(c)
|
|
49
49
|
|
|
50
50
|
|
|
51
|
-
def test_eq():
|
|
51
|
+
def test_eq() -> None:
|
|
52
52
|
eq = cirq.testing.EqualsTester()
|
|
53
53
|
eq.add_equality_group(Timestamp(), Timestamp(picos=0), Timestamp(nanos=0.0))
|
|
54
54
|
eq.add_equality_group(Timestamp(picos=1000), Timestamp(nanos=1))
|
|
55
55
|
eq.make_equality_group(lambda: Timestamp(picos=-1))
|
|
56
56
|
|
|
57
57
|
|
|
58
|
-
def test_cmp():
|
|
58
|
+
def test_cmp() -> None:
|
|
59
59
|
ordered_groups = [
|
|
60
60
|
Timestamp(picos=-1),
|
|
61
61
|
Timestamp(),
|
|
@@ -81,7 +81,7 @@ def test_cmp():
|
|
|
81
81
|
assert Timestamp() != Duration()
|
|
82
82
|
|
|
83
83
|
|
|
84
|
-
def test_cmp_vs_other_type():
|
|
84
|
+
def test_cmp_vs_other_type() -> None:
|
|
85
85
|
with pytest.raises(TypeError):
|
|
86
86
|
_ = Timestamp() < Duration()
|
|
87
87
|
with pytest.raises(TypeError):
|
|
@@ -94,7 +94,7 @@ def test_cmp_vs_other_type():
|
|
|
94
94
|
_ = Timestamp() > 0
|
|
95
95
|
|
|
96
96
|
|
|
97
|
-
def test_add():
|
|
97
|
+
def test_add() -> None:
|
|
98
98
|
assert Timestamp(picos=1) + Duration(picos=2) == Timestamp(picos=3)
|
|
99
99
|
assert Duration(picos=3) + Timestamp(picos=-5) == Timestamp(picos=-2)
|
|
100
100
|
|
|
@@ -109,7 +109,7 @@ def test_add():
|
|
|
109
109
|
_ = Timestamp() + 1
|
|
110
110
|
|
|
111
111
|
|
|
112
|
-
def test_sub():
|
|
112
|
+
def test_sub() -> None:
|
|
113
113
|
assert Timestamp() - Timestamp() == Duration()
|
|
114
114
|
assert Timestamp(picos=1) - Timestamp(picos=2) == Duration(picos=-1)
|
|
115
115
|
assert Timestamp(picos=5) - Duration(picos=2) == Timestamp(picos=3)
|
|
@@ -118,6 +118,6 @@ def test_sub():
|
|
|
118
118
|
with pytest.raises(TypeError):
|
|
119
119
|
_ = Duration() - Timestamp()
|
|
120
120
|
with pytest.raises(TypeError):
|
|
121
|
-
_ = 1 - Timestamp()
|
|
121
|
+
_ = 1 - Timestamp() # type: ignore[operator]
|
|
122
122
|
with pytest.raises(TypeError):
|
|
123
|
-
_ = Timestamp() - 1
|
|
123
|
+
_ = Timestamp() - 1 # type: ignore[operator]
|
cirq/vis/density_matrix_test.py
CHANGED
|
@@ -24,7 +24,7 @@ from cirq.vis.density_matrix import _plot_element_of_density_matrix, plot_densit
|
|
|
24
24
|
@pytest.mark.usefixtures('closefigures')
|
|
25
25
|
@pytest.mark.parametrize('show_text', [True, False])
|
|
26
26
|
@pytest.mark.parametrize('size', [2, 4, 8, 16])
|
|
27
|
-
def test_density_matrix_plotter(size, show_text):
|
|
27
|
+
def test_density_matrix_plotter(size, show_text) -> None:
|
|
28
28
|
matrix = cirq.testing.random_density_matrix(size)
|
|
29
29
|
# Check that the title shows back up
|
|
30
30
|
ax = plot_density_matrix(matrix, show_text=show_text, title='Test Density Matrix Plot')
|
|
@@ -48,16 +48,16 @@ def test_density_matrix_plotter(size, show_text):
|
|
|
48
48
|
@pytest.mark.usefixtures('closefigures')
|
|
49
49
|
@pytest.mark.parametrize('show_text', [True, False])
|
|
50
50
|
@pytest.mark.parametrize('size', [2, 4, 8, 16])
|
|
51
|
-
def test_density_matrix_circle_rectangle_sizes(size, show_text):
|
|
51
|
+
def test_density_matrix_circle_rectangle_sizes(size, show_text) -> None:
|
|
52
52
|
matrix = cirq.testing.random_density_matrix(size)
|
|
53
53
|
ax = plot_density_matrix(matrix, show_text=show_text, title='Test Density Matrix Plot')
|
|
54
54
|
# Check that the radius of all the circles in the matrix is correct
|
|
55
|
-
|
|
56
|
-
mean_radius = np.mean([c.radius for c in
|
|
55
|
+
circle_list = [c for c in ax.get_children() if isinstance(c, patches.Circle)]
|
|
56
|
+
mean_radius = np.mean([c.radius for c in circle_list if c.fill])
|
|
57
57
|
mean_value = np.mean(np.abs(matrix))
|
|
58
|
-
circles = np.array(
|
|
59
|
-
(
|
|
60
|
-
)
|
|
58
|
+
circles = np.array(
|
|
59
|
+
sorted(circle_list, key=lambda x: (x.fill, x.center[0], -x.center[1]))
|
|
60
|
+
).reshape((2, size, size))
|
|
61
61
|
for i in range(size):
|
|
62
62
|
for j in range(size):
|
|
63
63
|
assert np.isclose(
|
|
@@ -65,15 +65,15 @@ def test_density_matrix_circle_rectangle_sizes(size, show_text):
|
|
|
65
65
|
)
|
|
66
66
|
|
|
67
67
|
# Check that all the rectangles are of the right height, and only on the diagonal elements
|
|
68
|
-
|
|
68
|
+
rect_list = [
|
|
69
69
|
r
|
|
70
70
|
for r in ax.get_children()
|
|
71
71
|
if isinstance(r, patches.Rectangle) and r.get_alpha() is not None
|
|
72
72
|
]
|
|
73
|
-
assert len(
|
|
74
|
-
mean_size = np.mean([r.get_height() for r in
|
|
73
|
+
assert len(rect_list) == size
|
|
74
|
+
mean_size = np.mean([r.get_height() for r in rect_list])
|
|
75
75
|
mean_value = np.trace(np.abs(matrix)) / size
|
|
76
|
-
rects = np.array(sorted(
|
|
76
|
+
rects = np.array(sorted(rect_list, key=lambda x: x.get_x()))
|
|
77
77
|
for i in range(size):
|
|
78
78
|
# Ensuring that the rectangle is the right height
|
|
79
79
|
assert np.isclose(np.abs(matrix[i, i]) * mean_size / mean_value, rects[i].get_height())
|
|
@@ -90,7 +90,7 @@ def test_density_matrix_circle_rectangle_sizes(size, show_text):
|
|
|
90
90
|
@pytest.mark.usefixtures('closefigures')
|
|
91
91
|
@pytest.mark.parametrize('show_text', [True, False])
|
|
92
92
|
@pytest.mark.parametrize('size', [2, 4, 8, 16])
|
|
93
|
-
def test_density_matrix_sizes_upper_bounds(size, show_text):
|
|
93
|
+
def test_density_matrix_sizes_upper_bounds(size, show_text) -> None:
|
|
94
94
|
matrix = cirq.testing.random_density_matrix(size)
|
|
95
95
|
ax = plot_density_matrix(matrix, show_text=show_text, title='Test Density Matrix Plot')
|
|
96
96
|
|
|
@@ -113,7 +113,7 @@ def test_density_matrix_sizes_upper_bounds(size, show_text):
|
|
|
113
113
|
@pytest.mark.usefixtures('closefigures')
|
|
114
114
|
@pytest.mark.parametrize('show_rect', [True, False])
|
|
115
115
|
@pytest.mark.parametrize('value', [0.0, 1.0, 0.5 + 0.3j, 0.2 + 0.1j, 0.5 + 0.5j])
|
|
116
|
-
def test_density_element_plot(value, show_rect):
|
|
116
|
+
def test_density_element_plot(value, show_rect) -> None:
|
|
117
117
|
_, ax = plt.subplots(figsize=(10, 10))
|
|
118
118
|
_plot_element_of_density_matrix(
|
|
119
119
|
ax, 0, 0, np.abs(value), np.angle(value), show_rect=False, show_text=False
|
|
@@ -122,9 +122,9 @@ def test_density_element_plot(value, show_rect):
|
|
|
122
122
|
plotted_lines = [c for c in ax.get_children() if isinstance(c, lines.Line2D)]
|
|
123
123
|
assert len(plotted_lines) == 1
|
|
124
124
|
line_position = plotted_lines[0].get_xydata()
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
)
|
|
125
|
+
numerator = line_position[1, 1] - line_position[0, 1] # type: ignore
|
|
126
|
+
denumerator = line_position[1, 0] - line_position[0, 0] # type: ignore
|
|
127
|
+
angle = np.arctan(numerator / denumerator)
|
|
128
128
|
assert np.isclose(np.angle(value), angle)
|
|
129
129
|
# Check if the circles are the right size ratio, given the value of the element
|
|
130
130
|
circles_in = [c for c in ax.get_children() if isinstance(c, patches.Circle) and c.fill]
|
|
@@ -151,6 +151,6 @@ def test_density_element_plot(value, show_rect):
|
|
|
151
151
|
np.random.random((4, 8)) * np.exp(np.random.random((4, 8)) * 2 * np.pi * 1j),
|
|
152
152
|
],
|
|
153
153
|
)
|
|
154
|
-
def test_density_matrix_type_error(matrix):
|
|
154
|
+
def test_density_matrix_type_error(matrix) -> None:
|
|
155
155
|
with pytest.raises(ValueError, match="Incorrect shape for density matrix:*"):
|
|
156
156
|
plot_density_matrix(matrix)
|
cirq/work/collector_test.py
CHANGED
|
@@ -18,7 +18,7 @@ import pytest
|
|
|
18
18
|
import cirq
|
|
19
19
|
|
|
20
20
|
|
|
21
|
-
def test_circuit_sample_job_equality():
|
|
21
|
+
def test_circuit_sample_job_equality() -> None:
|
|
22
22
|
eq = cirq.testing.EqualsTester()
|
|
23
23
|
c1 = cirq.Circuit()
|
|
24
24
|
c2 = cirq.Circuit(cirq.measure(cirq.LineQubit(0)))
|
|
@@ -32,14 +32,14 @@ def test_circuit_sample_job_equality():
|
|
|
32
32
|
eq.add_equality_group(cirq.CircuitSampleJob(c1, repetitions=10, tag='test'))
|
|
33
33
|
|
|
34
34
|
|
|
35
|
-
def test_circuit_sample_job_repr():
|
|
35
|
+
def test_circuit_sample_job_repr() -> None:
|
|
36
36
|
cirq.testing.assert_equivalent_repr(
|
|
37
37
|
cirq.CircuitSampleJob(cirq.Circuit(cirq.H(cirq.LineQubit(0))), repetitions=10, tag='guess')
|
|
38
38
|
)
|
|
39
39
|
|
|
40
40
|
|
|
41
41
|
@duet.sync
|
|
42
|
-
async def test_async_collect():
|
|
42
|
+
async def test_async_collect() -> None:
|
|
43
43
|
received = []
|
|
44
44
|
|
|
45
45
|
class TestCollector(cirq.Collector):
|
|
@@ -51,14 +51,13 @@ async def test_async_collect():
|
|
|
51
51
|
def on_job_result(self, job, result):
|
|
52
52
|
received.append(job.tag)
|
|
53
53
|
|
|
54
|
-
|
|
54
|
+
await TestCollector().collect_async(
|
|
55
55
|
sampler=cirq.Simulator(), max_total_samples=100, concurrency=5
|
|
56
56
|
)
|
|
57
|
-
assert result is None
|
|
58
57
|
assert received == ['test'] * 10
|
|
59
58
|
|
|
60
59
|
|
|
61
|
-
def test_collect():
|
|
60
|
+
def test_collect() -> None:
|
|
62
61
|
received = []
|
|
63
62
|
|
|
64
63
|
class TestCollector(cirq.Collector):
|
|
@@ -74,7 +73,7 @@ def test_collect():
|
|
|
74
73
|
assert received == ['test'] * 10
|
|
75
74
|
|
|
76
75
|
|
|
77
|
-
def test_failed_job():
|
|
76
|
+
def test_failed_job() -> None:
|
|
78
77
|
class FailingSampler:
|
|
79
78
|
async def run_async(self, circuit, repetitions):
|
|
80
79
|
await duet.completed_future(None)
|
|
@@ -90,10 +89,14 @@ def test_failed_job():
|
|
|
90
89
|
pass
|
|
91
90
|
|
|
92
91
|
with pytest.raises(Exception, match='job failed!'):
|
|
93
|
-
TestCollector().collect(
|
|
92
|
+
TestCollector().collect(
|
|
93
|
+
sampler=FailingSampler(), # type:ignore
|
|
94
|
+
max_total_samples=100,
|
|
95
|
+
concurrency=5,
|
|
96
|
+
)
|
|
94
97
|
|
|
95
98
|
|
|
96
|
-
def test_collect_with_reaction():
|
|
99
|
+
def test_collect_with_reaction() -> None:
|
|
97
100
|
events = [0]
|
|
98
101
|
sent = 0
|
|
99
102
|
received = 0
|
|
@@ -123,7 +126,7 @@ def test_collect_with_reaction():
|
|
|
123
126
|
assert all(events.index(-k) > events.index(k) for k in range(1, 11))
|
|
124
127
|
|
|
125
128
|
|
|
126
|
-
def test_flatten_jobs_terminate_from_collector():
|
|
129
|
+
def test_flatten_jobs_terminate_from_collector() -> None:
|
|
127
130
|
sent = False
|
|
128
131
|
received = []
|
|
129
132
|
|
|
@@ -20,7 +20,19 @@ import itertools
|
|
|
20
20
|
import os
|
|
21
21
|
import tempfile
|
|
22
22
|
import warnings
|
|
23
|
-
from typing import
|
|
23
|
+
from typing import (
|
|
24
|
+
Any,
|
|
25
|
+
Dict,
|
|
26
|
+
Iterable,
|
|
27
|
+
List,
|
|
28
|
+
Mapping,
|
|
29
|
+
Optional,
|
|
30
|
+
Sequence,
|
|
31
|
+
Set,
|
|
32
|
+
Tuple,
|
|
33
|
+
TYPE_CHECKING,
|
|
34
|
+
Union,
|
|
35
|
+
)
|
|
24
36
|
|
|
25
37
|
import numpy as np
|
|
26
38
|
import pandas as pd
|
|
@@ -246,7 +258,7 @@ def _aggregate_n_repetitions(next_chunk_repetitions: Set[int]) -> int:
|
|
|
246
258
|
|
|
247
259
|
def _check_meas_specs_still_todo(
|
|
248
260
|
meas_specs: List[_MeasurementSpec],
|
|
249
|
-
accumulators:
|
|
261
|
+
accumulators: Mapping[_MeasurementSpec, BitstringAccumulator],
|
|
250
262
|
stopping_criteria: StoppingCriteria,
|
|
251
263
|
) -> Tuple[List[_MeasurementSpec], int]:
|
|
252
264
|
"""Filter `meas_specs` in case some are done.
|
|
@@ -45,7 +45,7 @@ def _check_and_get_real_coef(observable: cirq.PauliString, atol: float):
|
|
|
45
45
|
|
|
46
46
|
def _obs_vals_from_measurements(
|
|
47
47
|
bitstrings: np.ndarray,
|
|
48
|
-
qubit_to_index:
|
|
48
|
+
qubit_to_index: Mapping[cirq.Qid, int],
|
|
49
49
|
observable: cirq.PauliString,
|
|
50
50
|
atol: float,
|
|
51
51
|
):
|
|
@@ -63,7 +63,7 @@ def _obs_vals_from_measurements(
|
|
|
63
63
|
|
|
64
64
|
def _stats_from_measurements(
|
|
65
65
|
bitstrings: np.ndarray,
|
|
66
|
-
qubit_to_index:
|
|
66
|
+
qubit_to_index: Mapping[cirq.Qid, int],
|
|
67
67
|
observable: cirq.PauliString,
|
|
68
68
|
atol: float,
|
|
69
69
|
) -> Tuple[float, float]:
|
|
@@ -216,7 +216,7 @@ class BitstringAccumulator:
|
|
|
216
216
|
self,
|
|
217
217
|
meas_spec: _MeasurementSpec,
|
|
218
218
|
simul_settings: List[InitObsSetting],
|
|
219
|
-
qubit_to_index:
|
|
219
|
+
qubit_to_index: Mapping[cirq.Qid, int],
|
|
220
220
|
bitstrings: Optional[np.ndarray] = None,
|
|
221
221
|
chunksizes: Optional[np.ndarray] = None,
|
|
222
222
|
timestamps: Optional[np.ndarray] = None,
|
|
@@ -16,6 +16,7 @@ from typing import Dict, Iterable, List
|
|
|
16
16
|
|
|
17
17
|
import numpy as np
|
|
18
18
|
import pytest
|
|
19
|
+
import sympy
|
|
19
20
|
|
|
20
21
|
import cirq
|
|
21
22
|
import cirq.work as cw
|
|
@@ -37,7 +38,7 @@ from cirq.work.observable_measurement import (
|
|
|
37
38
|
)
|
|
38
39
|
|
|
39
40
|
|
|
40
|
-
def test_with_parameterized_layers():
|
|
41
|
+
def test_with_parameterized_layers() -> None:
|
|
41
42
|
qs = cirq.LineQubit.range(3)
|
|
42
43
|
circuit = cirq.Circuit([cirq.H.on_each(*qs), cirq.CZ(qs[0], qs[1]), cirq.CZ(qs[1], qs[2])])
|
|
43
44
|
circuit2 = _with_parameterized_layers(circuit, qubits=qs, needs_init_layer=False)
|
|
@@ -46,9 +47,11 @@ def test_with_parameterized_layers():
|
|
|
46
47
|
*_, xlayer, ylayer, measurelayer = circuit2.moments
|
|
47
48
|
for op in xlayer.operations:
|
|
48
49
|
assert isinstance(op.gate, cirq.XPowGate)
|
|
50
|
+
assert isinstance(op.gate.exponent, sympy.Symbol)
|
|
49
51
|
assert op.gate.exponent.name.endswith('-Xf')
|
|
50
52
|
for op in ylayer.operations:
|
|
51
53
|
assert isinstance(op.gate, cirq.YPowGate)
|
|
54
|
+
assert isinstance(op.gate.exponent, sympy.Symbol)
|
|
52
55
|
assert op.gate.exponent.name.endswith('-Yf')
|
|
53
56
|
for op in measurelayer:
|
|
54
57
|
assert isinstance(op.gate, cirq.MeasurementGate)
|
|
@@ -60,13 +63,15 @@ def test_with_parameterized_layers():
|
|
|
60
63
|
xlayer, ylayer, *_ = circuit3.moments
|
|
61
64
|
for op in xlayer.operations:
|
|
62
65
|
assert isinstance(op.gate, cirq.XPowGate)
|
|
66
|
+
assert isinstance(op.gate.exponent, sympy.Symbol)
|
|
63
67
|
assert op.gate.exponent.name.endswith('-Xi')
|
|
64
68
|
for op in ylayer.operations:
|
|
65
69
|
assert isinstance(op.gate, cirq.YPowGate)
|
|
70
|
+
assert isinstance(op.gate.exponent, sympy.Symbol)
|
|
66
71
|
assert op.gate.exponent.name.endswith('-Yi')
|
|
67
72
|
|
|
68
73
|
|
|
69
|
-
def test_get_params_for_setting():
|
|
74
|
+
def test_get_params_for_setting() -> None:
|
|
70
75
|
qubits = cirq.LineQubit.range(3)
|
|
71
76
|
a, b, c = qubits
|
|
72
77
|
|
|
@@ -82,10 +87,10 @@ def test_get_params_for_setting():
|
|
|
82
87
|
needs_init_layer = True
|
|
83
88
|
with pytest.raises(ValueError):
|
|
84
89
|
_get_params_for_setting(
|
|
85
|
-
padded_setting, flips=[
|
|
90
|
+
padded_setting, flips=[False, False], qubits=qubits, needs_init_layer=needs_init_layer
|
|
86
91
|
)
|
|
87
92
|
params = _get_params_for_setting(
|
|
88
|
-
padded_setting, flips=[
|
|
93
|
+
padded_setting, flips=[False, False, True], qubits=qubits, needs_init_layer=needs_init_layer
|
|
89
94
|
)
|
|
90
95
|
assert all(
|
|
91
96
|
x in params
|
|
@@ -116,7 +121,7 @@ def test_get_params_for_setting():
|
|
|
116
121
|
np.testing.assert_allclose([ma, mb, mc], [1, 0, -1])
|
|
117
122
|
|
|
118
123
|
|
|
119
|
-
def test_params_and_settings():
|
|
124
|
+
def test_params_and_settings() -> None:
|
|
120
125
|
qubits = cirq.LineQubit.range(1)
|
|
121
126
|
(q,) = qubits
|
|
122
127
|
tests = [
|
|
@@ -143,7 +148,7 @@ def test_params_and_settings():
|
|
|
143
148
|
assert np.abs(coef - z) < 1e-2, f'{init} {obs} {coef}'
|
|
144
149
|
|
|
145
150
|
|
|
146
|
-
def test_subdivide_meas_specs():
|
|
151
|
+
def test_subdivide_meas_specs() -> None:
|
|
147
152
|
qubits = cirq.LineQubit.range(2)
|
|
148
153
|
q0, q1 = qubits
|
|
149
154
|
setting = cw.InitObsSetting(
|
|
@@ -177,7 +182,7 @@ def test_subdivide_meas_specs():
|
|
|
177
182
|
]
|
|
178
183
|
|
|
179
184
|
|
|
180
|
-
def test_aggregate_n_repetitions():
|
|
185
|
+
def test_aggregate_n_repetitions() -> None:
|
|
181
186
|
with pytest.warns(UserWarning):
|
|
182
187
|
reps = _aggregate_n_repetitions({5, 6})
|
|
183
188
|
assert reps == 6
|
|
@@ -197,7 +202,7 @@ class _MockBitstringAccumulator(BitstringAccumulator):
|
|
|
197
202
|
return cov / len(self.bitstrings)
|
|
198
203
|
|
|
199
204
|
|
|
200
|
-
def test_variance_stopping_criteria():
|
|
205
|
+
def test_variance_stopping_criteria() -> None:
|
|
201
206
|
stop = cw.VarianceStoppingCriteria(variance_bound=1e-6)
|
|
202
207
|
acc = _MockBitstringAccumulator()
|
|
203
208
|
assert stop.more_repetitions(acc) == 10_000
|
|
@@ -222,22 +227,30 @@ class _WildVarianceStoppingCriteria(StoppingCriteria):
|
|
|
222
227
|
return [5, 6][self._state % 2]
|
|
223
228
|
|
|
224
229
|
|
|
225
|
-
def test_variance_stopping_criteria_aggregate_n_repetitions():
|
|
230
|
+
def test_variance_stopping_criteria_aggregate_n_repetitions() -> None:
|
|
231
|
+
q0, q1 = cirq.LineQubit.range(2)
|
|
226
232
|
stop = _WildVarianceStoppingCriteria()
|
|
227
233
|
acc1 = _MockBitstringAccumulator()
|
|
228
234
|
acc2 = _MockBitstringAccumulator()
|
|
229
|
-
|
|
235
|
+
setting = InitObsSetting(
|
|
236
|
+
init_state=cirq.KET_ZERO(q0) * cirq.KET_ZERO(q1), observable=cirq.X(q0) * cirq.Y(q1)
|
|
237
|
+
)
|
|
238
|
+
meas_spec = _MeasurementSpec(
|
|
239
|
+
max_setting=setting, circuit_params={'beta': 0.123, 'gamma': 0.456}
|
|
240
|
+
)
|
|
241
|
+
meas_spec2 = _MeasurementSpec(
|
|
242
|
+
max_setting=setting, circuit_params={'beta': 0.123, 'gamma': 0.456}
|
|
243
|
+
)
|
|
244
|
+
accumulators = {meas_spec: acc1, meas_spec2: acc2}
|
|
230
245
|
with pytest.warns(UserWarning, match='the largest value will be used: 6.'):
|
|
231
246
|
still_todo, reps = _check_meas_specs_still_todo(
|
|
232
|
-
meas_specs=
|
|
233
|
-
accumulators=accumulators,
|
|
234
|
-
stopping_criteria=stop,
|
|
247
|
+
meas_specs=[meas_spec, meas_spec2], accumulators=accumulators, stopping_criteria=stop
|
|
235
248
|
)
|
|
236
|
-
assert still_todo == [
|
|
249
|
+
assert still_todo == [meas_spec, meas_spec2]
|
|
237
250
|
assert reps == 6
|
|
238
251
|
|
|
239
252
|
|
|
240
|
-
def test_repetitions_stopping_criteria():
|
|
253
|
+
def test_repetitions_stopping_criteria() -> None:
|
|
241
254
|
stop = cw.RepetitionsStoppingCriteria(total_repetitions=50_000)
|
|
242
255
|
acc = _MockBitstringAccumulator()
|
|
243
256
|
|
|
@@ -248,7 +261,7 @@ def test_repetitions_stopping_criteria():
|
|
|
248
261
|
assert todos == [10_000] * 5 + [0, 0]
|
|
249
262
|
|
|
250
263
|
|
|
251
|
-
def test_repetitions_stopping_criteria_partial():
|
|
264
|
+
def test_repetitions_stopping_criteria_partial() -> None:
|
|
252
265
|
stop = cw.RepetitionsStoppingCriteria(total_repetitions=5_000, repetitions_per_chunk=1_000_000)
|
|
253
266
|
acc = _MockBitstringAccumulator()
|
|
254
267
|
assert stop.more_repetitions(acc) == 5_000
|
|
@@ -268,7 +281,7 @@ def _set_up_meas_specs_for_testing():
|
|
|
268
281
|
return bsa, meas_spec
|
|
269
282
|
|
|
270
283
|
|
|
271
|
-
def test_meas_specs_still_todo():
|
|
284
|
+
def test_meas_specs_still_todo() -> None:
|
|
272
285
|
bsa, meas_spec = _set_up_meas_specs_for_testing()
|
|
273
286
|
stop = cw.RepetitionsStoppingCriteria(1_000)
|
|
274
287
|
|
|
@@ -296,7 +309,7 @@ def test_meas_specs_still_todo():
|
|
|
296
309
|
assert reps == 0
|
|
297
310
|
|
|
298
311
|
|
|
299
|
-
def test_meas_spec_still_todo_bad_spec():
|
|
312
|
+
def test_meas_spec_still_todo_bad_spec() -> None:
|
|
300
313
|
bsa, meas_spec = _set_up_meas_specs_for_testing()
|
|
301
314
|
|
|
302
315
|
class BadStopping(StoppingCriteria):
|
|
@@ -310,7 +323,7 @@ def test_meas_spec_still_todo_bad_spec():
|
|
|
310
323
|
)
|
|
311
324
|
|
|
312
325
|
|
|
313
|
-
def test_meas_spec_still_todo_too_many_params(monkeypatch):
|
|
326
|
+
def test_meas_spec_still_todo_too_many_params(monkeypatch) -> None:
|
|
314
327
|
monkeypatch.setattr(cw.observable_measurement, 'MAX_REPETITIONS_PER_JOB', 30_000)
|
|
315
328
|
bsa, meas_spec = _set_up_meas_specs_for_testing()
|
|
316
329
|
lots_of_meas_spec = [meas_spec] * 3_001
|
|
@@ -321,7 +334,7 @@ def test_meas_spec_still_todo_too_many_params(monkeypatch):
|
|
|
321
334
|
)
|
|
322
335
|
|
|
323
336
|
|
|
324
|
-
def test_meas_spec_still_todo_lots_of_params(monkeypatch):
|
|
337
|
+
def test_meas_spec_still_todo_lots_of_params(monkeypatch) -> None:
|
|
325
338
|
monkeypatch.setattr(cw.observable_measurement, 'MAX_REPETITIONS_PER_JOB', 30_000)
|
|
326
339
|
bsa, meas_spec = _set_up_meas_specs_for_testing()
|
|
327
340
|
lots_of_meas_spec = [meas_spec] * 4
|
|
@@ -332,7 +345,7 @@ def test_meas_spec_still_todo_lots_of_params(monkeypatch):
|
|
|
332
345
|
)
|
|
333
346
|
|
|
334
347
|
|
|
335
|
-
def test_checkpoint_options():
|
|
348
|
+
def test_checkpoint_options() -> None:
|
|
336
349
|
# There are three ~binary options (the latter two can be either specified or `None`. We
|
|
337
350
|
# test those 2^3 cases.
|
|
338
351
|
|
|
@@ -345,12 +358,15 @@ def test_checkpoint_options():
|
|
|
345
358
|
_parse_checkpoint_options(False, 'test1', 'test2')
|
|
346
359
|
|
|
347
360
|
chk, chkprev = _parse_checkpoint_options(True, None, None)
|
|
361
|
+
assert chk is not None
|
|
362
|
+
assert chkprev is not None
|
|
348
363
|
assert chk.startswith(tempfile.gettempdir())
|
|
349
364
|
assert chk.endswith('observables.json')
|
|
350
365
|
assert chkprev.startswith(tempfile.gettempdir())
|
|
351
366
|
assert chkprev.endswith('observables.prev.json')
|
|
352
367
|
|
|
353
368
|
chk, chkprev = _parse_checkpoint_options(True, None, 'prev.json')
|
|
369
|
+
assert chk is not None
|
|
354
370
|
assert chk.startswith(tempfile.gettempdir())
|
|
355
371
|
assert chk.endswith('observables.json')
|
|
356
372
|
assert chkprev == 'prev.json'
|
|
@@ -381,7 +397,7 @@ def test_checkpoint_options():
|
|
|
381
397
|
|
|
382
398
|
|
|
383
399
|
@pytest.mark.parametrize(('with_circuit_sweep', 'checkpoint'), [(True, True), (False, False)])
|
|
384
|
-
def test_measure_grouped_settings(with_circuit_sweep, checkpoint, tmpdir):
|
|
400
|
+
def test_measure_grouped_settings(with_circuit_sweep, checkpoint, tmpdir) -> None:
|
|
385
401
|
qubits = cirq.LineQubit.range(1)
|
|
386
402
|
(q,) = qubits
|
|
387
403
|
tests = [
|
|
@@ -431,7 +447,7 @@ def _get_some_grouped_settings():
|
|
|
431
447
|
return grouped_settings, qubits
|
|
432
448
|
|
|
433
449
|
|
|
434
|
-
def test_measure_grouped_settings_calibration_validation():
|
|
450
|
+
def test_measure_grouped_settings_calibration_validation() -> None:
|
|
435
451
|
mock_ro_calib = _MockBitstringAccumulator()
|
|
436
452
|
grouped_settings, qubits = _get_some_grouped_settings()
|
|
437
453
|
|
|
@@ -448,7 +464,7 @@ def test_measure_grouped_settings_calibration_validation():
|
|
|
448
464
|
)
|
|
449
465
|
|
|
450
466
|
|
|
451
|
-
def test_measure_grouped_settings_read_checkpoint(tmpdir):
|
|
467
|
+
def test_measure_grouped_settings_read_checkpoint(tmpdir) -> None:
|
|
452
468
|
qubits = cirq.LineQubit.range(1)
|
|
453
469
|
(q,) = qubits
|
|
454
470
|
|
|
@@ -495,7 +511,7 @@ Q = cirq.NamedQubit('q')
|
|
|
495
511
|
(cirq.Circuit(cirq.Y(Q) ** 0.5, cirq.Z(Q) ** 0.2), cirq.X(Q)),
|
|
496
512
|
],
|
|
497
513
|
)
|
|
498
|
-
def test_XYZ_point8(circuit, observable):
|
|
514
|
+
def test_XYZ_point8(circuit, observable) -> None:
|
|
499
515
|
# each circuit, observable combination should result in the observable value of 0.8
|
|
500
516
|
df = measure_observables_df(
|
|
501
517
|
circuit,
|
|
@@ -517,7 +533,7 @@ def _each_in_its_own_group_grouper(
|
|
|
517
533
|
@pytest.mark.parametrize(
|
|
518
534
|
'grouper', ['greedy', group_settings_greedy, _each_in_its_own_group_grouper]
|
|
519
535
|
)
|
|
520
|
-
def test_measure_observable_grouper(grouper):
|
|
536
|
+
def test_measure_observable_grouper(grouper) -> None:
|
|
521
537
|
circuit = cirq.Circuit(cirq.X(Q) ** 0.2)
|
|
522
538
|
observables = [cirq.Z(Q), cirq.Z(cirq.NamedQubit('q2'))]
|
|
523
539
|
results = measure_observables(
|
|
@@ -532,7 +548,7 @@ def test_measure_observable_grouper(grouper):
|
|
|
532
548
|
np.testing.assert_allclose(1, results[1].mean, atol=1e-9)
|
|
533
549
|
|
|
534
550
|
|
|
535
|
-
def test_measure_observable_bad_grouper():
|
|
551
|
+
def test_measure_observable_bad_grouper() -> None:
|
|
536
552
|
circuit = cirq.Circuit(cirq.X(Q) ** 0.2)
|
|
537
553
|
observables = [cirq.Z(Q), cirq.Z(cirq.NamedQubit('q2'))]
|
|
538
554
|
with pytest.raises(ValueError, match=r'Unknown grouping function'):
|
cirq/work/observable_settings.py
CHANGED
|
@@ -16,17 +16,7 @@ from __future__ import annotations
|
|
|
16
16
|
|
|
17
17
|
import dataclasses
|
|
18
18
|
import numbers
|
|
19
|
-
from typing import
|
|
20
|
-
AbstractSet,
|
|
21
|
-
Dict,
|
|
22
|
-
FrozenSet,
|
|
23
|
-
Iterable,
|
|
24
|
-
Mapping,
|
|
25
|
-
Optional,
|
|
26
|
-
Tuple,
|
|
27
|
-
TYPE_CHECKING,
|
|
28
|
-
Union,
|
|
29
|
-
)
|
|
19
|
+
from typing import Dict, FrozenSet, Iterable, Mapping, Optional, Tuple, TYPE_CHECKING, Union
|
|
30
20
|
|
|
31
21
|
import sympy
|
|
32
22
|
|
|
@@ -156,7 +146,7 @@ def _fix_precision(val: Union[value.Scalar, sympy.Expr], precision) -> Union[int
|
|
|
156
146
|
|
|
157
147
|
|
|
158
148
|
def _hashable_param(
|
|
159
|
-
param_tuples:
|
|
149
|
+
param_tuples: Iterable[Tuple[Union[str, sympy.Expr], Union[value.Scalar, sympy.Expr]]],
|
|
160
150
|
precision=1e7,
|
|
161
151
|
) -> FrozenSet[Tuple[str, Union[int, Tuple[int, int]]]]:
|
|
162
152
|
"""Hash circuit parameters using fixed precision.
|
|
@@ -20,7 +20,7 @@ from cirq.work import _MeasurementSpec, InitObsSetting, observables_to_settings
|
|
|
20
20
|
from cirq.work.observable_settings import _hashable_param, _max_weight_observable, _max_weight_state
|
|
21
21
|
|
|
22
22
|
|
|
23
|
-
def test_init_obs_setting():
|
|
23
|
+
def test_init_obs_setting() -> None:
|
|
24
24
|
q0, q1 = cirq.LineQubit.range(2)
|
|
25
25
|
setting = InitObsSetting(
|
|
26
26
|
init_state=cirq.KET_ZERO(q0) * cirq.KET_ZERO(q1), observable=cirq.X(q0) * cirq.Y(q1)
|
|
@@ -32,7 +32,7 @@ def test_init_obs_setting():
|
|
|
32
32
|
setting = InitObsSetting(init_state=cirq.KET_ZERO(q0), observable=cirq.X(q0) * cirq.Y(q1))
|
|
33
33
|
|
|
34
34
|
|
|
35
|
-
def test_max_weight_observable():
|
|
35
|
+
def test_max_weight_observable() -> None:
|
|
36
36
|
q0, q1 = cirq.LineQubit.range(2)
|
|
37
37
|
observables = [cirq.X(q0), cirq.X(q1)]
|
|
38
38
|
assert _max_weight_observable(observables) == cirq.X(q0) * cirq.X(q1)
|
|
@@ -41,7 +41,7 @@ def test_max_weight_observable():
|
|
|
41
41
|
assert _max_weight_observable(observables) is None
|
|
42
42
|
|
|
43
43
|
|
|
44
|
-
def test_max_weight_state():
|
|
44
|
+
def test_max_weight_state() -> None:
|
|
45
45
|
q0, q1 = cirq.LineQubit.range(2)
|
|
46
46
|
states = [cirq.KET_PLUS(q0), cirq.KET_PLUS(q1)]
|
|
47
47
|
assert _max_weight_state(states) == cirq.KET_PLUS(q0) * cirq.KET_PLUS(q1)
|
|
@@ -50,7 +50,7 @@ def test_max_weight_state():
|
|
|
50
50
|
assert _max_weight_state(states) is None
|
|
51
51
|
|
|
52
52
|
|
|
53
|
-
def test_observable_to_setting():
|
|
53
|
+
def test_observable_to_setting() -> None:
|
|
54
54
|
q0, q1, q2 = cirq.LineQubit.range(3)
|
|
55
55
|
observables = [cirq.X(q0) * cirq.Y(q1), cirq.Z(q2) * 1]
|
|
56
56
|
|
|
@@ -62,7 +62,7 @@ def test_observable_to_setting():
|
|
|
62
62
|
assert list(observables_to_settings(observables, qubits=[q0, q1, q2])) == settings_should_be
|
|
63
63
|
|
|
64
64
|
|
|
65
|
-
def test_param_hash():
|
|
65
|
+
def test_param_hash() -> None:
|
|
66
66
|
params1 = [('beta', 1.23), ('gamma', 4.56)]
|
|
67
67
|
params2 = [('beta', 1.23), ('gamma', 4.56)]
|
|
68
68
|
params3 = [('beta', 1.24), ('gamma', 4.57)]
|
|
@@ -81,7 +81,7 @@ def test_param_hash():
|
|
|
81
81
|
assert hash(_hashable_param(params4)) == hash(_hashable_param(params5))
|
|
82
82
|
|
|
83
83
|
|
|
84
|
-
def test_measurement_spec():
|
|
84
|
+
def test_measurement_spec() -> None:
|
|
85
85
|
q0, q1 = cirq.LineQubit.range(2)
|
|
86
86
|
setting = InitObsSetting(
|
|
87
87
|
init_state=cirq.KET_ZERO(q0) * cirq.KET_ZERO(q1), observable=cirq.X(q0) * cirq.Y(q1)
|
|
@@ -96,7 +96,7 @@ def test_measurement_spec():
|
|
|
96
96
|
cirq.testing.assert_equivalent_repr(meas_spec)
|
|
97
97
|
|
|
98
98
|
|
|
99
|
-
def test_measurement_spec_no_symbols():
|
|
99
|
+
def test_measurement_spec_no_symbols() -> None:
|
|
100
100
|
q0, q1 = cirq.LineQubit.range(2)
|
|
101
101
|
setting = InitObsSetting(
|
|
102
102
|
init_state=cirq.KET_ZERO(q0) * cirq.KET_ZERO(q1), observable=cirq.X(q0) * cirq.Y(q1)
|