From 832bd9f40e5e8edfd2ec7ea51446494767f4a79c Mon Sep 17 00:00:00 2001 From: Tanuj Khattar Date: Wed, 28 Jun 2023 16:28:23 -0700 Subject: [PATCH 1/2] Speed up execution time of merge_single_qubit_moments_to_phxz transformer by avoiding redundant calls to unitary --- .../transformers/merge_single_qubit_gates.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/cirq-core/cirq/transformers/merge_single_qubit_gates.py b/cirq-core/cirq/transformers/merge_single_qubit_gates.py index 1b41ae95859..85adcbb722d 100644 --- a/cirq-core/cirq/transformers/merge_single_qubit_gates.py +++ b/cirq-core/cirq/transformers/merge_single_qubit_gates.py @@ -127,10 +127,20 @@ def merge_func(m1: 'cirq.Moment', m2: 'cirq.Moment') -> Optional['cirq.Moment']: return None ret_ops = [] for q in m1.qubits | m2.qubits: - mat = protocols.unitary(circuits.Circuit(m.operation_at(q) or [] for m in [m1, m2])) - gate = single_qubit_decompositions.single_qubit_matrix_to_phxz(mat, atol) - if gate: + op1, op2 = m1.operation_at(q), m2.operation_at(q) + if op1 and op2: + mat = protocols.unitary(op2) @ protocols.unitary(op1) + gate = single_qubit_decompositions.single_qubit_matrix_to_phxz(mat, atol) ret_ops.append(gate(q)) + else: + op = op1 or op2 + if isinstance(op.gate, ops.PhasedXZGate): + ret_ops.append(op) + else: + gate = single_qubit_decompositions.single_qubit_matrix_to_phxz( + protocols.unitary(op), atol + ) + ret_ops.append(gate(q)) return circuits.Moment(ret_ops) return transformer_primitives.merge_moments( From d2760e639dd330f7085f73f57f01532a7139a599 Mon Sep 17 00:00:00 2001 From: Tanuj Khattar Date: Wed, 28 Jun 2023 16:36:22 -0700 Subject: [PATCH 2/2] Fix mypy errors --- cirq-core/cirq/transformers/merge_single_qubit_gates.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cirq-core/cirq/transformers/merge_single_qubit_gates.py b/cirq-core/cirq/transformers/merge_single_qubit_gates.py index 85adcbb722d..4b4af561e5a 100644 --- a/cirq-core/cirq/transformers/merge_single_qubit_gates.py +++ b/cirq-core/cirq/transformers/merge_single_qubit_gates.py @@ -131,16 +131,19 @@ def merge_func(m1: 'cirq.Moment', m2: 'cirq.Moment') -> Optional['cirq.Moment']: if op1 and op2: mat = protocols.unitary(op2) @ protocols.unitary(op1) gate = single_qubit_decompositions.single_qubit_matrix_to_phxz(mat, atol) - ret_ops.append(gate(q)) + if gate: + ret_ops.append(gate(q)) else: op = op1 or op2 + assert op is not None if isinstance(op.gate, ops.PhasedXZGate): ret_ops.append(op) else: gate = single_qubit_decompositions.single_qubit_matrix_to_phxz( protocols.unitary(op), atol ) - ret_ops.append(gate(q)) + if gate: + ret_ops.append(gate(q)) return circuits.Moment(ret_ops) return transformer_primitives.merge_moments(