Skip to content

Commit

Permalink
remove partial CZs if allow_partial_czs=False (#6436)
Browse files Browse the repository at this point in the history
  • Loading branch information
NoureldinYosri authored Feb 2, 2024
1 parent 9f07ce8 commit e9e12ee
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,24 @@
import cirq


def _remove_partial_czs_or_fail(
operations: Iterable['cirq.Operation'], atol: float
) -> List['cirq.Operation']:
result = []
for op in operations:
if isinstance(op.gate, ops.CZPowGate):
t = op.gate.exponent % 2 # CZ^t is periodic with period 2.
if t < atol:
continue # Identity.
elif abs(t - 1) < atol:
result.append(ops.CZ(*op.qubits)) # Was either CZ or CZ**-1.
else:
raise ValueError(f'CZ^t is not allowed for t={t}')
else:
result.append(op)
return result


def two_qubit_matrix_to_cz_operations(
q0: 'cirq.Qid',
q1: 'cirq.Qid',
Expand All @@ -53,10 +71,16 @@ def two_qubit_matrix_to_cz_operations(
Returns:
A list of operations implementing the matrix.
Raises:
ValueError: If allow_partial_czs=False and the matrix requires partial CZs.
"""
kak = linalg.kak_decomposition(mat, atol=atol)
operations = _kak_decomposition_to_operations(q0, q1, kak, allow_partial_czs, atol=atol)
if clean_operations:
if not allow_partial_czs:
# CZ^t is not allowed for any $t$ except $t=1$.
return _remove_partial_czs_or_fail(cleanup_operations(operations), atol=atol)
return cleanup_operations(operations)
return operations

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,3 +257,20 @@ def test_decompose_to_diagonal_and_circuit(v):
combined_circuit = cirq.Circuit(cirq.MatrixGate(diagonal)(b, c), ops)
circuit_unitary = combined_circuit.unitary(qubits_that_should_be_present=[b, c])
cirq.testing.assert_allclose_up_to_global_phase(circuit_unitary, v, atol=2e-6)


def test_remove_partial_czs_or_fail():
CZ = cirq.CZ(*cirq.LineQubit.range(2))
assert (
cirq.transformers.analytical_decompositions.two_qubit_to_cz._remove_partial_czs_or_fail(
[CZ**1e-15], atol=1e-9
)
== []
)
assert cirq.transformers.analytical_decompositions.two_qubit_to_cz._remove_partial_czs_or_fail(
[CZ**-1, CZ], atol=1e-9
) == [CZ, CZ]
with pytest.raises(ValueError):
_ = cirq.transformers.analytical_decompositions.two_qubit_to_cz._remove_partial_czs_or_fail(
[CZ**-0.5], atol=1e-9
)

0 comments on commit e9e12ee

Please sign in to comment.