Cirq
Cirq copied to clipboard
Add drop_diagonal_before_measurement transformer
Description
Implemented the drop_diagonal_before_measurement transformer as requested in #4935.
This transformer identifies diagonal gates (Z, S, T, CZ, etc.) that are immediately followed by measurements. Since diagonal gates commute with the computational basis measurement, they can be removed without affecting the outcome probabilities.
Implementation Details:
- Pre-processing: Runs
eject_zfirst to push Z gates as far right as possible (handling the Z-CZ commutation case described in the issue). - Safety Logic: Uses strict safety checks. A diagonal gate is only removed if ALL qubits it acts on are being measured.
- Example:
CZ(q0, q1)followed byMeasure(q0)is NOT removed (to preserveq1's phase). - Example:
CZ(q0, q1)followed byMeasure(q0), Measure(q1)IS removed.
- Example:
Testing:
Added diagonal_optimization_test.py covering:
- Single qubit removal (Z, S chains).
- Multi-qubit safety (CZ removal vs retention).
- Commutation blocking (Z blocked by X).
- The specific use cases mentioned in the issue.
Fixes: #4935