|
| 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 pyo3::exceptions::PyValueError; |
| 14 | +use pyo3::prelude::PyModule; |
| 15 | +use pyo3::{pyfunction, pymodule, wrap_pyfunction, Bound, PyResult, Python}; |
| 16 | +use qiskit_circuit::Qubit; |
| 17 | + |
| 18 | +use crate::commutation_checker::CommutationChecker; |
| 19 | +use hashbrown::HashMap; |
| 20 | +use pyo3::prelude::*; |
| 21 | + |
| 22 | +use pyo3::types::{PyDict, PyList}; |
| 23 | +use qiskit_circuit::dag_circuit::{DAGCircuit, NodeType, Wire}; |
| 24 | +use rustworkx_core::petgraph::stable_graph::NodeIndex; |
| 25 | + |
| 26 | +// Custom types to store the commutation sets and node indices, |
| 27 | +// see the docstring below for more information. |
| 28 | +type CommutationSet = HashMap<Wire, Vec<Vec<NodeIndex>>>; |
| 29 | +type NodeIndices = HashMap<(NodeIndex, Wire), usize>; |
| 30 | + |
| 31 | +// the maximum number of qubits we check commutativity for |
| 32 | +const MAX_NUM_QUBITS: u32 = 3; |
| 33 | + |
| 34 | +/// Compute the commutation sets for a given DAG. |
| 35 | +/// |
| 36 | +/// We return two HashMaps: |
| 37 | +/// * {wire: commutation_sets}: For each wire, we keep a vector of index sets, where each index |
| 38 | +/// set contains mutually commuting nodes. Note that these include the input and output nodes |
| 39 | +/// which do not commute with anything. |
| 40 | +/// * {(node, wire): index}: For each (node, wire) pair we store the index indicating in which |
| 41 | +/// commutation set the node appears on a given wire. |
| 42 | +/// |
| 43 | +/// For example, if we have a circuit |
| 44 | +/// |
| 45 | +/// |0> -- X -- SX -- Z (out) |
| 46 | +/// 0 2 3 4 1 <-- node indices including input (0) and output (1) nodes |
| 47 | +/// |
| 48 | +/// Then we would have |
| 49 | +/// |
| 50 | +/// commutation_set = {0: [[0], [2, 3], [4], [1]]} |
| 51 | +/// node_indices = {(0, 0): 0, (1, 0): 3, (2, 0): 1, (3, 0): 1, (4, 0): 2} |
| 52 | +/// |
| 53 | +fn analyze_commutations_inner( |
| 54 | + py: Python, |
| 55 | + dag: &mut DAGCircuit, |
| 56 | + commutation_checker: &mut CommutationChecker, |
| 57 | +) -> PyResult<(CommutationSet, NodeIndices)> { |
| 58 | + let mut commutation_set: CommutationSet = HashMap::new(); |
| 59 | + let mut node_indices: NodeIndices = HashMap::new(); |
| 60 | + |
| 61 | + for qubit in 0..dag.num_qubits() { |
| 62 | + let wire = Wire::Qubit(Qubit(qubit as u32)); |
| 63 | + |
| 64 | + for current_gate_idx in dag.nodes_on_wire(py, &wire, false) { |
| 65 | + // get the commutation set associated with the current wire, or create a new |
| 66 | + // index set containing the current gate |
| 67 | + let commutation_entry = commutation_set |
| 68 | + .entry(wire.clone()) |
| 69 | + .or_insert_with(|| vec![vec![current_gate_idx]]); |
| 70 | + |
| 71 | + // we can unwrap as we know the commutation entry has at least one element |
| 72 | + let last = commutation_entry.last_mut().unwrap(); |
| 73 | + |
| 74 | + // if the current gate index is not in the set, check whether it commutes with |
| 75 | + // the previous nodes -- if yes, add it to the commutation set |
| 76 | + if !last.contains(¤t_gate_idx) { |
| 77 | + let mut all_commute = true; |
| 78 | + |
| 79 | + for prev_gate_idx in last.iter() { |
| 80 | + // if the node is an input/output node, they do not commute, so we only |
| 81 | + // continue if the nodes are operation nodes |
| 82 | + if let (NodeType::Operation(packed_inst0), NodeType::Operation(packed_inst1)) = |
| 83 | + (&dag.dag[current_gate_idx], &dag.dag[*prev_gate_idx]) |
| 84 | + { |
| 85 | + let op1 = packed_inst0.op.view(); |
| 86 | + let op2 = packed_inst1.op.view(); |
| 87 | + let params1 = packed_inst0.params_view(); |
| 88 | + let params2 = packed_inst1.params_view(); |
| 89 | + let qargs1 = dag.get_qargs(packed_inst0.qubits); |
| 90 | + let qargs2 = dag.get_qargs(packed_inst1.qubits); |
| 91 | + let cargs1 = dag.get_cargs(packed_inst0.clbits); |
| 92 | + let cargs2 = dag.get_cargs(packed_inst1.clbits); |
| 93 | + |
| 94 | + all_commute = commutation_checker.commute_inner( |
| 95 | + py, |
| 96 | + &op1, |
| 97 | + params1, |
| 98 | + packed_inst0.extra_attrs.as_deref(), |
| 99 | + qargs1, |
| 100 | + cargs1, |
| 101 | + &op2, |
| 102 | + params2, |
| 103 | + packed_inst1.extra_attrs.as_deref(), |
| 104 | + qargs2, |
| 105 | + cargs2, |
| 106 | + MAX_NUM_QUBITS, |
| 107 | + )?; |
| 108 | + if !all_commute { |
| 109 | + break; |
| 110 | + } |
| 111 | + } else { |
| 112 | + all_commute = false; |
| 113 | + break; |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + if all_commute { |
| 118 | + // all commute, add to current list |
| 119 | + last.push(current_gate_idx); |
| 120 | + } else { |
| 121 | + // does not commute, create new list |
| 122 | + commutation_entry.push(vec![current_gate_idx]); |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + node_indices.insert( |
| 127 | + (current_gate_idx, wire.clone()), |
| 128 | + commutation_entry.len() - 1, |
| 129 | + ); |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + Ok((commutation_set, node_indices)) |
| 134 | +} |
| 135 | + |
| 136 | +#[pyfunction] |
| 137 | +#[pyo3(signature = (dag, commutation_checker))] |
| 138 | +pub(crate) fn analyze_commutations( |
| 139 | + py: Python, |
| 140 | + dag: &mut DAGCircuit, |
| 141 | + commutation_checker: &mut CommutationChecker, |
| 142 | +) -> PyResult<Py<PyDict>> { |
| 143 | + // This returns two HashMaps: |
| 144 | + // * The commuting nodes per wire: {wire: [commuting_nodes_1, commuting_nodes_2, ...]} |
| 145 | + // * The index in which commutation set a given node is located on a wire: {(node, wire): index} |
| 146 | + // The Python dict will store both of these dictionaries in one. |
| 147 | + let (commutation_set, node_indices) = analyze_commutations_inner(py, dag, commutation_checker)?; |
| 148 | + |
| 149 | + let out_dict = PyDict::new_bound(py); |
| 150 | + |
| 151 | + // First set the {wire: [commuting_nodes_1, ...]} bit |
| 152 | + for (wire, commutations) in commutation_set { |
| 153 | + // we know all wires are of type Wire::Qubit, since in analyze_commutations_inner |
| 154 | + // we only iterater over the qubits |
| 155 | + let py_wire = match wire { |
| 156 | + Wire::Qubit(q) => dag.qubits.get(q).unwrap().to_object(py), |
| 157 | + _ => return Err(PyValueError::new_err("Unexpected wire type.")), |
| 158 | + }; |
| 159 | + |
| 160 | + out_dict.set_item( |
| 161 | + py_wire, |
| 162 | + PyList::new_bound( |
| 163 | + py, |
| 164 | + commutations.iter().map(|inner| { |
| 165 | + PyList::new_bound( |
| 166 | + py, |
| 167 | + inner |
| 168 | + .iter() |
| 169 | + .map(|node_index| dag.get_node(py, *node_index).unwrap()), |
| 170 | + ) |
| 171 | + }), |
| 172 | + ), |
| 173 | + )?; |
| 174 | + } |
| 175 | + |
| 176 | + // Then we add the {(node, wire): index} dictionary |
| 177 | + for ((node_index, wire), index) in node_indices { |
| 178 | + let py_wire = match wire { |
| 179 | + Wire::Qubit(q) => dag.qubits.get(q).unwrap().to_object(py), |
| 180 | + _ => return Err(PyValueError::new_err("Unexpected wire type.")), |
| 181 | + }; |
| 182 | + out_dict.set_item((dag.get_node(py, node_index)?, py_wire), index)?; |
| 183 | + } |
| 184 | + |
| 185 | + Ok(out_dict.unbind()) |
| 186 | +} |
| 187 | + |
| 188 | +#[pymodule] |
| 189 | +pub fn commutation_analysis(m: &Bound<PyModule>) -> PyResult<()> { |
| 190 | + m.add_wrapped(wrap_pyfunction!(analyze_commutations))?; |
| 191 | + Ok(()) |
| 192 | +} |
0 commit comments