Skip to content

Commit

Permalink
Tweak control_flow_op_nodes() method to avoid dag traversal when not …
Browse files Browse the repository at this point in the history
…necessary
  • Loading branch information
mtreinish committed Aug 23, 2024
1 parent 317a057 commit 2c0aad5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 18 deletions.
38 changes: 24 additions & 14 deletions crates/circuit/src/dag_circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3923,21 +3923,31 @@ def _format(operand):
/// Get a list of "op" nodes in the dag that contain control flow instructions.
///
/// Returns:
/// list[DAGOpNode]: The list of dag nodes containing control flow ops.
fn control_flow_op_nodes(&self, py: Python) -> PyResult<Vec<Py<PyAny>>> {
self.dag
.node_references()
.filter_map(|(node_index, node_type)| match node_type {
NodeType::Operation(ref node) => {
if node.op.control_flow() {
Some(self.unpack_into(py, node_index, node_type))
} else {
None
/// list[DAGOpNode] | None: The list of dag nodes containing control flow ops. If there
/// are no control flow nodes None is returned
fn control_flow_op_nodes(&self, py: Python) -> PyResult<Option<Vec<Py<PyAny>>>> {
if CONTROL_FLOW_OP_NAMES
.iter()
.any(|name| self.op_names.contains_key(*name))
{
let result: PyResult<Vec<Py<PyAny>>> = self
.dag
.node_references()
.filter_map(|(node_index, node_type)| match node_type {
NodeType::Operation(ref node) => {
if node.op.control_flow() {
Some(self.unpack_into(py, node_index, node_type))
} else {
None
}
}
}
_ => None,
})
.collect()
_ => None,
})
.collect();
Ok(Some(result?))
} else {
Ok(None)
}
}

/// Get the list of gate nodes in the dag.
Expand Down
10 changes: 6 additions & 4 deletions qiskit/transpiler/passes/utils/control_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,12 @@ def out(self, dag):
def bound_wrapped_method(dag):
return out(self, dag)

for node in dag.control_flow_op_nodes():
dag.substitute_node(
node, map_blocks(bound_wrapped_method, node.op), propagate_condition=False
)
control_flow_nodes = dag.control_flow_op_nodes()
if control_flow_nodes is not None:
for node in control_flow_nodes:
dag.substitute_node(
node, map_blocks(bound_wrapped_method, node.op), propagate_condition=False
)
return method(self, dag)

return out

0 comments on commit 2c0aad5

Please sign in to comment.