cirq-core 1.7.0.dev20250926201022__py3-none-any.whl → 1.7.0.dev20250929235728__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/_version.py CHANGED
@@ -28,4 +28,4 @@ if sys.version_info < (3, 11, 0): # pragma: no cover
28
28
  'of Cirq (e.g. "python -m pip install cirq==1.5.0")'
29
29
  )
30
30
 
31
- __version__ = "1.7.0.dev20250926201022"
31
+ __version__ = "1.7.0.dev20250929235728"
cirq/_version_test.py CHANGED
@@ -3,4 +3,4 @@ import cirq
3
3
 
4
4
 
5
5
  def test_version() -> None:
6
- assert cirq.__version__ == "1.7.0.dev20250926201022"
6
+ assert cirq.__version__ == "1.7.0.dev20250929235728"
@@ -150,6 +150,7 @@ from cirq.transformers.gauge_compiling import (
150
150
  SpinInversionGaugeTransformer as SpinInversionGaugeTransformer,
151
151
  SqrtCZGaugeTransformer as SqrtCZGaugeTransformer,
152
152
  SqrtISWAPGaugeTransformer as SqrtISWAPGaugeTransformer,
153
+ CPhaseGaugeTransformerMM as CPhaseGaugeTransformerMM,
153
154
  )
154
155
 
