-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
decompose.py
98 lines (84 loc) · 3.69 KB
/
decompose.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Expand a gate in a circuit using its decomposition rules."""
from typing import Type, Union, List, Optional
from fnmatch import fnmatch
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.dagcircuit.dagcircuit import DAGCircuit
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.circuit.gate import Gate
class Decompose(TransformationPass):
"""Expand a gate in a circuit using its decomposition rules."""
def __init__(
self,
gates_to_decompose: Optional[Union[Type[Gate], List[Type[Gate]], List[str], str]] = None,
) -> None:
"""Decompose initializer.
Args:
gates_to_decompose: optional subset of gates to be decomposed,
identified by gate label, name or type. Defaults to all gates.
"""
super().__init__()
self.gates_to_decompose = gates_to_decompose
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Run the Decompose pass on `dag`.
Args:
dag: input dag.
Returns:
output dag where ``gate`` was expanded.
"""
# Walk through the DAG and expand each non-basis node
for node in dag.op_nodes():
if self._should_decompose(node):
if getattr(node.op, "definition", None) is None:
continue
# TODO: allow choosing among multiple decomposition rules
rule = node.op.definition.data
if (
len(rule) == 1
and len(node.qargs) == len(rule[0].qubits) == 1 # to preserve gate order
and len(node.cargs) == len(rule[0].clbits) == 0
):
if node.op.definition.global_phase:
dag.global_phase += node.op.definition.global_phase
dag.substitute_node(node, rule[0].operation, inplace=True)
else:
decomposition = circuit_to_dag(node.op.definition)
dag.substitute_node_with_dag(node, decomposition)
return dag
def _should_decompose(self, node) -> bool:
"""Call a decomposition pass on this circuit,
to decompose one level (shallow decompose)."""
if self.gates_to_decompose is None: # check if no gates given
return True
if not isinstance(self.gates_to_decompose, list):
gates = [self.gates_to_decompose]
else:
gates = self.gates_to_decompose
strings_list = [s for s in gates if isinstance(s, str)]
gate_type_list = [g for g in gates if isinstance(g, type)]
if (
getattr(node.op, "label", None) is not None
and node.op.label != ""
and ( # check if label or label wildcard is given
node.op.label in gates or any(fnmatch(node.op.label, p) for p in strings_list)
)
):
return True
elif node.name in gates or any( # check if name or name wildcard is given
fnmatch(node.name, p) for p in strings_list
):
return True
elif any(isinstance(node.op, op) for op in gate_type_list): # check if Gate type given
return True
else:
return False