|
| 1 | +// This code is part of Qiskit. |
| 2 | +// |
| 3 | +// (C) Copyright IBM 2024 |
| 4 | +// |
| 5 | +// This code is licensed under the Apache License, Version 2.0. You may |
| 6 | +// obtain a copy of this license in the LICENSE.txt file in the root directory |
| 7 | +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. |
| 8 | +// |
| 9 | +// Any modifications or derivative works of this code must retain this |
| 10 | +// copyright notice, and modified files need to carry a notice indicating |
| 11 | +// that they have been altered from the originals. |
| 12 | + |
| 13 | +use std::f64::consts::PI; |
| 14 | + |
| 15 | +use hashbrown::{HashMap, HashSet}; |
| 16 | +use pyo3::exceptions::PyRuntimeError; |
| 17 | +use pyo3::prelude::*; |
| 18 | +use pyo3::{pyfunction, pymodule, wrap_pyfunction, Bound, PyResult, Python}; |
| 19 | +use rustworkx_core::petgraph::stable_graph::NodeIndex; |
| 20 | +use smallvec::{smallvec, SmallVec}; |
| 21 | + |
| 22 | +use qiskit_circuit::dag_circuit::{DAGCircuit, NodeType, Wire}; |
| 23 | +use qiskit_circuit::operations::StandardGate::{ |
| 24 | + CXGate, CYGate, CZGate, HGate, PhaseGate, RXGate, RZGate, SGate, TGate, U1Gate, XGate, YGate, |
| 25 | + ZGate, |
| 26 | +}; |
| 27 | +use qiskit_circuit::operations::{Operation, Param, StandardGate}; |
| 28 | +use qiskit_circuit::Qubit; |
| 29 | + |
| 30 | +use crate::commutation_analysis::analyze_commutations_inner; |
| 31 | +use crate::commutation_checker::CommutationChecker; |
| 32 | +use crate::{euler_one_qubit_decomposer, QiskitError}; |
| 33 | + |
| 34 | +const _CUTOFF_PRECISION: f64 = 1e-5; |
| 35 | +static ROTATION_GATES: [&str; 4] = ["p", "u1", "rz", "rx"]; |
| 36 | +static HALF_TURNS: [&str; 2] = ["z", "x"]; |
| 37 | +static QUARTER_TURNS: [&str; 1] = ["s"]; |
| 38 | +static EIGHTH_TURNS: [&str; 1] = ["t"]; |
| 39 | + |
| 40 | +static VAR_Z_MAP: [(&str, StandardGate); 3] = [("rz", RZGate), ("p", PhaseGate), ("u1", U1Gate)]; |
| 41 | +static Z_ROTATIONS: [StandardGate; 6] = [PhaseGate, ZGate, U1Gate, RZGate, TGate, SGate]; |
| 42 | +static X_ROTATIONS: [StandardGate; 2] = [XGate, RXGate]; |
| 43 | +static SUPPORTED_GATES: [StandardGate; 5] = [CXGate, CYGate, CZGate, HGate, YGate]; |
| 44 | + |
| 45 | +#[derive(Hash, Eq, PartialEq, Debug)] |
| 46 | +enum GateOrRotation { |
| 47 | + Gate(StandardGate), |
| 48 | + ZRotation, |
| 49 | + XRotation, |
| 50 | +} |
| 51 | +#[derive(Hash, Eq, PartialEq, Debug)] |
| 52 | +struct CancellationSetKey { |
| 53 | + gate: GateOrRotation, |
| 54 | + qubits: SmallVec<[Qubit; 2]>, |
| 55 | + com_set_index: usize, |
| 56 | + second_index: Option<usize>, |
| 57 | +} |
| 58 | + |
| 59 | +#[pyfunction] |
| 60 | +#[pyo3(signature = (dag, commutation_checker, basis_gates=None))] |
| 61 | +pub(crate) fn cancel_commutations( |
| 62 | + py: Python, |
| 63 | + dag: &mut DAGCircuit, |
| 64 | + commutation_checker: &mut CommutationChecker, |
| 65 | + basis_gates: Option<HashSet<String>>, |
| 66 | +) -> PyResult<()> { |
| 67 | + let basis: HashSet<String> = if let Some(basis) = basis_gates { |
| 68 | + basis |
| 69 | + } else { |
| 70 | + HashSet::new() |
| 71 | + }; |
| 72 | + let z_var_gate = dag |
| 73 | + .get_op_counts() |
| 74 | + .keys() |
| 75 | + .find_map(|g| { |
| 76 | + VAR_Z_MAP |
| 77 | + .iter() |
| 78 | + .find(|(key, _)| *key == g.as_str()) |
| 79 | + .map(|(_, gate)| gate) |
| 80 | + }) |
| 81 | + .or_else(|| { |
| 82 | + basis.iter().find_map(|g| { |
| 83 | + VAR_Z_MAP |
| 84 | + .iter() |
| 85 | + .find(|(key, _)| *key == g.as_str()) |
| 86 | + .map(|(_, gate)| gate) |
| 87 | + }) |
| 88 | + }); |
| 89 | + // Fallback to the first matching key from basis if there is no match in dag.op_names |
| 90 | + |
| 91 | + // Gate sets to be cancelled |
| 92 | + /* Traverse each qubit to generate the cancel dictionaries |
| 93 | + Cancel dictionaries: |
| 94 | + - For 1-qubit gates the key is (gate_type, qubit_id, commutation_set_id), |
| 95 | + the value is the list of gates that share the same gate type, qubit, commutation set. |
| 96 | + - For 2qbit gates the key: (gate_type, first_qbit, sec_qbit, first commutation_set_id, |
| 97 | + sec_commutation_set_id), the value is the list gates that share the same gate type, |
| 98 | + qubits and commutation sets. |
| 99 | + */ |
| 100 | + let (commutation_set, node_indices) = analyze_commutations_inner(py, dag, commutation_checker)?; |
| 101 | + let mut cancellation_sets: HashMap<CancellationSetKey, Vec<NodeIndex>> = HashMap::new(); |
| 102 | + |
| 103 | + (0..dag.num_qubits() as u32).for_each(|qubit| { |
| 104 | + let wire = Qubit(qubit); |
| 105 | + if let Some(wire_commutation_set) = commutation_set.get(&Wire::Qubit(wire)) { |
| 106 | + for (com_set_idx, com_set) in wire_commutation_set.iter().enumerate() { |
| 107 | + if let Some(&nd) = com_set.first() { |
| 108 | + if !matches!(dag.dag[nd], NodeType::Operation(_)) { |
| 109 | + continue; |
| 110 | + } |
| 111 | + } else { |
| 112 | + continue; |
| 113 | + } |
| 114 | + for node in com_set.iter() { |
| 115 | + let instr = match &dag.dag[*node] { |
| 116 | + NodeType::Operation(instr) => instr, |
| 117 | + _ => panic!("Unexpected type in commutation set."), |
| 118 | + }; |
| 119 | + let num_qargs = dag.get_qargs(instr.qubits).len(); |
| 120 | + // no support for cancellation of parameterized gates |
| 121 | + if instr.is_parameterized() { |
| 122 | + continue; |
| 123 | + } |
| 124 | + if let Some(op_gate) = instr.op.try_standard_gate() { |
| 125 | + if num_qargs == 1 && SUPPORTED_GATES.contains(&op_gate) { |
| 126 | + cancellation_sets |
| 127 | + .entry(CancellationSetKey { |
| 128 | + gate: GateOrRotation::Gate(op_gate), |
| 129 | + qubits: smallvec![wire], |
| 130 | + com_set_index: com_set_idx, |
| 131 | + second_index: None, |
| 132 | + }) |
| 133 | + .or_insert_with(Vec::new) |
| 134 | + .push(*node); |
| 135 | + } |
| 136 | + |
| 137 | + if num_qargs == 1 && Z_ROTATIONS.contains(&op_gate) { |
| 138 | + cancellation_sets |
| 139 | + .entry(CancellationSetKey { |
| 140 | + gate: GateOrRotation::ZRotation, |
| 141 | + qubits: smallvec![wire], |
| 142 | + com_set_index: com_set_idx, |
| 143 | + second_index: None, |
| 144 | + }) |
| 145 | + .or_insert_with(Vec::new) |
| 146 | + .push(*node); |
| 147 | + } |
| 148 | + if num_qargs == 1 && X_ROTATIONS.contains(&op_gate) { |
| 149 | + cancellation_sets |
| 150 | + .entry(CancellationSetKey { |
| 151 | + gate: GateOrRotation::XRotation, |
| 152 | + qubits: smallvec![wire], |
| 153 | + com_set_index: com_set_idx, |
| 154 | + second_index: None, |
| 155 | + }) |
| 156 | + .or_insert_with(Vec::new) |
| 157 | + .push(*node); |
| 158 | + } |
| 159 | + // Don't deal with Y rotation, because Y rotation doesn't commute with |
| 160 | + // CNOT, so it should be dealt with by optimized1qgate pass |
| 161 | + if num_qargs == 2 && dag.get_qargs(instr.qubits)[0] == wire { |
| 162 | + let second_qarg = dag.get_qargs(instr.qubits)[1]; |
| 163 | + cancellation_sets |
| 164 | + .entry(CancellationSetKey { |
| 165 | + gate: GateOrRotation::Gate(op_gate), |
| 166 | + qubits: smallvec![wire, second_qarg], |
| 167 | + com_set_index: com_set_idx, |
| 168 | + second_index: node_indices |
| 169 | + .get(&(*node, Wire::Qubit(second_qarg))) |
| 170 | + .copied(), |
| 171 | + }) |
| 172 | + .or_insert_with(Vec::new) |
| 173 | + .push(*node); |
| 174 | + } |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | + } |
| 179 | + }); |
| 180 | + |
| 181 | + for (cancel_key, cancel_set) in &cancellation_sets { |
| 182 | + if cancel_set.len() > 1 { |
| 183 | + if let GateOrRotation::Gate(g) = cancel_key.gate { |
| 184 | + if SUPPORTED_GATES.contains(&g) { |
| 185 | + for &c_node in &cancel_set[0..(cancel_set.len() / 2) * 2] { |
| 186 | + dag.remove_op_node(c_node); |
| 187 | + } |
| 188 | + } |
| 189 | + continue; |
| 190 | + } |
| 191 | + if matches!(cancel_key.gate, GateOrRotation::ZRotation) && z_var_gate.is_none() { |
| 192 | + continue; |
| 193 | + } |
| 194 | + if matches!( |
| 195 | + cancel_key.gate, |
| 196 | + GateOrRotation::ZRotation | GateOrRotation::XRotation |
| 197 | + ) { |
| 198 | + let mut total_angle: f64 = 0.0; |
| 199 | + let mut total_phase: f64 = 0.0; |
| 200 | + for current_node in cancel_set { |
| 201 | + let node_op = match &dag.dag[*current_node] { |
| 202 | + NodeType::Operation(instr) => instr, |
| 203 | + _ => panic!("Unexpected type in commutation set run."), |
| 204 | + }; |
| 205 | + let node_op_name = node_op.op.name(); |
| 206 | + |
| 207 | + let node_angle = if ROTATION_GATES.contains(&node_op_name) { |
| 208 | + match node_op.params_view().first() { |
| 209 | + Some(Param::Float(f)) => Ok(*f), |
| 210 | + _ => return Err(QiskitError::new_err(format!( |
| 211 | + "Rotational gate with parameter expression encountered in cancellation {:?}", |
| 212 | + node_op.op |
| 213 | + ))) |
| 214 | + } |
| 215 | + } else if HALF_TURNS.contains(&node_op_name) { |
| 216 | + Ok(PI) |
| 217 | + } else if QUARTER_TURNS.contains(&node_op_name) { |
| 218 | + Ok(PI / 2.0) |
| 219 | + } else if EIGHTH_TURNS.contains(&node_op_name) { |
| 220 | + Ok(PI / 4.0) |
| 221 | + } else { |
| 222 | + Err(PyRuntimeError::new_err(format!( |
| 223 | + "Angle for operation {} is not defined", |
| 224 | + node_op_name |
| 225 | + ))) |
| 226 | + }; |
| 227 | + total_angle += node_angle?; |
| 228 | + |
| 229 | + let Param::Float(new_phase) = node_op |
| 230 | + .op |
| 231 | + .definition(node_op.params_view()) |
| 232 | + .unwrap() |
| 233 | + .global_phase() |
| 234 | + .clone() |
| 235 | + else { |
| 236 | + unreachable!() |
| 237 | + }; |
| 238 | + total_phase += new_phase |
| 239 | + } |
| 240 | + |
| 241 | + let new_op = match cancel_key.gate { |
| 242 | + GateOrRotation::ZRotation => z_var_gate.unwrap(), |
| 243 | + GateOrRotation::XRotation => &RXGate, |
| 244 | + _ => unreachable!(), |
| 245 | + }; |
| 246 | + |
| 247 | + let gate_angle = euler_one_qubit_decomposer::mod_2pi(total_angle, 0.); |
| 248 | + |
| 249 | + let new_op_phase: f64 = if gate_angle.abs() > _CUTOFF_PRECISION { |
| 250 | + dag.insert_1q_on_incoming_qubit((*new_op, &[total_angle]), cancel_set[0]); |
| 251 | + let Param::Float(new_phase) = new_op |
| 252 | + .definition(&[Param::Float(total_angle)]) |
| 253 | + .unwrap() |
| 254 | + .global_phase() |
| 255 | + .clone() |
| 256 | + else { |
| 257 | + unreachable!(); |
| 258 | + }; |
| 259 | + new_phase |
| 260 | + } else { |
| 261 | + 0.0 |
| 262 | + }; |
| 263 | + |
| 264 | + dag.add_global_phase(py, &Param::Float(total_phase - new_op_phase))?; |
| 265 | + |
| 266 | + for node in cancel_set { |
| 267 | + dag.remove_op_node(*node); |
| 268 | + } |
| 269 | + } |
| 270 | + } |
| 271 | + } |
| 272 | + |
| 273 | + Ok(()) |
| 274 | +} |
| 275 | + |
| 276 | +#[pymodule] |
| 277 | +pub fn commutation_cancellation(m: &Bound<PyModule>) -> PyResult<()> { |
| 278 | + m.add_wrapped(wrap_pyfunction!(cancel_commutations))?; |
| 279 | + Ok(()) |
| 280 | +} |
0 commit comments