155
156
  from cirq.transformers.randomized_measurements import (
@@ -47,3 +47,11 @@ from cirq.transformers.gauge_compiling.cphase_gauge import (
47
47
  from cirq.transformers.gauge_compiling.idle_moments_gauge import (
48
48
  IdleMomentsGauge as IdleMomentsGauge,
49
49
  )
50
+
51
+ from cirq.transformers.gauge_compiling.multi_moment_gauge_compiling import (
52
+ MultiMomentGaugeTransformer as MultiMomentGaugeTransformer,
53
+ )
54
+
55
+ from cirq.transformers.gauge_compiling.multi_moment_cphase_gauge import (
56
+ CPhaseGaugeTransformerMM as CPhaseGaugeTransformerMM,
57
+ )
@@ -0,0 +1,245 @@
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
+ """A Multi-Moment Gauge Transformer for the cphase gate."""
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import cast
20
+
21
+ import numpy as np
22
+ from attrs import field, frozen
23
+
24
+ from cirq import circuits, ops
25
+ from cirq.transformers.gauge_compiling.multi_moment_gauge_compiling import (
26
+ MultiMomentGaugeTransformer,
27
+ )
28
+
29
+ _PAULIS: np.ndarray = np.array((ops.I, ops.X, ops.Y, ops.Z), dtype=object)
30
+ _COMMUTING_GATES = {ops.I, ops.Z} # I,Z Commute with ZPowGate and CZPowGate; X,Y anti-commute.
31
+
32
+
33
+ def _merge_pauliandzpow(left: _PauliAndZPow, right: _PauliAndZPow) -> _PauliAndZPow:
34
+ # 1. Commute left.zpow and right.pauli:
35
+ # ─left.pauli─left.zpow─right.pauli─right.zpow─
36
+ # ==> ─left.pauli─right.pauli─(+/-left.zpow─right.zpow)─
37
+ if right.pauli in _COMMUTING_GATES:
38
+ new_zpow_exp = left.zpow.exponent + right.zpow.exponent
39
+ else:
40
+ new_zpow_exp = -left.zpow.exponent + right.zpow.exponent
41
+
42
+ # 2. Merge left.pauli and right.pauli
43
+ new_pauli = left.pauli
44
+ if right.pauli is not ops.I:
45
+ if new_pauli is ops.I:
46
+ new_pauli = right.pauli
47
+ else:
48
+ # left.pauli * right.pauli
49
+ new_pauli = cast(ops.Pauli, new_pauli).phased_pauli_product(
50
+ cast(ops.Pauli, right.pauli)
51
+ )[1]
52
+
53
+ return _PauliAndZPow(pauli=new_pauli, zpow=ops.ZPowGate(exponent=new_zpow_exp))
54
+
55
+
56
+ @frozen
57
+ class _PauliAndZPow:
58
+ """A gate represented by a Pauli followed by a ZPowGate.
59
+
60
+ The order is ─Pauli──ZPowGate─.
61
+
62
+ Attributes:
63
+ pauli: The Pauli gate.
64
+ zpow: The ZPowGate.
65
+ """
66
+
67
+ pauli: ops.Pauli | ops.IdentityGate = ops.I
68
+ zpow: ops.ZPowGate = ops.ZPowGate(exponent=0)
69
+
70
+ def merge_left(self, left: _PauliAndZPow) -> _PauliAndZPow:
71
+ """Merges another `_PauliAndZPow` from the left.
72
+
73
+ Calculates `─left─self─` and returns a new `_PauliAndZPow` instance.
74
+ """
75
+ return _merge_pauliandzpow(left, self)
76
+
77
+ def merge_right(self, right: _PauliAndZPow) -> _PauliAndZPow:
78
+ """Merges another `_PauliAndZPow` from the right.
79
+
80
+ Calculates `─self─right─` and returns a new `_PauliAndZPow` instance.
81
+ """
82
+ return _merge_pauliandzpow(self, right)
83
+
84
+ def after_cphase(
85
+ self, cphase: ops.CZPowGate
86
+ ) -> tuple[ops.CZPowGate, _PauliAndZPow, _PauliAndZPow]:
87
+ """Pull self through cphase.
88
+
89
+ Returns:
90
+ A tuple of
91
+ (updated cphase gate, pull_through of this qubit, pull_through of the other qubit).
92
+ """
93
+ if self.pauli in _COMMUTING_GATES:
94
+ return cphase, _PauliAndZPow(self.pauli, self.zpow), _PauliAndZPow()
95
+ else:
96
+ # Taking self.pauli==X gate as an example:
97
+ # 0: ─X─Z^t──@────── 0: ─X──@─────Z^t─ 0: ─@──────X──Z^t──
98
+ # │ ==> │ ==> │
99
+ # 1: ────────@^exp── 1: ────@^exp───── 1: ─@^-exp─Z^exp───
100
+ # Similarly for X|Y on qubit 0/1, the result is always flipping cphase and
101
+ # add an extra Rz rotation on the other qubit.
102
+ return (
103
+ cast(ops.CZPowGate, cphase**-1),
104
+ _PauliAndZPow(self.pauli, self.zpow),
105
+ _PauliAndZPow(zpow=ops.ZPowGate(exponent=cphase.exponent)),
106
+ )
107
+
108
+ def after_pauli(self, pauli: ops.Pauli | ops.IdentityGate) -> _PauliAndZPow:
109
+ """Calculates ─self─pauli─ ==> ─pauli─output─."""
110
+ if pauli in _COMMUTING_GATES:
111
+ return _PauliAndZPow(self.pauli, self.zpow)
112
+ else:
113
+ return _PauliAndZPow(self.pauli, ops.ZPowGate(exponent=-self.zpow.exponent))
114
+
115
+ def after_zpow(self, zpow: ops.ZPowGate) -> tuple[ops.ZPowGate, _PauliAndZPow]:
116
+ """Calculates ─self─zpow─ ==> ─+/-zpow─output─."""
117
+ if self.pauli in _COMMUTING_GATES:
118
+ return zpow, _PauliAndZPow(self.pauli, self.zpow)
119
+ else:
120
+ return ops.ZPowGate(exponent=-zpow.exponent), self
121
+
122
+ def __str__(self) -> str:
123
+ return f"─{self.pauli}──{self.zpow}─"
124
+
125
+ def to_single_qubit_gate(self) -> ops.PhasedXZGate | ops.ZPowGate | ops.IdentityGate:
126
+ """Converts the _PauliAndZPow to a single-qubit gate."""
127
+ exp = self.zpow.exponent
128
+ match self.pauli:
129
+ case ops.I:
130
+ if exp % 2 == 0:
131
+ return ops.I
132
+ return self.zpow
133
+ case ops.X:
134
+ return ops.PhasedXZGate(x_exponent=1, z_exponent=exp, axis_phase_exponent=0)
135
+ case ops.Y:
136
+ return ops.PhasedXZGate(x_exponent=1, z_exponent=exp - 1, axis_phase_exponent=0)
137
+ case _: # ops.Z
138
+ return ops.ZPowGate(exponent=1 + exp)
139
+
140
+
141
+ def _pull_through_single_cphase(
142
+ cphase: ops.CZPowGate, input0: _PauliAndZPow, input1: _PauliAndZPow
143
+ ) -> tuple[ops.CZPowGate, _PauliAndZPow, _PauliAndZPow]:
144
+ """Pulls input0 and input1 through a CZPowGate.
145
+ Input: Output:
146
+ 0: ─(input0)─@───── 0: ─@────────(output0)─
147
+ │ ==> │
148
+ 1: ─(input1)─@^exp─ 1: ─@^+/-exp─(output1)─
149
+ """
150
+
151
+ # Step 1; pull input0 through CZPowGate.
152
+ # 0: ─input0─@───── 0: ────────@─────────output0─
153
+ # │ ==> │
154
+ # 1: ─input1─@^exp─ 1: ─input1─@^+/-exp──output1─
155
+ output_cphase, output0, output1 = input0.after_cphase(cphase)
156
+
157
+ # Step 2; similar to step 1, pull input1 through CZPowGate.
158
+ # 0: ─@──────────pulled0────output0─ 0: ─@────────output0─
159
+ # ==> │ ==> │
160
+ # 1: ─@^+/-exp───pulled1────output1─ 1: ─@^+/-exp─output1─
161
+ output_cphase, pulled1, pulled0 = input1.after_cphase(output_cphase)
162
+ output0 = output0.merge_left(pulled0)
163
+ output1 = output1.merge_left(pulled1)
164
+
165
+ return output_cphase, output0, output1
166
+
167
+
168
+ _TARGET_GATESET: ops.Gateset = ops.Gateset(ops.CZPowGate)
169
+ _SUPPORTED_GATESET: ops.Gateset = ops.Gateset(ops.Pauli, ops.IdentityGate, ops.ZPowGate)
170
+
171
+
172
+ @frozen
173
+ class CPhaseGaugeTransformerMM(MultiMomentGaugeTransformer):
174
+ """A gauge transformer for the cphase gate."""
175
+
176
+ target: ops.GateFamily | ops.Gateset = field(default=_TARGET_GATESET, init=False)
177
+ supported_gates: ops.GateFamily | ops.Gateset = field(default=_SUPPORTED_GATESET)
178
+
179
+ def sample_left_moment(
180
+ self, active_qubits: frozenset[ops.Qid], rng: np.random.Generator
181
+ ) -> circuits.Moment:
182
+ """Samples a random single-qubit moment to be inserted before the target block."""
183
+ return circuits.Moment([cast(ops.Gate, rng.choice(_PAULIS)).on(q) for q in active_qubits])
184
+
185
+ def gauge_on_moments(
186
+ self,
187
+ moments_to_gauge: list[circuits.Moment],
188
+ prng: np.random.Generator = np.random.default_rng(),
189
+ ) -> list[circuits.Moment]:
190
+ """Gauges a block of moments that contains at least a cphase gate in each of the moment.
191
+
192
+ Args:
193
+ moments_to_gauge: A list of moments to be gauged.
194
+ prng: A pseudorandom number generator.
195
+
196
+ Returns:
197
+ A list of moments after gauging.
198
+ """
199
+ active_qubits = circuits.Circuit.from_moments(*moments_to_gauge).all_qubits()
200
+ left_moment = self.sample_left_moment(active_qubits, prng)
201
+ pulled: dict[ops.Qid, _PauliAndZPow] = {
202
+ op.qubits[0]: _PauliAndZPow(pauli=cast(ops.Pauli | ops.IdentityGate, op.gate))
203
+ for op in left_moment
204
+ if op.gate
205
+ }
206
+ ret: list[circuits.Moment] = [left_moment]
207
+ # The loop iterates through each moment of the target block, propagating
208
+ # the `pulled` gauge from left to right. In each iteration, `prev` holds
209
+ # the gauge to the left of the current `moment`, and the loop computes
210
+ # the transformed `moment` and the new `pulled` gauge to its right.
211
+ for moment in moments_to_gauge:
212
+ # Calculate --prev--moment-- ==> --updated_momment--pulled--
213
+ prev = pulled
214
+ pulled = {}
215
+ ops_at_updated_moment: list[ops.Operation] = []
216
+ for op in moment:
217
+ # Pull prev through ops at the moment.
218
+ if op.gate:
219
+ match op.gate:
220
+ case ops.CZPowGate():
221
+ q0, q1 = op.qubits
222
+ new_gate, pulled[q0], pulled[q1] = _pull_through_single_cphase(
223
+ op.gate, prev[q0], prev[q1]
224
+ )
225
+ ops_at_updated_moment.append(new_gate.on(q0, q1))
226
+ case ops.Pauli() | ops.IdentityGate():
227
+ q = op.qubits[0]
228
+ ops_at_updated_moment.append(op)
229
+ pulled[q] = prev[q].after_pauli(op.gate)
230
+ case ops.ZPowGate():
231
+ q = op.qubits[0]
232
+ new_zpow, pulled[q] = prev[q].after_zpow(op.gate)
233
+ ops_at_updated_moment.append(new_zpow.on(q))
234
+ case _:
235
+ raise ValueError(f"Gate type {type(op.gate)} is not supported.")
236
+ # Keep the other ops of prev
237
+ for q, gate in prev.items():
238
+ if q not in pulled:
239
+ pulled[q] = gate
240
+ ret.append(circuits.Moment(ops_at_updated_moment))
241
+ last_moment = circuits.Moment(
242
+ [gate.to_single_qubit_gate().on(q) for q, gate in pulled.items()]
243
+ )
244
+ ret.append(last_moment)
245
+ return ret
@@ -0,0 +1,243 @@
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
+ from __future__ import annotations
16
+
17
+ import numpy as np
18
+ import pytest
19
+
20
+ import cirq
21
+ from cirq import I, X, Y, Z, ZPowGate
22
+ from cirq.transformers.gauge_compiling.multi_moment_cphase_gauge import (
23
+ _PauliAndZPow,
24
+ CPhaseGaugeTransformerMM,
25
+ )
26
+
27
+
28
+ def test_gauge_on_single_cphase():
29
+ """Test case.
30
+ Input:
31
+ 0: ───@───────
32
+
33
+ 1: ───@^0.2───
34
+ Example output:
35
+ 0: ───X───@────────PhXZ(a=0,x=1,z=0)───
36
+
37
+ 1: ───I───@^-0.2───Z^0.2───────────────
38
+ """
39
+ q0, q1 = cirq.LineQubit.range(2)
40
+
41
+ input_circuit = cirq.Circuit(cirq.Moment(cirq.CZ(q0, q1) ** 0.2))
42
+
43
+ class _TestCPhaseGaugeTransformerMM(CPhaseGaugeTransformerMM):
44
+ def sample_left_moment(
45
+ self,
46
+ active_qubits: frozenset[cirq.Qid],
47
+ rng: np.random.Generator = np.random.default_rng(),
48
+ ) -> cirq.Moment:
49
+ return cirq.Moment(g1(q0), g2(q1))
50
+
51
+ for g1 in [X, Y, Z, I]:
52
+ for g2 in [X, Y, Z, I]: # Test with all possible samples of the left moment.
53
+ cphase_transformer = _TestCPhaseGaugeTransformerMM()
54
+ output_circuit = cphase_transformer(input_circuit)
55
+ cirq.testing.assert_circuits_have_same_unitary_given_final_permutation(
56
+ input_circuit, output_circuit, {q: q for q in input_circuit.all_qubits()}
57
+ )
58
+
59
+
60
+ def test_gauge_on_cz_moments():
61
+ """Test case.
62
+ Input:
63
+ ┌──┐
64
+ 0: ───@────@─────H───────@───@───
65
+ │ │ │ │
66
+ 1: ───@────┼@────────────@───@───
67
+ ││
68
+ 2: ───@────@┼────────@───@───@───
69
+ │ │ │ │ │
70
+ 3: ───@─────@────────@───@───@───
71
+ └──┘
72
+ Example output:
73
+ ┌──┐
74
+ 0: ───X───@────@─────PhXZ(a=0,x=1,z=1)──────H───X───────@───@───PhXZ(a=0,x=1,z=2)────
75
+ │ │ │ │
76
+ 1: ───I───@────┼@────Z──────────────────────────X───────@───@───PhXZ(a=2,x=1,z=-2)───
77
+ ││
78
+ 2: ───Y───@────@┼────PhXZ(a=1.5,x=1,z=-1)───────Z───@───@───@───Z────────────────────
79
+ │ │ │ │ │
80
+ 3: ───Z───@─────@────Z^0────────────────────────I───@───@───@───Z^0──────────────────
81
+ └──┘
82
+ """
83
+ q0, q1, q2, q3 = cirq.LineQubit.range(4)
84
+ input_circuit = cirq.Circuit(
85
+ cirq.Moment(cirq.CZ(q0, q1), cirq.CZ(q2, q3)),
86
+ cirq.Moment(cirq.CZ(q0, q2), cirq.CZ(q1, q3)),
87
+ cirq.Moment(cirq.H(q0)),
88
+ cirq.Moment(cirq.CZ(q2, q3)),
89
+ cirq.Moment(cirq.CZ(q0, q1), cirq.CZ(q2, q3)),
90
+ cirq.Moment(cirq.CZ(q0, q1), cirq.CZ(q2, q3)),
91
+ )
92
+ transformer = CPhaseGaugeTransformerMM()
93
+
94
+ output_circuit = transformer(input_circuit)
95
+ cirq.testing.assert_circuits_have_same_unitary_given_final_permutation(
96
+ input_circuit, output_circuit, {q: q for q in input_circuit.all_qubits()}
97
+ )
98
+
99
+
100
+ def test_is_target_moment():
101
+ q0, q1, q2 = cirq.LineQubit.range(3)
102
+
103
+ target_moments = [
104
+ cirq.Moment(cirq.CZ(q0, q1) ** 0.2),
105
+ cirq.Moment(cirq.CZ(q0, q1) ** 0.2, cirq.X(q2)),
106
+ ]
107
+ non_target_moments = [
108
+ cirq.Moment(cirq.X(q0), cirq.Y(q1)),
109
+ cirq.Moment(cirq.CZ(q0, q1) ** 0.2, cirq.Rz(rads=-0.8).on(q2)),
110
+ cirq.Moment(cirq.CZ(q0, q1).with_tags("ignore")),
111
+ cirq.Moment(cirq.CZ(q0, q1)).with_tags("ignore"),
112
+ ]
113
+ cphase_transformer = CPhaseGaugeTransformerMM(supported_gates=cirq.Gateset(cirq.Pauli))
114
+ for m in target_moments:
115
+ assert cphase_transformer.is_target_moment(m)
116
+ for m in non_target_moments:
117
+ assert not cphase_transformer.is_target_moment(
118
+ m, cirq.TransformerContext(tags_to_ignore={'ignore'})
119
+ )
120
+
121
+
122
+ def test_gauge_on_cphase_moments():
123
+ """Test case.
124
+ Input:
125
+ ┌──┐
126
+ 0: ───@────────@─────H───Rz(-0.255π)───────────@───────@───────
127
+ │ │ │ │
128
+ 1: ───@^0.2────┼@──────────────────────────────@^0.1───@───────
129
+ ││
130
+ 2: ───@────────@┼────────@─────────────@───────@───────@───────
131
+ │ │ │ │ │ │
132
+ 3: ───@─────────@────────@^0.2─────────@^0.2───@───────@^0.2───
133
+ └──┘
134
+ Example output:
135
+ ┌──┐
136
+ 0: ───Y───@─────────@─────PhXZ(a=0,x=1,z=0)───H───X───Rz(0.255π)────────────@───────@────────PhXZ(a=0,x=1,z=1.1)───
137
+ │ │ │ │
138
+ 1: ───I───@^-0.2────┼@────Z^0.2───────────────────Y─────────────────────────@^0.1───@────────PhXZ(a=0,x=1,z=0.1)───
139
+ ││
140
+ 2: ───X───@─────────@┼────PhXZ(a=0,x=1,z=1)───────X───@────────────@────────@───────@────────PhXZ(a=0,x=1,z=0)─────
141
+ │ │ │ │ │ │
142
+ 3: ───Z───@──────────@────I───────────────────────I───@^-0.2───────@^-0.2───@───────@^-0.2───Z^-0.4────────────────
143
+ └──┘
144
+ """ # noqa: E501
145
+ q0, q1, q2, q3 = cirq.LineQubit.range(4)
146
+ cphase_transformer = CPhaseGaugeTransformerMM()
147
+ for _ in range(5):
148
+ input_circuit = cirq.Circuit(
149
+ cirq.Moment(cirq.CZ(q0, q1) ** 0.2, cirq.CZ(q2, q3)),
150
+ cirq.Moment(cirq.CZ(q0, q2), cirq.CZ(q1, q3)),
151
+ cirq.Moment(cirq.H(q0)),
152
+ cirq.Moment(cirq.CZ(q2, q3) ** 0.2, cirq.Rz(rads=-0.8).on(q0)),
153
+ cirq.Moment(cirq.CZ(q2, q3) ** 0.2),
154
+ cirq.Moment(cirq.CZ(q0, q1) ** 0.1, cirq.CZ(q2, q3)),
155
+ cirq.Moment(cirq.CZ(q0, q1), cirq.CZ(q2, q3) ** 0.2),
156
+ )
157
+
158
+ output_circuit = cphase_transformer(input_circuit)
159
+ cirq.testing.assert_circuits_have_same_unitary_given_final_permutation(
160
+ input_circuit, output_circuit, {q: q for q in input_circuit.all_qubits()}
161
+ )
162
+
163
+
164
+ def test_gauge_on_czpow_only_moments():
165
+ q0, q1, q2 = cirq.LineQubit.range(3)
166
+
167
+ input_circuit = cirq.Circuit(cirq.Moment(cirq.CZ(q0, q1) ** 0.2, X(q2)))
168
+ cphase_transformer = CPhaseGaugeTransformerMM(supported_gates=cirq.Gateset())
169
+ output_circuit = cphase_transformer(input_circuit)
170
+
171
+ # Since X isn't in supported_gates, the moment won't be gauged.
172
+ assert input_circuit == output_circuit
173
+
174
+
175
+ def test_gauge_on_supported_gates():
176
+ q0, q1, q2, q3 = cirq.LineQubit.range(4)
177
+ cphase_transformer = CPhaseGaugeTransformerMM()
178
+ for g1 in [X, Z**0.6, I, Z]:
179
+ for g2 in [Y, cirq.Rz(rads=0.2), Z**0.7]:
180
+ input_circuit = cirq.Circuit(
181
+ cirq.Moment(cirq.CZ(q0, q1) ** 0.2, g1(q2), g2(q3)),
182
+ cirq.Moment(cirq.CZ(q0, q2), g2(q1), g1(q3)),
183
+ )
184
+ output_circuit = cphase_transformer(input_circuit)
185
+ cirq.testing.assert_circuits_have_same_unitary_given_final_permutation(
186
+ input_circuit, output_circuit, {q: q for q in input_circuit.all_qubits()}
187
+ )
188
+
189
+
190
+ def test_gauge_on_unsupported_gates():
191
+ q0, q1, q2, q3 = cirq.LineQubit.range(4)
192
+
193
+ cphase_transformer = CPhaseGaugeTransformerMM(supported_gates=cirq.Gateset(cirq.CNOT))
194
+ with pytest.raises(ValueError, match="Gate type .* is not supported."):
195
+ cphase_transformer(cirq.Circuit(cirq.CNOT(q0, q1), cirq.CZ(q2, q3)))
196
+
197
+
198
+ def test_pauli_and_phxz_util_str():
199
+ assert str(_PauliAndZPow(pauli=X)) == '─X──Z**0─'
200
+ assert str(_PauliAndZPow(pauli=X, zpow=Z**0.1)) == '─X──Z**0.1─'
201
+
202
+
203
+ def test_pauli_and_phxz_util_gate_merges():
204
+ """Tests _PauliAndZPow's merge_left() and merge_right()."""
205
+ for left_pauli in [X, Y, Z, I]:
206
+ for right_pauli in [X, Y, Z, I]:
207
+ left = _PauliAndZPow(pauli=left_pauli, zpow=ZPowGate(exponent=0.2))
208
+ right = _PauliAndZPow(pauli=right_pauli, zpow=ZPowGate(exponent=0.6))
209
+ merge1 = right.merge_left(left)
210
+ merge2 = left.merge_right(right)
211
+
212
+ assert np.allclose(
213
+ cirq.unitary(merge1.to_single_qubit_gate()),
214
+ cirq.unitary(merge2.to_single_qubit_gate()),
215
+ )
216
+ q = cirq.LineQubit(0)
217
+ cirq.testing.assert_allclose_up_to_global_phase(
218
+ cirq.unitary(
219
+ cirq.Circuit(
220
+ left.to_single_qubit_gate().on(q), right.to_single_qubit_gate().on(q)
221
+ )
222
+ ),
223
+ cirq.unitary(merge1.to_single_qubit_gate()),
224
+ atol=1e-6,
225
+ )
226
+
227
+
228
+ def test_pauli_and_phxz_util_to_1q_gate():
229
+ """Tests _PauliAndZPow.to_single_qubit_gate()."""
230
+ q = cirq.LineQubit(0)
231
+ for pauli in [cirq.X, cirq.Y, cirq.Z, cirq.I]:
232
+ for zpow in [cirq.ZPowGate(exponent=exp) for exp in [0, 0.1, 0.5, 1, 10.2]]:
233
+ cirq.testing.assert_circuits_have_same_unitary_given_final_permutation(
234
+ cirq.Circuit(pauli(q), zpow(q)),
235
+ cirq.Circuit(_PauliAndZPow(pauli=pauli, zpow=zpow).to_single_qubit_gate().on(q)),
236
+ {q: q},
237
+ )
238
+
239
+
240
+ def test_deep_not_supported():
241
+ with pytest.raises(ValueError, match="GaugeTransformer cannot be used with deep=True"):
242
+ t = CPhaseGaugeTransformerMM()
243
+ t(cirq.Circuit(), context=cirq.TransformerContext(deep=True))
@@ -0,0 +1,127 @@
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
+ """Defines the abstraction for multi-moment gauge compiling as a cirq transformer."""
16
+
17
+ import abc
18
+
19
+ import attrs
20
+ import numpy as np
21
+
22
+ from cirq import circuits, ops
23
+ from cirq.transformers import transformer_api
24
+
25
+
26
+ @transformer_api.transformer
27
+ @attrs.frozen
28
+ class MultiMomentGaugeTransformer(abc.ABC):
29
+ """A gauge transformer that wraps target blocks of moments with single-qubit gates.
30
+
31
+ In detail, a "gauging moment" of single-qubit gates is inserted before a target block of
32
+ moments. These gates are then commuted through the block, resulting in a corresponding
33
+ moment of gates after it.
34
+
35
+ q₀: ... ───LG0───╭───────────╮────RG0───...
36
+ │ │
37
+ q₁: ... ───LG1───┤ moments ├────RG1───...
38
+ │ to be │
39
+ q₂: ... ───LG2───┤ gauged on ├────RG2───...
40
+ │ │
41
+ q₃: ... ───LG3───╰───────────╯────RG3───...
42
+
43
+ Attributes:
44
+ target: The target gate, gate family or gateset, must exist in each of the moment in
45
+ the "moments to be gauged".
46
+ supported_gates: The gates that are supported in the "moments to be gauged".
47
+ """
48
+
49
+ target: ops.GateFamily | ops.Gateset
50
+ supported_gates: ops.GateFamily | ops.Gateset
51
+
52
+ @abc.abstractmethod
53
+ def gauge_on_moments(self, moments_to_gauge: list[circuits.Moment]) -> list[circuits.Moment]:
54
+ """Gauges a block of moments.
55
+
56
+ Args:
57
+ moments_to_gauge: A list of moments to be gauged.
58
+
59
+ Returns:
60
+ A list of moments after gauging.
61
+ """
62
+
63
+ @abc.abstractmethod
64
+ def sample_left_moment(
65
+ self, active_qubits: frozenset[ops.Qid], rng: np.random.Generator
66
+ ) -> circuits.Moment:
67
+ """Samples a random single-qubit moment to be inserted before the target block.
68
+
69
+ Args:
70
+ active_qubits: The qubits on which the sampled gates should be applied.
71
+ rng: A pseudorandom number generator.
72
+
73
+ Returns:
74
+ The sampled moment.
75
+ """
76
+
77
+ def is_target_moment(
78
+ self, moment: circuits.Moment, context: transformer_api.TransformerContext | None = None
79
+ ) -> bool:
80
+ """Checks if a moment is a target for gauging.
81
+
82
+ A moment is a target moment if it contains at least one target op and
83
+ all its operations are supported by this transformer.
84
+ """
85
+ # skip the moment if the moment is tagged to be ignored
86
+ if context and set(moment.tags).intersection(context.tags_to_ignore):
87
+ return False
88
+
89
+ has_target_gates: bool = False
90
+ for op in moment:
91
+ if (
92
+ context
93
+ and isinstance(op, ops.TaggedOperation)
94
+ and set(op.tags).intersection(context.tags_to_ignore)
95
+ ): # skip the moment if the op is tagged to be ignored
96
+ return False
97
+ if op.gate:
98
+ if op in self.target:
99
+ has_target_gates = True
100
+ elif op not in self.supported_gates:
101
+ return False
102
+ return has_target_gates
103
+
104
+ def __call__(
105
+ self,
106
+ circuit: circuits.AbstractCircuit,
107
+ *,
108
+ context: transformer_api.TransformerContext | None = None,
109
+ ) -> circuits.AbstractCircuit:
110
+ if context is None:
111
+ context = transformer_api.TransformerContext(deep=False)
112
+ if context.deep:
113
+ raise ValueError('GaugeTransformer cannot be used with deep=True')
114
+ output_moments: list[circuits.Moment] = []
115
+ moments_to_gauge: list[circuits.Moment] = []
116
+ for moment in circuit:
117
+ if self.is_target_moment(moment, context):
118
+ moments_to_gauge.append(moment)
119
+ else:
120
+ if moments_to_gauge:
121
+ output_moments.extend(self.gauge_on_moments(moments_to_gauge))
122
+ moments_to_gauge.clear()
123
+ output_moments.append(moment)
124
+ if moments_to_gauge:
125
+ output_moments.extend(self.gauge_on_moments(moments_to_gauge))
126
+
127
+ return circuits.Circuit.from_moments(*output_moments)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cirq-core
3
- Version: 1.7.0.dev20250926201022
3
+ Version: 1.7.0.dev20250929235728
4
4
  Summary: A framework for creating, editing, and invoking Noisy Intermediate Scale Quantum (NISQ) circuits.
5
5
  Home-page: http://github.com/quantumlib/cirq
6
6
  Author: The Cirq Developers
@@ -28,10 +28,10 @@ Description-Content-Type: text/markdown
28
28
  License-File: LICENSE
29
29
  Requires-Dist: attrs>=21.3.0
30
30
  Requires-Dist: duet>=0.2.8
31
- Requires-Dist: matplotlib~=3.8
31
+ Requires-Dist: matplotlib~=3.9
32
32
  Requires-Dist: networkx~=3.4
33
- Requires-Dist: numpy>=1.26
34
- Requires-Dist: pandas~=2.1
33
+ Requires-Dist: numpy~=2.0
34
+ Requires-Dist: pandas~=2.2
35
35
  Requires-Dist: sortedcontainers~=2.0
36
36
  Requires-Dist: scipy~=1.12
37
37
  Requires-Dist: sympy
@@ -4,8 +4,8 @@ cirq/_compat_test.py,sha256=emXpdD5ZvwLRlFAoQB8YatmZyU3b4e9jg6FppMTUhkU,33900
4
4
  cirq/_doc.py,sha256=BrnoABo1hk5RgB3Cgww4zLHUfiyFny0F1V-tOMCbdaU,2909
5
5
  cirq/_import.py,sha256=ixBu4EyGl46Ram2cP3p5eZVEFDW5L2DS-VyTjz4N9iw,8429
6
6
  cirq/_import_test.py,sha256=oF4izzOVZLc7NZ0aZHFcGv-r01eiFFt_JORx_x7_D4s,1089
7
- cirq/_version.py,sha256=fjaZ2di0NR7whUNcwGkmF3IOgPG3Wu6l1eD3zeQbTVA,1206
8
- cirq/_version_test.py,sha256=wnUqgraEp8DfxNmFHlL6yecd_SRp3Y3LL-Az55wGXo4,155
7
+ cirq/_version.py,sha256=tIbsr2jWNBuchDuiOv42-52AeR_ck4Ngf3vBiThjAew,1206
8
+ cirq/_version_test.py,sha256=XoAMi49y_VDwNLZRNYzeaG95Ps-6Y2_GLDNjiqvcr8E,155
9
9
  cirq/conftest.py,sha256=wSDKNdIQRDfLnXvOCWD3erheOw8JHRhdfQ53EyTUIXg,1239
10
10
  cirq/json_resolver_cache.py,sha256=A5DIgFAY1hUNt9vai_C3-gGBv24116CJMzQxMcXOax4,13726
11
11
  cirq/py.typed,sha256=VFSlmh_lNwnaXzwY-ZuW-C2Ws5PkuDoVgBdNCs0jXJE,63
@@ -1064,7 +1064,7 @@ cirq/testing/test_data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3
1064
1064
  cirq/testing/test_data/test_module_missing_json_test_data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
1065
1065
  cirq/testing/test_data/test_module_missing_testspec/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
1066
1066
  cirq/testing/test_data/test_module_missing_testspec/json_test_data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
1067
- cirq/transformers/__init__.py,sha256=B4ijV7PR4bN_QBswNqpAehIWTjXuaRMeyccrWz4Gw4w,7285
1067
+ cirq/transformers/__init__.py,sha256=6noA2FZMgzwYorHZuyi1aMB8mQzohE2FIdNxbNxMLsM,7343
1068
1068
  cirq/transformers/align.py,sha256=95iI2sIil7V02hRPaXB-wG_eiMb5yF6ffUZU3fHmPP4,3341
1069
1069
  cirq/transformers/align_test.py,sha256=X4ysJuemqqOeKix2rO9SlwF4CBQzEYbgiqgZmlMxbsQ,7722
1070
1070
  cirq/transformers/drop_empty_moments.py,sha256=uZJG9FpUNyA1Mi0xLDuVuhj_siZhPZ1_s08Ry9xQ-1M,1535
@@ -1134,7 +1134,7 @@ cirq/transformers/analytical_decompositions/two_qubit_to_ms.py,sha256=dP9umZJBgN
1134
1134
  cirq/transformers/analytical_decompositions/two_qubit_to_ms_test.py,sha256=Cj_GZvJykt5NfNuB8vEY30DE2tU3nJtnUztAArgnfE4,4204
1135
1135
  cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap.py,sha256=s08m1PJODNUNzNNkn_zu2qasRSWmXJAq8Tb9cHKk-yU,25348
1136
1136
  cirq/transformers/analytical_decompositions/two_qubit_to_sqrt_iswap_test.py,sha256=WfPQA_wTpRknovNenxC1LPAt9cVHqwdRhUhPZ8sLNr0,20655
1137
- cirq/transformers/gauge_compiling/__init__.py,sha256=T1IaBKgf2GgVbozsHun7lJhdypasX9olQVh9eYhY7gk,1670
1137
+ cirq/transformers/gauge_compiling/__init__.py,sha256=AoDneer0nUDmvlK4SYaWrcSAOZyJr_EhgSe7E2WN8hg,1949
1138
1138
  cirq/transformers/gauge_compiling/cphase_gauge.py,sha256=EoM_TKZt8mJwYFQAfv3rviitXWvGT8I5N36droPWPCE,5576
1139
1139
  cirq/transformers/gauge_compiling/cphase_gauge_test.py,sha256=dPV2vqsyC-eUi_jmwEk6dhOKHnQLJ_A01_Emxw2j8QQ,1427
1140
1140
  cirq/transformers/gauge_compiling/cz_gauge.py,sha256=dtcC49-qIvH_hRaQpQLBvGu-3323r4cwWpFImBnDebE,2586
@@ -1147,6 +1147,9 @@ cirq/transformers/gauge_compiling/idle_moments_gauge.py,sha256=9NVZMXTgcEQN-AmT_
1147
1147
  cirq/transformers/gauge_compiling/idle_moments_gauge_test.py,sha256=OSb0840o0M8Qpde_Dp3-sRCGrJCO4rBgArDLnnT8D-g,6903
1148
1148
  cirq/transformers/gauge_compiling/iswap_gauge.py,sha256=CfW3hgO6AgUB7D6tC8J2XZQw2Ge77LT44BygCzMW4Xc,3536
1149
1149
  cirq/transformers/gauge_compiling/iswap_gauge_test.py,sha256=V6g-jyGujMKEzGtOi_OhMxX5oTznGXJi9tCNKI9Qrb8,901
1150
+ cirq/transformers/gauge_compiling/multi_moment_cphase_gauge.py,sha256=cx25fzPF77PhSDMzAQUbSW-5TJ81ziKyuZtUl3SrGck,10516
1151
+ cirq/transformers/gauge_compiling/multi_moment_cphase_gauge_test.py,sha256=JoFXYc34acy05HIh1POOq636NZ5f6Q9FH4WmJ5TqsPY,11636
1152
+ cirq/transformers/gauge_compiling/multi_moment_gauge_compiling.py,sha256=vrbZ6y0HtGJ6vwiew1Uwr9joQuIgL1NVUpnUTWtQNMg,4886
1150
1153
  cirq/transformers/gauge_compiling/spin_inversion_gauge.py,sha256=yhrF4pa1u0-iwYay47_2bZ4xfU323TOdlyazl0U9v4c,1122
1151
1154
  cirq/transformers/gauge_compiling/spin_inversion_gauge_test.py,sha256=FJO8BoP4uA0SqSLXS6bqn3T69SwcBHCQHBwWAkI8YTk,1328
1152
1155
  cirq/transformers/gauge_compiling/sqrt_cz_gauge.py,sha256=qnVmbXqehhDucg6Cm3VZm5lHez-uttayPSHqL4JHPEA,2557
@@ -1236,8 +1239,8 @@ cirq/work/sampler.py,sha256=rxbMWvrhu3gfNSBjZKozw28lLKVvBAS_1EGyPdYe8Xg,19041
1236
1239
  cirq/work/sampler_test.py,sha256=SsMrRvLDYELyOAWLKISjkdEfrBwLYWRsT6D8WrsLM3Q,13533
1237
1240
  cirq/work/zeros_sampler.py,sha256=Fs2JWwq0n9zv7_G5Rm-9vPeHUag7uctcMOHg0JTkZpc,2371
1238
1241
  cirq/work/zeros_sampler_test.py,sha256=lQLgQDGBLtfImryys2HzQ2jOSGxHgc7-koVBUhv8qYk,3345
1239
- cirq_core-1.7.0.dev20250926201022.dist-info/licenses/LICENSE,sha256=tAkwu8-AdEyGxGoSvJ2gVmQdcicWw3j1ZZueVV74M-E,11357
1240
- cirq_core-1.7.0.dev20250926201022.dist-info/METADATA,sha256=9lwWfHkvg09FMfdzii9_T47nvQEsD_YFnEANCE33BeY,4758
1241
- cirq_core-1.7.0.dev20250926201022.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
1242
- cirq_core-1.7.0.dev20250926201022.dist-info/top_level.txt,sha256=Sz9iOxHU0IEMLSFGwiwOCaN2e9K-jFbBbtpPN1hB73g,5
1243
- cirq_core-1.7.0.dev20250926201022.dist-info/RECORD,,
1242
+ cirq_core-1.7.0.dev20250929235728.dist-info/licenses/LICENSE,sha256=tAkwu8-AdEyGxGoSvJ2gVmQdcicWw3j1ZZueVV74M-E,11357
1243
+ cirq_core-1.7.0.dev20250929235728.dist-info/METADATA,sha256=7NdO_83x7NpEADFQaR3zWYeUd_C8rWPE320PK5llZPI,4757
1244
+ cirq_core-1.7.0.dev20250929235728.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
1245
+ cirq_core-1.7.0.dev20250929235728.dist-info/top_level.txt,sha256=Sz9iOxHU0IEMLSFGwiwOCaN2e9K-jFbBbtpPN1hB73g,5
1246
+ cirq_core-1.7.0.dev20250929235728.dist-info/RECORD,,