From 82e5e986fb6ab35d2f21f2269408553a14e46c33 Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Fri, 26 Jun 2020 12:25:47 -0400 Subject: [PATCH 01/11] definition changed to circuit some multi-qubit controlled gate tests are still failing. --- qiskit/circuit/add_control.py | 14 +- qiskit/circuit/controlledgate.py | 30 +- qiskit/circuit/instruction.py | 31 +- qiskit/circuit/library/standard_gates/dcx.py | 20 +- qiskit/circuit/library/standard_gates/h.py | 80 ++-- .../circuit/library/standard_gates/iswap.py | 46 +- qiskit/circuit/library/standard_gates/ms.py | 24 +- qiskit/circuit/library/standard_gates/r.py | 30 +- qiskit/circuit/library/standard_gates/rx.py | 76 +-- qiskit/circuit/library/standard_gates/rxx.py | 40 +- qiskit/circuit/library/standard_gates/ry.py | 66 +-- qiskit/circuit/library/standard_gates/ryy.py | 42 +- qiskit/circuit/library/standard_gates/rz.py | 66 +-- qiskit/circuit/library/standard_gates/rzx.py | 24 +- qiskit/circuit/library/standard_gates/rzz.py | 32 +- qiskit/circuit/library/standard_gates/s.py | 52 +- qiskit/circuit/library/standard_gates/swap.py | 68 +-- qiskit/circuit/library/standard_gates/t.py | 52 +- qiskit/circuit/library/standard_gates/u1.py | 68 +-- qiskit/circuit/library/standard_gates/u2.py | 16 +- qiskit/circuit/library/standard_gates/u3.py | 52 +- qiskit/circuit/library/standard_gates/x.py | 452 +++++++++--------- qiskit/circuit/library/standard_gates/y.py | 52 +- qiskit/circuit/library/standard_gates/z.py | 52 +- qiskit/converters/ast_to_dag.py | 18 +- qiskit/converters/circuit_to_gate.py | 12 +- qiskit/converters/circuit_to_instruction.py | 12 +- qiskit/extensions/hamiltonian_gate.py | 4 +- .../quantum_initializer/diagonal.py | 2 +- .../quantum_initializer/initializer.py | 2 +- .../quantum_initializer/isometry.py | 2 +- .../quantum_initializer/mcg_up_to_diagonal.py | 2 +- qiskit/extensions/quantum_initializer/squ.py | 18 +- qiskit/extensions/quantum_initializer/uc.py | 2 +- .../quantum_initializer/uc_pauli_rot.py | 2 +- qiskit/extensions/unitary.py | 13 +- .../quantum_info/operators/channel/superop.py | 5 +- qiskit/quantum_info/operators/operator.py | 7 +- .../operators/symplectic/clifford_circuits.py | 5 +- qiskit/quantum_info/states/densitymatrix.py | 5 +- qiskit/quantum_info/states/statevector.py | 6 +- qiskit/transpiler/passes/basis/decompose.py | 2 +- .../passes/basis/unroll_3q_or_more.py | 2 +- .../passes/basis/unroll_custom_definitions.py | 5 +- qiskit/transpiler/passes/basis/unroller.py | 4 +- test/python/circuit/test_controlled_gate.py | 9 +- test/python/circuit/test_gate_definitions.py | 2 +- .../operators/symplectic/test_clifford.py | 8 +- .../test_unroll_custom_definitions.py | 9 +- 49 files changed, 858 insertions(+), 785 deletions(-) diff --git a/qiskit/circuit/add_control.py b/qiskit/circuit/add_control.py index df7b3a814d01..7ea93e100a3c 100644 --- a/qiskit/circuit/add_control.py +++ b/qiskit/circuit/add_control.py @@ -118,18 +118,19 @@ def control(operation: Union[Gate, ControlledGate], operation.base_gate.name == 'x'): qc.mct(q_control[:] + q_target[:-1], q_target[-1], q_ancillae) elif operation.name == 'rx': - qc.mcrx(operation.definition[0][0].params[0], q_control, q_target[0], + qc.mcrx(operation.definition.data[0][0].params[0], q_control, q_target[0], use_basis_gates=True) elif operation.name == 'ry': - qc.mcry(operation.definition[0][0].params[0], q_control, q_target[0], + qc.mcry(operation.definition.data[0][0].params[0], q_control, q_target[0], q_ancillae, mode='noancilla', use_basis_gates=True) elif operation.name == 'rz': - qc.mcrz(operation.definition[0][0].params[0], q_control, q_target[0], + qc.mcrz(operation.definition.data[0][0].params[0], q_control, q_target[0], use_basis_gates=True) else: bgate = _unroll_gate(operation, ['u1', 'u3', 'cx']) # now we have a bunch of single qubit rotation gates and cx - for rule in bgate.definition: + bgate.definition.data + for rule in bgate.definition.data: if rule[0].name == 'u3': theta, phi, lamb = rule[0].params if phi == -pi / 2 and lamb == pi / 2: @@ -156,7 +157,6 @@ def control(operation: Union[Gate, ControlledGate], else: raise CircuitError('gate contains non-controllable instructions') - instr = qc.to_instruction() if isinstance(operation, controlledgate.ControlledGate): new_num_ctrl_qubits = num_ctrl_qubits + operation.num_ctrl_qubits new_ctrl_state = operation.ctrl_state << num_ctrl_qubits | ctrl_state @@ -177,11 +177,11 @@ def control(operation: Union[Gate, ControlledGate], ctrl_substr = ('{0}' * new_num_ctrl_qubits).format('c') new_name = '{0}{1}'.format(ctrl_substr, base_name) cgate = controlledgate.ControlledGate(new_name, - instr.num_qubits, + qc.num_qubits, operation.params, label=label, num_ctrl_qubits=new_num_ctrl_qubits, - definition=instr.definition, + definition=qc, ctrl_state=new_ctrl_state) cgate.base_gate = base_gate return cgate diff --git a/qiskit/circuit/controlledgate.py b/qiskit/circuit/controlledgate.py index a080c3857fee..4794a7c41736 100644 --- a/qiskit/circuit/controlledgate.py +++ b/qiskit/circuit/controlledgate.py @@ -30,7 +30,7 @@ class ControlledGate(Gate): def __init__(self, name: str, num_qubits: int, params: List, label: Optional[str] = None, num_ctrl_qubits: Optional[int] = 1, - definition: Optional[List[Tuple[Gate, List[Qubit], List[Clbit]]]] = None, + definition: Optional['QuantumCircuit'] = None, ctrl_state: Optional[Union[int, str]] = None): """Create a new ControlledGate. In the new gate the first ``num_ctrl_qubits`` of the gate are the controls. @@ -92,8 +92,8 @@ def __init__(self, name: str, num_qubits: int, params: List, self.base_gate = None if definition: self.definition = definition - if len(definition) == 1: - base_gate = definition[0][0] + if len(definition.data) == 1: + base_gate = definition.data[0][0] if isinstance(base_gate, ControlledGate): self.base_gate = base_gate.base_gate else: @@ -108,28 +108,30 @@ def definition(self) -> List: definition is conjugated with X without changing the internal `_definition`. """ + from qiskit import QuantumCircuit if self._open_ctrl: closed_gate = self.copy() closed_gate.ctrl_state = None - # pylint: disable=cyclic-import - from qiskit.circuit.library.standard_gates import XGate bit_ctrl_state = bin(self.ctrl_state)[2:].zfill(self.num_ctrl_qubits) qreg = QuantumRegister(self.num_qubits, 'q') - definition = [(closed_gate, qreg, [])] - open_rules = [] + qc_open_ctrl = QuantumCircuit(qreg) for qind, val in enumerate(bit_ctrl_state[::-1]): if val == '0': - open_rules.append([XGate(), [qreg[qind]], []]) - if open_rules: - return open_rules + definition + open_rules - else: - return self._definition + qc_open_ctrl.x(qind) + qc_open_ctrl.append(closed_gate, qargs=qreg[:]) + for qind, val in enumerate(bit_ctrl_state[::-1]): + if val == '0': + qc_open_ctrl.x(qind) + return qc_open_ctrl else: return super().definition @definition.setter - def definition(self, excited_def: List): - """Set controlled gate definition with closed controls.""" + def definition(self, excited_def: 'QuantumCircuit'): + """Set controlled gate definition with closed controls. + + Args: + excited_def: The circuit with all closed controls.""" super(Gate, self.__class__).definition.fset(self, excited_def) @property diff --git a/qiskit/circuit/instruction.py b/qiskit/circuit/instruction.py index b14761e5f994..1e099f29ff64 100644 --- a/qiskit/circuit/instruction.py +++ b/qiskit/circuit/instruction.py @@ -128,7 +128,11 @@ def __eq__(self, other): def _define(self): """Populates self.definition with a decomposition of this gate.""" - pass + try: + self._definition = self.decompositions[0] + except IndexError: + # u3 or cx + pass @property def params(self): @@ -177,9 +181,13 @@ def definition(self): return self._definition @definition.setter - def definition(self, array): - """Set matrix representation""" - self._definition = array + def definition(self, definition): + """Set gate representation""" + from qiskit import QuantumCircuit + if not isinstance(definition, QuantumCircuit) and definition is not None: + raise CircuitError('Instruction definition must be QuantumCircuit. Got {}'.format( + type(definition))) + self._definition = definition @property def decompositions(self): @@ -246,9 +254,9 @@ def reverse_ops(self): return self.copy() reverse_inst = self.copy(name=self.name + '_reverse') - reverse_inst.definition = [] + reverse_inst.definition.data = [] for inst, qargs, cargs in reversed(self._definition): - reverse_inst._definition.append((inst.reverse_ops(), qargs, cargs)) + reverse_inst._definition.data.append((inst.reverse_ops(), qargs, cargs)) return reverse_inst def inverse(self): @@ -270,9 +278,9 @@ def inverse(self): if self.definition is None: raise CircuitError("inverse() not implemented for %s." % self.name) inverse_gate = self.copy(name=self.name + '_dg') - inverse_gate._definition = [] - for inst, qargs, cargs in reversed(self._definition): - inverse_gate._definition.append((inst.inverse(), qargs, cargs)) + inverse_gate._definition.data = [] + for inst, qargs, cargs in reversed(self._definition.data): + inverse_gate._definition.data.append((inst.inverse(), qargs, cargs)) return inverse_gate def c_if(self, classical, val): @@ -377,5 +385,8 @@ def repeat(self, n): qargs = [] if self.num_qubits == 0 else QuantumRegister(self.num_qubits, 'q') cargs = [] if self.num_clbits == 0 else ClassicalRegister(self.num_clbits, 'c') - instruction.definition = [(self, qargs[:], cargs[:])] * n + if instruction.definition is None: + from qiskit import QuantumCircuit + instruction.definition = QuantumCircuit(self.num_qubits) + instruction.definition.data = [(self, qargs[:], cargs[:])] * n return instruction diff --git a/qiskit/circuit/library/standard_gates/dcx.py b/qiskit/circuit/library/standard_gates/dcx.py index 4c27a777f5b4..a54146f0bd19 100644 --- a/qiskit/circuit/library/standard_gates/dcx.py +++ b/qiskit/circuit/library/standard_gates/dcx.py @@ -50,16 +50,16 @@ def __init__(self): """Create new DCX gate.""" super().__init__('dcx', 2, []) - def _define(self): - """ - gate dcx a, b { cx a, b; cx a, b; } - """ - from .x import CXGate - q = QuantumRegister(2, 'q') - self.definition = [ - (CXGate(), [q[0], q[1]], []), - (CXGate(), [q[1], q[0]], []) - ] + # def _define(self): + # """ + # gate dcx a, b { cx a, b; cx a, b; } + # """ + # from .x import CXGate + # q = QuantumRegister(2, 'q') + # self.definition = [ + # (CXGate(), [q[0], q[1]], []), + # (CXGate(), [q[1], q[0]], []) + # ] def to_matrix(self): """Return a numpy.array for the DCX gate.""" diff --git a/qiskit/circuit/library/standard_gates/h.py b/qiskit/circuit/library/standard_gates/h.py index 7a4463b23204..bead4fc368e2 100644 --- a/qiskit/circuit/library/standard_gates/h.py +++ b/qiskit/circuit/library/standard_gates/h.py @@ -53,19 +53,19 @@ def __init__(self, label=None): """Create new H gate.""" super().__init__('h', 1, [], label=label) - def _define(self): - """ - gate h a { u2(0,pi) a; } - """ - from .u2 import U2Gate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (U2Gate(0, pi), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate h a { u2(0,pi) a; } + # """ + # from .u2 import U2Gate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (U2Gate(0, pi), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (multi-)controlled-H gate. @@ -169,33 +169,33 @@ def __init__(self, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = HGate() - def _define(self): - """ - gate ch a,b { - s b; - h b; - t b; - cx a, b; - tdg b; - h b; - sdg b; - } - """ - from .x import CXGate # pylint: disable=cyclic-import - definition = [] - q = QuantumRegister(2, 'q') - rule = [ - (SGate(), [q[1]], []), - (HGate(), [q[1]], []), - (TGate(), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (TdgGate(), [q[1]], []), - (HGate(), [q[1]], []), - (SdgGate(), [q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate ch a,b { + # s b; + # h b; + # t b; + # cx a, b; + # tdg b; + # h b; + # sdg b; + # } + # """ + # from .x import CXGate # pylint: disable=cyclic-import + # definition = [] + # q = QuantumRegister(2, 'q') + # rule = [ + # (SGate(), [q[1]], []), + # (HGate(), [q[1]], []), + # (TGate(), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (TdgGate(), [q[1]], []), + # (HGate(), [q[1]], []), + # (SdgGate(), [q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverted CH gate (itself).""" diff --git a/qiskit/circuit/library/standard_gates/iswap.py b/qiskit/circuit/library/standard_gates/iswap.py index c2f38f22824b..3567d23c23b8 100644 --- a/qiskit/circuit/library/standard_gates/iswap.py +++ b/qiskit/circuit/library/standard_gates/iswap.py @@ -81,29 +81,29 @@ def __init__(self): """Create new iSwap gate.""" super().__init__('iswap', 2, []) - def _define(self): - """ - gate iswap a,b { - s q[0]; - s q[1]; - h q[0]; - cx q[0],q[1]; - cx q[1],q[0]; - h q[1]; - } - """ - from .h import HGate - from .s import SGate - from .x import CXGate - q = QuantumRegister(2, 'q') - self.definition = [ - (SGate(), [q[0]], []), - (SGate(), [q[1]], []), - (HGate(), [q[0]], []), - (CXGate(), [q[0], q[1]], []), - (CXGate(), [q[1], q[0]], []), - (HGate(), [q[1]], []) - ] + # def _define(self): + # """ + # gate iswap a,b { + # s q[0]; + # s q[1]; + # h q[0]; + # cx q[0],q[1]; + # cx q[1],q[0]; + # h q[1]; + # } + # """ + # from .h import HGate + # from .s import SGate + # from .x import CXGate + # q = QuantumRegister(2, 'q') + # self.definition = [ + # (SGate(), [q[0]], []), + # (SGate(), [q[1]], []), + # (HGate(), [q[0]], []), + # (CXGate(), [q[0], q[1]], []), + # (CXGate(), [q[1], q[0]], []), + # (HGate(), [q[1]], []) + # ] def to_matrix(self): """Return a numpy.array for the iSWAP gate.""" diff --git a/qiskit/circuit/library/standard_gates/ms.py b/qiskit/circuit/library/standard_gates/ms.py index 33170e3cd852..20b3a9043750 100644 --- a/qiskit/circuit/library/standard_gates/ms.py +++ b/qiskit/circuit/library/standard_gates/ms.py @@ -35,15 +35,15 @@ def __init__(self, num_qubits, theta, *, n_qubits=None, # pylint:disable=unused """Create new MS gate.""" super().__init__('ms', num_qubits, [theta], label=label) - def _define(self): - from .rxx import RXXGate - definition = [] - q = QuantumRegister(self.num_qubits, 'q') - rule = [] - for i in range(self.num_qubits): - for j in range(i + 1, self.num_qubits): - rule += [(RXXGate(self.params[0]), [q[i], q[j]], [])] - - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # from .rxx import RXXGate + # definition = [] + # q = QuantumRegister(self.num_qubits, 'q') + # rule = [] + # for i in range(self.num_qubits): + # for j in range(i + 1, self.num_qubits): + # rule += [(RXXGate(self.params[0]), [q[i], q[j]], [])] + + # for inst in rule: + # definition.append(inst) + # self.definition = definition diff --git a/qiskit/circuit/library/standard_gates/r.py b/qiskit/circuit/library/standard_gates/r.py index 11973a9a43b3..43780ec47122 100644 --- a/qiskit/circuit/library/standard_gates/r.py +++ b/qiskit/circuit/library/standard_gates/r.py @@ -48,21 +48,21 @@ def __init__(self, theta, phi): """Create new r single-qubit gate.""" super().__init__('r', 1, [theta, phi]) - def _define(self): - """ - gate r(θ, φ) a {u3(θ, φ - π/2, -φ + π/2) a;} - """ - from .u3 import U3Gate - definition = [] - q = QuantumRegister(1, 'q') - theta = self.params[0] - phi = self.params[1] - rule = [ - (U3Gate(theta, phi - pi / 2, -phi + pi / 2), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate r(θ, φ) a {u3(θ, φ - π/2, -φ + π/2) a;} + # """ + # from .u3 import U3Gate + # definition = [] + # q = QuantumRegister(1, 'q') + # theta = self.params[0] + # phi = self.params[1] + # rule = [ + # (U3Gate(theta, phi - pi / 2, -phi + pi / 2), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Invert this gate. diff --git a/qiskit/circuit/library/standard_gates/rx.py b/qiskit/circuit/library/standard_gates/rx.py index c28256c6e308..bfdb142c1ac8 100644 --- a/qiskit/circuit/library/standard_gates/rx.py +++ b/qiskit/circuit/library/standard_gates/rx.py @@ -50,19 +50,19 @@ def __init__(self, theta, label=None): """Create new RX gate.""" super().__init__('rx', 1, [theta], label=label) - def _define(self): - """ - gate rx(theta) a {r(theta, 0) a;} - """ - from .r import RGate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (RGate(self.params[0], 0), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate rx(theta) a {r(theta, 0) a;} + # """ + # from .r import RGate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (RGate(self.params[0], 0), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-RX gate. @@ -168,31 +168,31 @@ def __init__(self, theta, label=None, ctrl_state=None): label=label, ctrl_state=ctrl_state) self.base_gate = RXGate(theta) - def _define(self): - """ - gate cu3(theta,phi,lambda) c, t - { u1(pi/2) t; - cx c,t; - u3(-theta/2,0,0) t; - cx c,t; - u3(theta/2,-pi/2,0) t; - } - """ - from .u1 import U1Gate - from .u3 import U3Gate - from .x import CXGate - definition = [] - q = QuantumRegister(2, 'q') - rule = [ - (U1Gate(pi / 2), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (U3Gate(-self.params[0] / 2, 0, 0), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (U3Gate(self.params[0] / 2, -pi / 2, 0), [q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate cu3(theta,phi,lambda) c, t + # { u1(pi/2) t; + # cx c,t; + # u3(-theta/2,0,0) t; + # cx c,t; + # u3(theta/2,-pi/2,0) t; + # } + # """ + # from .u1 import U1Gate + # from .u3 import U3Gate + # from .x import CXGate + # definition = [] + # q = QuantumRegister(2, 'q') + # rule = [ + # (U1Gate(pi / 2), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (U3Gate(-self.params[0] / 2, 0, 0), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (U3Gate(self.params[0] / 2, -pi / 2, 0), [q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse RX gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/rxx.py b/qiskit/circuit/library/standard_gates/rxx.py index 273afe1397b0..31955469507b 100644 --- a/qiskit/circuit/library/standard_gates/rxx.py +++ b/qiskit/circuit/library/standard_gates/rxx.py @@ -72,26 +72,26 @@ def __init__(self, theta): """Create new RXX gate.""" super().__init__('rxx', 2, [theta]) - def _define(self): - """Calculate a subcircuit that implements this unitary.""" - from .x import CXGate - from .u1 import U1Gate - from .h import HGate - definition = [] - q = QuantumRegister(2, 'q') - theta = self.params[0] - rule = [ - (HGate(), [q[0]], []), - (HGate(), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (U1Gate(theta), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (HGate(), [q[1]], []), - (HGate(), [q[0]], []), - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """Calculate a subcircuit that implements this unitary.""" + # from .x import CXGate + # from .u1 import U1Gate + # from .h import HGate + # definition = [] + # q = QuantumRegister(2, 'q') + # theta = self.params[0] + # rule = [ + # (HGate(), [q[0]], []), + # (HGate(), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (U1Gate(theta), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (HGate(), [q[1]], []), + # (HGate(), [q[0]], []), + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse RXX gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/ry.py b/qiskit/circuit/library/standard_gates/ry.py index b6ca8648fed7..f66438c52902 100644 --- a/qiskit/circuit/library/standard_gates/ry.py +++ b/qiskit/circuit/library/standard_gates/ry.py @@ -50,19 +50,19 @@ def __init__(self, theta, label=None): """Create new RY gate.""" super().__init__('ry', 1, [theta], label=label) - def _define(self): - """ - gate ry(theta) a { r(theta, pi/2) a; } - """ - from .r import RGate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (RGate(self.params[0], pi / 2), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate ry(theta) a { r(theta, pi/2) a; } + # """ + # from .r import RGate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (RGate(self.params[0], pi / 2), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-RY gate. @@ -168,26 +168,26 @@ def __init__(self, theta, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = RYGate(theta) - def _define(self): - """ - gate cry(lambda) a,b - { u3(lambda/2,0,0) b; cx a,b; - u3(-lambda/2,0,0) b; cx a,b; - } - """ - from .u3 import U3Gate - from .x import CXGate - definition = [] - q = QuantumRegister(2, 'q') - rule = [ - (U3Gate(self.params[0] / 2, 0, 0), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (U3Gate(-self.params[0] / 2, 0, 0), [q[1]], []), - (CXGate(), [q[0], q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate cry(lambda) a,b + # { u3(lambda/2,0,0) b; cx a,b; + # u3(-lambda/2,0,0) b; cx a,b; + # } + # """ + # from .u3 import U3Gate + # from .x import CXGate + # definition = [] + # q = QuantumRegister(2, 'q') + # rule = [ + # (U3Gate(self.params[0] / 2, 0, 0), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (U3Gate(-self.params[0] / 2, 0, 0), [q[1]], []), + # (CXGate(), [q[0], q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse RY gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/ryy.py b/qiskit/circuit/library/standard_gates/ryy.py index b039b0fa4d6b..5e4b2ac45dc4 100644 --- a/qiskit/circuit/library/standard_gates/ryy.py +++ b/qiskit/circuit/library/standard_gates/ryy.py @@ -73,27 +73,27 @@ def __init__(self, theta): """Create new RYY gate.""" super().__init__('ryy', 2, [theta]) - def _define(self): - """Calculate a subcircuit that implements this unitary.""" - from .x import CXGate - from .rx import RXGate - from .rz import RZGate - - definition = [] - q = QuantumRegister(2, 'q') - theta = self.params[0] - rule = [ - (RXGate(np.pi / 2), [q[0]], []), - (RXGate(np.pi / 2), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (RZGate(theta), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (RXGate(-np.pi / 2), [q[0]], []), - (RXGate(-np.pi / 2), [q[1]], []), - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """Calculate a subcircuit that implements this unitary.""" + # from .x import CXGate + # from .rx import RXGate + # from .rz import RZGate + + # definition = [] + # q = QuantumRegister(2, 'q') + # theta = self.params[0] + # rule = [ + # (RXGate(np.pi / 2), [q[0]], []), + # (RXGate(np.pi / 2), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (RZGate(theta), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (RXGate(-np.pi / 2), [q[0]], []), + # (RXGate(-np.pi / 2), [q[1]], []), + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse RYY gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/rz.py b/qiskit/circuit/library/standard_gates/rz.py index 8ee5b7c97c7f..1c0d13bfe738 100644 --- a/qiskit/circuit/library/standard_gates/rz.py +++ b/qiskit/circuit/library/standard_gates/rz.py @@ -60,19 +60,19 @@ def __init__(self, phi, label=None): """Create new RZ gate.""" super().__init__('rz', 1, [phi], label=label) - def _define(self): - """ - gate rz(phi) a { u1(phi) a; } - """ - from .u1 import U1Gate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (U1Gate(self.params[0]), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate rz(phi) a { u1(phi) a; } + # """ + # from .u1 import U1Gate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (U1Gate(self.params[0]), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-RZ gate. @@ -186,26 +186,26 @@ def __init__(self, theta, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = RZGate(theta) - def _define(self): - """ - gate crz(lambda) a,b - { u1(lambda/2) b; cx a,b; - u1(-lambda/2) b; cx a,b; - } - """ - from .u1 import U1Gate - from .x import CXGate - definition = [] - q = QuantumRegister(2, 'q') - rule = [ - (U1Gate(self.params[0] / 2), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (U1Gate(-self.params[0] / 2), [q[1]], []), - (CXGate(), [q[0], q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate crz(lambda) a,b + # { u1(lambda/2) b; cx a,b; + # u1(-lambda/2) b; cx a,b; + # } + # """ + # from .u1 import U1Gate + # from .x import CXGate + # definition = [] + # q = QuantumRegister(2, 'q') + # rule = [ + # (U1Gate(self.params[0] / 2), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (U1Gate(-self.params[0] / 2), [q[1]], []), + # (CXGate(), [q[0], q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse RZ gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/rzx.py b/qiskit/circuit/library/standard_gates/rzx.py index d1b756318d0d..1d3ae2e99cc1 100644 --- a/qiskit/circuit/library/standard_gates/rzx.py +++ b/qiskit/circuit/library/standard_gates/rzx.py @@ -121,18 +121,18 @@ def __init__(self, theta): """Create new RZX gate.""" super().__init__('rzx', 2, [theta]) - def _define(self): - """ - gate rzx(theta) a, b { h b; cx a, b; u1(theta) b; cx a, b; h b;} - """ - q = QuantumRegister(2, 'q') - self.definition = [ - (HGate(), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (RZGate(self.params[0]), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (HGate(), [q[1]], []) - ] + # def _define(self): + # """ + # gate rzx(theta) a, b { h b; cx a, b; u1(theta) b; cx a, b; h b;} + # """ + # q = QuantumRegister(2, 'q') + # self.definition = [ + # (HGate(), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (RZGate(self.params[0]), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (HGate(), [q[1]], []) + # ] def inverse(self): """Return inverse RZX gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/rzz.py b/qiskit/circuit/library/standard_gates/rzz.py index e526cb36719f..b426434fbf3f 100644 --- a/qiskit/circuit/library/standard_gates/rzz.py +++ b/qiskit/circuit/library/standard_gates/rzz.py @@ -85,22 +85,22 @@ def __init__(self, theta): """Create new RZZ gate.""" super().__init__('rzz', 2, [theta]) - def _define(self): - """ - gate rzz(theta) a, b { cx a, b; u1(theta) b; cx a, b; } - """ - from .u1 import U1Gate - from .x import CXGate - definition = [] - q = QuantumRegister(2, 'q') - rule = [ - (CXGate(), [q[0], q[1]], []), - (U1Gate(self.params[0]), [q[1]], []), - (CXGate(), [q[0], q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate rzz(theta) a, b { cx a, b; u1(theta) b; cx a, b; } + # """ + # from .u1 import U1Gate + # from .x import CXGate + # definition = [] + # q = QuantumRegister(2, 'q') + # rule = [ + # (CXGate(), [q[0], q[1]], []), + # (U1Gate(self.params[0]), [q[1]], []), + # (CXGate(), [q[0], q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse RZZ gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/s.py b/qiskit/circuit/library/standard_gates/s.py index fd603b616285..497b7ec675c2 100644 --- a/qiskit/circuit/library/standard_gates/s.py +++ b/qiskit/circuit/library/standard_gates/s.py @@ -51,19 +51,19 @@ def __init__(self, label=None): """Create new S gate.""" super().__init__('s', 1, [], label=label) - def _define(self): - """ - gate s a { u1(pi/2) a; } - """ - from .u1 import U1Gate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (U1Gate(pi / 2), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate s a { u1(pi/2) a; } + # """ + # from .u1 import U1Gate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (U1Gate(pi / 2), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse of S (SdgGate).""" @@ -106,19 +106,19 @@ def __init__(self, label=None): """Create new Sdg gate.""" super().__init__('sdg', 1, [], label=label) - def _define(self): - """ - gate sdg a { u1(-pi/2) a; } - """ - from .u1 import U1Gate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (U1Gate(-pi / 2), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate sdg a { u1(-pi/2) a; } + # """ + # from .u1 import U1Gate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (U1Gate(-pi / 2), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse of Sdg (SGate).""" diff --git a/qiskit/circuit/library/standard_gates/swap.py b/qiskit/circuit/library/standard_gates/swap.py index f1e6a5d5389b..864ffc2e0502 100644 --- a/qiskit/circuit/library/standard_gates/swap.py +++ b/qiskit/circuit/library/standard_gates/swap.py @@ -56,21 +56,21 @@ def __init__(self, label=None): """Create new SWAP gate.""" super().__init__('swap', 2, [], label=label) - def _define(self): - """ - gate swap a,b { cx a,b; cx b,a; cx a,b; } - """ - from .x import CXGate - definition = [] - q = QuantumRegister(2, 'q') - rule = [ - (CXGate(), [q[0], q[1]], []), - (CXGate(), [q[1], q[0]], []), - (CXGate(), [q[0], q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate swap a,b { cx a,b; cx b,a; cx a,b; } + # """ + # from .x import CXGate + # definition = [] + # q = QuantumRegister(2, 'q') + # rule = [ + # (CXGate(), [q[0], q[1]], []), + # (CXGate(), [q[1], q[0]], []), + # (CXGate(), [q[0], q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (multi-)controlled-SWAP gate. @@ -210,25 +210,25 @@ def __init__(self, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = SwapGate() - def _define(self): - """ - gate cswap a,b,c - { cx c,b; - ccx a,b,c; - cx c,b; - } - """ - from .x import CXGate, CCXGate - definition = [] - q = QuantumRegister(3, 'q') - rule = [ - (CXGate(), [q[2], q[1]], []), - (CCXGate(), [q[0], q[1], q[2]], []), - (CXGate(), [q[2], q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate cswap a,b,c + # { cx c,b; + # ccx a,b,c; + # cx c,b; + # } + # """ + # from .x import CXGate, CCXGate + # definition = [] + # q = QuantumRegister(3, 'q') + # rule = [ + # (CXGate(), [q[2], q[1]], []), + # (CCXGate(), [q[0], q[1], q[2]], []), + # (CXGate(), [q[2], q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse CSwap gate (itself).""" diff --git a/qiskit/circuit/library/standard_gates/t.py b/qiskit/circuit/library/standard_gates/t.py index e52da07be905..8950a6efeecb 100644 --- a/qiskit/circuit/library/standard_gates/t.py +++ b/qiskit/circuit/library/standard_gates/t.py @@ -52,19 +52,19 @@ def __init__(self, label=None): """Create new T gate.""" super().__init__('t', 1, [], label=label) - def _define(self): - """ - gate t a { u1(pi/4) a; } - """ - from .u1 import U1Gate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (U1Gate(pi / 4), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate t a { u1(pi/4) a; } + # """ + # from .u1 import U1Gate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (U1Gate(pi / 4), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse T gate (i.e. Tdg).""" @@ -107,19 +107,19 @@ def __init__(self, label=None): """Create new Tdg gate.""" super().__init__('tdg', 1, [], label=label) - def _define(self): - """ - gate tdg a { u1(pi/4) a; } - """ - from .u1 import U1Gate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (U1Gate(-pi / 4), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate tdg a { u1(pi/4) a; } + # """ + # from .u1 import U1Gate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (U1Gate(-pi / 4), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverse Tdg gate (i.e. T).""" diff --git a/qiskit/circuit/library/standard_gates/u1.py b/qiskit/circuit/library/standard_gates/u1.py index 4c9f5bb18204..b5939b5fa8cc 100644 --- a/qiskit/circuit/library/standard_gates/u1.py +++ b/qiskit/circuit/library/standard_gates/u1.py @@ -79,16 +79,16 @@ def __init__(self, theta, label=None): """Create new U1 gate.""" super().__init__('u1', 1, [theta], label=label) - def _define(self): - from .u3 import U3Gate # pylint: disable=cyclic-import - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (U3Gate(0, 0, self.params[0]), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # from .u3 import U3Gate # pylint: disable=cyclic-import + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (U3Gate(0, 0, self.params[0]), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-U1 gate. @@ -175,27 +175,27 @@ def __init__(self, theta, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = U1Gate(theta) - def _define(self): - """ - gate cu1(lambda) a,b - { u1(lambda/2) a; cx a,b; - u1(-lambda/2) b; cx a,b; - u1(lambda/2) b; - } - """ - from .x import CXGate # pylint: disable=cyclic-import - definition = [] - q = QuantumRegister(2, 'q') - rule = [ - (U1Gate(self.params[0] / 2), [q[0]], []), - (CXGate(), [q[0], q[1]], []), - (U1Gate(-self.params[0] / 2), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (U1Gate(self.params[0] / 2), [q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate cu1(lambda) a,b + # { u1(lambda/2) a; cx a,b; + # u1(-lambda/2) b; cx a,b; + # u1(lambda/2) b; + # } + # """ + # from .x import CXGate # pylint: disable=cyclic-import + # definition = [] + # q = QuantumRegister(2, 'q') + # rule = [ + # (U1Gate(self.params[0] / 2), [q[0]], []), + # (CXGate(), [q[0], q[1]], []), + # (U1Gate(-self.params[0] / 2), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (U1Gate(self.params[0] / 2), [q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Controlled version of this gate. @@ -275,7 +275,9 @@ def __init__(self, lam, num_ctrl_qubits, label=None): self.base_gate = U1Gate(lam) def _define(self): + from qiskit import QuantumCircuit q = QuantumRegister(self.num_qubits, 'q') + qc = QuantumCircuit(q, name=self.name) if self.num_ctrl_qubits == 0: definition = U1Gate(self.params[0]).definition @@ -286,8 +288,8 @@ def _define(self): scaled_lam = self.params[0] / (2 ** (self.num_ctrl_qubits - 1)) bottom_gate = CU1Gate(scaled_lam) definition = _gray_code_chain(q, self.num_ctrl_qubits, bottom_gate) - - self.definition = definition + qc.data = definition + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Controlled version of this gate. diff --git a/qiskit/circuit/library/standard_gates/u2.py b/qiskit/circuit/library/standard_gates/u2.py index 7b9831711c2e..ea299cc68fa2 100644 --- a/qiskit/circuit/library/standard_gates/u2.py +++ b/qiskit/circuit/library/standard_gates/u2.py @@ -63,14 +63,14 @@ def __init__(self, phi, lam, label=None): """Create new U2 gate.""" super().__init__('u2', 1, [phi, lam], label=label) - def _define(self): - from .u3 import U3Gate - definition = [] - q = QuantumRegister(1, 'q') - rule = [(U3Gate(pi / 2, self.params[0], self.params[1]), [q[0]], [])] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # from .u3 import U3Gate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [(U3Gate(pi / 2, self.params[0], self.params[1]), [q[0]], [])] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): r"""Return inverted U2 gate. diff --git a/qiskit/circuit/library/standard_gates/u3.py b/qiskit/circuit/library/standard_gates/u3.py index 221e444bc78f..f05772b64f76 100644 --- a/qiskit/circuit/library/standard_gates/u3.py +++ b/qiskit/circuit/library/standard_gates/u3.py @@ -180,32 +180,32 @@ def __init__(self, theta, phi, lam, label=None, ctrl_state=None): label=label, ctrl_state=ctrl_state) self.base_gate = U3Gate(theta, phi, lam) - def _define(self): - """ - gate cu3(theta,phi,lambda) c, t - { u1((lambda+phi)/2) c; - u1((lambda-phi)/2) t; - cx c,t; - u3(-theta/2,0,-(phi+lambda)/2) t; - cx c,t; - u3(theta/2,phi,0) t; - } - """ - from .u1 import U1Gate - from .x import CXGate # pylint: disable=cyclic-import - definition = [] - q = QuantumRegister(2, 'q') - rule = [ - (U1Gate((self.params[2] + self.params[1]) / 2), [q[0]], []), - (U1Gate((self.params[2] - self.params[1]) / 2), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (U3Gate(-self.params[0] / 2, 0, -(self.params[1] + self.params[2]) / 2), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (U3Gate(self.params[0] / 2, self.params[1], 0), [q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate cu3(theta,phi,lambda) c, t + # { u1((lambda+phi)/2) c; + # u1((lambda-phi)/2) t; + # cx c,t; + # u3(-theta/2,0,-(phi+lambda)/2) t; + # cx c,t; + # u3(theta/2,phi,0) t; + # } + # """ + # from .u1 import U1Gate + # from .x import CXGate # pylint: disable=cyclic-import + # definition = [] + # q = QuantumRegister(2, 'q') + # rule = [ + # (U1Gate((self.params[2] + self.params[1]) / 2), [q[0]], []), + # (U1Gate((self.params[2] - self.params[1]) / 2), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (U3Gate(-self.params[0] / 2, 0, -(self.params[1] + self.params[2]) / 2), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (U3Gate(self.params[0] / 2, self.params[1], 0), [q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): r"""Return inverted CU3 gate. diff --git a/qiskit/circuit/library/standard_gates/x.py b/qiskit/circuit/library/standard_gates/x.py index ac998678e591..e59b7dd5dbf4 100644 --- a/qiskit/circuit/library/standard_gates/x.py +++ b/qiskit/circuit/library/standard_gates/x.py @@ -74,19 +74,11 @@ def __init__(self, label=None): """Create new X gate.""" super().__init__('x', 1, [], label=label) - def _define(self): - """ - gate x a { u3(pi,0,pi) a; } - """ - from .u3 import U3Gate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (U3Gate(pi, 0, pi), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate x a { u3(pi,0,pi) a; } + # """ + # self.definition = self.decompositions[0] def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-X gate. @@ -320,37 +312,41 @@ def __init__(self, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = XGate() - def _define(self): - """ - gate ccx a,b,c - { - h c; cx b,c; tdg c; cx a,c; - t c; cx b,c; tdg c; cx a,c; - t b; t c; h c; cx a,b; - t a; tdg b; cx a,b;} - """ - definition = [] - q = QuantumRegister(3, 'q') - rule = [ - (HGate(), [q[2]], []), - (CXGate(), [q[1], q[2]], []), - (TdgGate(), [q[2]], []), - (CXGate(), [q[0], q[2]], []), - (TGate(), [q[2]], []), - (CXGate(), [q[1], q[2]], []), - (TdgGate(), [q[2]], []), - (CXGate(), [q[0], q[2]], []), - (TGate(), [q[1]], []), - (TGate(), [q[2]], []), - (HGate(), [q[2]], []), - (CXGate(), [q[0], q[1]], []), - (TGate(), [q[0]], []), - (TdgGate(), [q[1]], []), - (CXGate(), [q[0], q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # circ = self.decompositions[0] + # self._definition = circ + + # def _define(self): + # """ + # gate ccx a,b,c + # { + # h c; cx b,c; tdg c; cx a,c; + # t c; cx b,c; tdg c; cx a,c; + # t b; t c; h c; cx a,b; + # t a; tdg b; cx a,b;} + # """ + # definition = [] + # q = QuantumRegister(3, 'q') + # rule = [ + # (HGate(), [q[2]], []), + # (CXGate(), [q[1], q[2]], []), + # (TdgGate(), [q[2]], []), + # (CXGate(), [q[0], q[2]], []), + # (TGate(), [q[2]], []), + # (CXGate(), [q[1], q[2]], []), + # (TdgGate(), [q[2]], []), + # (CXGate(), [q[0], q[2]], []), + # (TGate(), [q[1]], []), + # (TGate(), [q[2]], []), + # (HGate(), [q[2]], []), + # (CXGate(), [q[0], q[1]], []), + # (TGate(), [q[0]], []), + # (TdgGate(), [q[1]], []), + # (CXGate(), [q[0], q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Controlled version of this gate. @@ -411,34 +407,34 @@ def __init__(self, label=None): """Create a new simplified CCX gate.""" super().__init__('rccx', 3, [], label=label) - def _define(self): - """ - gate rccx a,b,c - { u2(0,pi) c; - u1(pi/4) c; - cx b, c; - u1(-pi/4) c; - cx a, c; - u1(pi/4) c; - cx b, c; - u1(-pi/4) c; - u2(0,pi) c; - } - """ - definition = [] - q = QuantumRegister(3, 'q') - definition = [ - (U2Gate(0, pi), [q[2]], []), # H gate - (U1Gate(pi / 4), [q[2]], []), # T gate - (CXGate(), [q[1], q[2]], []), - (U1Gate(-pi / 4), [q[2]], []), # inverse T gate - (CXGate(), [q[0], q[2]], []), - (U1Gate(pi / 4), [q[2]], []), - (CXGate(), [q[1], q[2]], []), - (U1Gate(-pi / 4), [q[2]], []), # inverse T gate - (U2Gate(0, pi), [q[2]], []), # H gate - ] - self.definition = definition + # def _define(self): + # """ + # gate rccx a,b,c + # { u2(0,pi) c; + # u1(pi/4) c; + # cx b, c; + # u1(-pi/4) c; + # cx a, c; + # u1(pi/4) c; + # cx b, c; + # u1(-pi/4) c; + # u2(0,pi) c; + # } + # """ + # definition = [] + # q = QuantumRegister(3, 'q') + # definition = [ + # (U2Gate(0, pi), [q[2]], []), # H gate + # (U1Gate(pi / 4), [q[2]], []), # T gate + # (CXGate(), [q[1], q[2]], []), + # (U1Gate(-pi / 4), [q[2]], []), # inverse T gate + # (CXGate(), [q[0], q[2]], []), + # (U1Gate(pi / 4), [q[2]], []), + # (CXGate(), [q[1], q[2]], []), + # (U1Gate(-pi / 4), [q[2]], []), # inverse T gate + # (U2Gate(0, pi), [q[2]], []), # H gate + # ] + # self.definition = definition def to_matrix(self): """Return a numpy.array for the simplified CCX gate.""" @@ -475,57 +471,57 @@ def __init__(self, angle=numpy.pi/4, label=None, ctrl_state=None): self.base_gate = XGate() self._angle = angle - def _define(self): - """ - gate c3x a,b,c,d - { - h d; cu1(-pi/4) a,d; h d; - cx a,b; - h d; cu1(pi/4) b,d; h d; - cx a,b; - h d; cu1(-pi/4) b,d; h d; - cx b,c; - h d; cu1(pi/4) c,d; h d; - cx a,c; - h d; cu1(-pi/4) c,d; h d; - cx b,c; - h d; cu1(pi/4) c,d; h d; - cx a,c; - h d; cu1(-pi/4) c,d; h d; - } - """ - from .u1 import CU1Gate - q = QuantumRegister(4, name='q') - definition = [ - (HGate(), [q[3]], []), - (CU1Gate(-self._angle), [q[0], q[3]], []), - (HGate(), [q[3]], []), - (CXGate(), [q[0], q[1]], []), - (HGate(), [q[3]], []), - (CU1Gate(self._angle), [q[1], q[3]], []), - (HGate(), [q[3]], []), - (CXGate(), [q[0], q[1]], []), - (HGate(), [q[3]], []), - (CU1Gate(-self._angle), [q[1], q[3]], []), - (HGate(), [q[3]], []), - (CXGate(), [q[1], q[2]], []), - (HGate(), [q[3]], []), - (CU1Gate(self._angle), [q[2], q[3]], []), - (HGate(), [q[3]], []), - (CXGate(), [q[0], q[2]], []), - (HGate(), [q[3]], []), - (CU1Gate(-self._angle), [q[2], q[3]], []), - (HGate(), [q[3]], []), - (CXGate(), [q[1], q[2]], []), - (HGate(), [q[3]], []), - (CU1Gate(self._angle), [q[2], q[3]], []), - (HGate(), [q[3]], []), - (CXGate(), [q[0], q[2]], []), - (HGate(), [q[3]], []), - (CU1Gate(-self._angle), [q[2], q[3]], []), - (HGate(), [q[3]], []) - ] - self.definition = definition + # def _define(self): + # """ + # gate c3x a,b,c,d + # { + # h d; cu1(-pi/4) a,d; h d; + # cx a,b; + # h d; cu1(pi/4) b,d; h d; + # cx a,b; + # h d; cu1(-pi/4) b,d; h d; + # cx b,c; + # h d; cu1(pi/4) c,d; h d; + # cx a,c; + # h d; cu1(-pi/4) c,d; h d; + # cx b,c; + # h d; cu1(pi/4) c,d; h d; + # cx a,c; + # h d; cu1(-pi/4) c,d; h d; + # } + # """ + # from .u1 import CU1Gate + # q = QuantumRegister(4, name='q') + # definition = [ + # (HGate(), [q[3]], []), + # (CU1Gate(-self._angle), [q[0], q[3]], []), + # (HGate(), [q[3]], []), + # (CXGate(), [q[0], q[1]], []), + # (HGate(), [q[3]], []), + # (CU1Gate(self._angle), [q[1], q[3]], []), + # (HGate(), [q[3]], []), + # (CXGate(), [q[0], q[1]], []), + # (HGate(), [q[3]], []), + # (CU1Gate(-self._angle), [q[1], q[3]], []), + # (HGate(), [q[3]], []), + # (CXGate(), [q[1], q[2]], []), + # (HGate(), [q[3]], []), + # (CU1Gate(self._angle), [q[2], q[3]], []), + # (HGate(), [q[3]], []), + # (CXGate(), [q[0], q[2]], []), + # (HGate(), [q[3]], []), + # (CU1Gate(-self._angle), [q[2], q[3]], []), + # (HGate(), [q[3]], []), + # (CXGate(), [q[1], q[2]], []), + # (HGate(), [q[3]], []), + # (CU1Gate(self._angle), [q[2], q[3]], []), + # (HGate(), [q[3]], []), + # (CXGate(), [q[0], q[2]], []), + # (HGate(), [q[3]], []), + # (CU1Gate(-self._angle), [q[2], q[3]], []), + # (HGate(), [q[3]], []) + # ] + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Controlled version of this gate. @@ -586,52 +582,52 @@ def __init__(self, label=None): """Create a new RC3X gate.""" super().__init__('rcccx', 4, [], label=label) - def _define(self): - """ - gate rc3x a,b,c,d - { u2(0,pi) d; - u1(pi/4) d; - cx c,d; - u1(-pi/4) d; - u2(0,pi) d; - cx a,d; - u1(pi/4) d; - cx b,d; - u1(-pi/4) d; - cx a,d; - u1(pi/4) d; - cx b,d; - u1(-pi/4) d; - u2(0,pi) d; - u1(pi/4) d; - cx c,d; - u1(-pi/4) d; - u2(0,pi) d; - } - """ - q = QuantumRegister(4, 'q') - - definition = [ - (U2Gate(0, pi), [q[3]], []), # H gate - (U1Gate(pi / 4), [q[3]], []), # T gate - (CXGate(), [q[2], q[3]], []), - (U1Gate(-pi / 4), [q[3]], []), # inverse T gate - (U2Gate(0, pi), [q[3]], []), - (CXGate(), [q[0], q[3]], []), - (U1Gate(pi / 4), [q[3]], []), - (CXGate(), [q[1], q[3]], []), - (U1Gate(-pi / 4), [q[3]], []), - (CXGate(), [q[0], q[3]], []), - (U1Gate(pi / 4), [q[3]], []), - (CXGate(), [q[1], q[3]], []), - (U1Gate(-pi / 4), [q[3]], []), - (U2Gate(0, pi), [q[3]], []), - (U1Gate(pi / 4), [q[3]], []), - (CXGate(), [q[2], q[3]], []), - (U1Gate(-pi / 4), [q[3]], []), - (U2Gate(0, pi), [q[3]], []), - ] - self.definition = definition + # def _define(self): + # """ + # gate rc3x a,b,c,d + # { u2(0,pi) d; + # u1(pi/4) d; + # cx c,d; + # u1(-pi/4) d; + # u2(0,pi) d; + # cx a,d; + # u1(pi/4) d; + # cx b,d; + # u1(-pi/4) d; + # cx a,d; + # u1(pi/4) d; + # cx b,d; + # u1(-pi/4) d; + # u2(0,pi) d; + # u1(pi/4) d; + # cx c,d; + # u1(-pi/4) d; + # u2(0,pi) d; + # } + # """ + # q = QuantumRegister(4, 'q') + + # definition = [ + # (U2Gate(0, pi), [q[3]], []), # H gate + # (U1Gate(pi / 4), [q[3]], []), # T gate + # (CXGate(), [q[2], q[3]], []), + # (U1Gate(-pi / 4), [q[3]], []), # inverse T gate + # (U2Gate(0, pi), [q[3]], []), + # (CXGate(), [q[0], q[3]], []), + # (U1Gate(pi / 4), [q[3]], []), + # (CXGate(), [q[1], q[3]], []), + # (U1Gate(-pi / 4), [q[3]], []), + # (CXGate(), [q[0], q[3]], []), + # (U1Gate(pi / 4), [q[3]], []), + # (CXGate(), [q[1], q[3]], []), + # (U1Gate(-pi / 4), [q[3]], []), + # (U2Gate(0, pi), [q[3]], []), + # (U1Gate(pi / 4), [q[3]], []), + # (CXGate(), [q[2], q[3]], []), + # (U1Gate(-pi / 4), [q[3]], []), + # (U2Gate(0, pi), [q[3]], []), + # ] + # self.definition = definition def to_matrix(self): """Return a numpy.array for the RC3X gate.""" @@ -667,47 +663,48 @@ def __init__(self, label=None, ctrl_state=None): super().__init__('mcx', 5, [], num_ctrl_qubits=4, label=label, ctrl_state=ctrl_state) self.base_gate = XGate() - def _define(self): - """ - gate c3sqrtx a,b,c,d - { - h d; cu1(-pi/8) a,d; h d; - cx a,b; - h d; cu1(pi/8) b,d; h d; - cx a,b; - h d; cu1(-pi/8) b,d; h d; - cx b,c; - h d; cu1(pi/8) c,d; h d; - cx a,c; - h d; cu1(-pi/8) c,d; h d; - cx b,c; - h d; cu1(pi/8) c,d; h d; - cx a,c; - h d; cu1(-pi/8) c,d; h d; - } - gate c4x a,b,c,d,e - { - h e; cu1(-pi/2) d,e; h e; - c3x a,b,c,d; - h d; cu1(pi/4) d,e; h d; - c3x a,b,c,d; - c3sqrtx a,b,c,e; - } - """ - from .u1 import CU1Gate - q = QuantumRegister(5, name='q') - definition = [ - (HGate(), [q[4]], []), - (CU1Gate(-numpy.pi / 2), [q[3], q[4]], []), - (HGate(), [q[4]], []), - (C3XGate(), [q[0], q[1], q[2], q[3]], []), - (HGate(), [q[4]], []), - (CU1Gate(numpy.pi / 2), [q[3], q[4]], []), - (HGate(), [q[4]], []), - (C3XGate(), [q[0], q[1], q[2], q[3]], []), - (C3XGate(numpy.pi / 8), [q[0], q[1], q[2], q[4]], []), - ] - self.definition = definition + # seems like open controls not hapening? + # def _define(self): + # """ + # gate c3sqrtx a,b,c,d + # { + # h d; cu1(-pi/8) a,d; h d; + # cx a,b; + # h d; cu1(pi/8) b,d; h d; + # cx a,b; + # h d; cu1(-pi/8) b,d; h d; + # cx b,c; + # h d; cu1(pi/8) c,d; h d; + # cx a,c; + # h d; cu1(-pi/8) c,d; h d; + # cx b,c; + # h d; cu1(pi/8) c,d; h d; + # cx a,c; + # h d; cu1(-pi/8) c,d; h d; + # } + # gate c4x a,b,c,d,e + # { + # h e; cu1(-pi/2) d,e; h e; + # c3x a,b,c,d; + # h d; cu1(pi/4) d,e; h d; + # c3x a,b,c,d; + # c3sqrtx a,b,c,e; + # } + # """ + # from .u1 import CU1Gate + # q = QuantumRegister(5, name='q') + # definition = [ + # (HGate(), [q[4]], []), + # (CU1Gate(-numpy.pi / 2), [q[3], q[4]], []), + # (HGate(), [q[4]], []), + # (C3XGate(), [q[0], q[1], q[2], q[3]], []), + # (HGate(), [q[4]], []), + # (CU1Gate(numpy.pi / 2), [q[3], q[4]], []), + # (HGate(), [q[4]], []), + # (C3XGate(), [q[0], q[1], q[2], q[3]], []), + # (C3XGate(numpy.pi / 8), [q[0], q[1], q[2], q[4]], []), + # ] + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Controlled version of this gate. @@ -782,10 +779,11 @@ def get_num_ancilla_qubits(num_ctrl_qubits, mode='noancilla'): def _define(self): """The standard definition used the Gray code implementation.""" + from qiskit import QuantumCircuit q = QuantumRegister(self.num_qubits, name='q') - self.definition = [ - (MCXGrayCode(self.num_ctrl_qubits), q[:], []) - ] + qc = QuantumCircuit(q) + qc.append(MCXGrayCode(self.num_ctrl_qubits), qargs=q[:]) + self.definition = qc @property def num_ancilla_qubits(self): @@ -824,13 +822,14 @@ def __init__(self, num_ctrl_qubits, label=None, ctrl_state=None): def _define(self): """Define the MCX gate using the Gray code.""" + from qiskit import QuantumCircuit from .u1 import MCU1Gate q = QuantumRegister(self.num_qubits, name='q') - self.definition = [ - (HGate(), [q[-1]], []), - (MCU1Gate(numpy.pi, num_ctrl_qubits=self.num_ctrl_qubits), q[:], []), - (HGate(), [q[-1]], []) - ] + qc = QuantumCircuit(q, name=self.name) + qc.h(q[-1]) + qc.append(MCU1Gate(numpy.pi, num_ctrl_qubits=self.num_ctrl_qubits), qargs=q[:]) + qc.h(q[-1]) + self.definition = qc class MCXRecursive(MCXGate): @@ -851,13 +850,19 @@ def get_num_ancilla_qubits(num_ctrl_qubits, mode='recursion'): def _define(self): """Define the MCX gate using recursion.""" + from qiskit import QuantumCircuit + #import ipdb;ipdb.set_trace() q = QuantumRegister(self.num_qubits, name='q') + qc = QuantumCircuit(q, name=self.name) if self.num_qubits == 4: - self.definition = [(C3XGate(), q[:], [])] + qc.append(C3XGate(), qargs=q[:]) + self.definition = qc elif self.num_qubits == 5: - self.definition = [(C4XGate(), q[:], [])] + qc.append(C4XGate(), qargs=q[:]) + self.definition = qc else: - self.definition = self._recurse(q[:-1], q_ancilla=q[-1]) + self.definition = qc + self.definition.data = self._recurse(q[:-1], q_ancilla=q[-1]) def _recurse(self, q, q_ancilla=None): # recursion stop @@ -905,7 +910,9 @@ def get_num_ancilla_qubits(num_ctrl_qubits, mode='v-chain'): def _define(self): """Define the MCX gate using a V-chain of CX gates.""" + from qiskit import QuantumCircuit q = QuantumRegister(self.num_qubits, name='q') + qc = QuantumCircuit(q, name=self.name) q_controls = q[:self.num_ctrl_qubits] q_target = q[self.num_ctrl_qubits] q_ancillas = q[self.num_ctrl_qubits + 1:] @@ -966,4 +973,5 @@ def _define(self): definition.append( (RCCXGate(), [q_controls[j], q_ancillas[i], q_ancillas[i + 1]], [])) - self.definition = definition + qc.data = definition + self.definition = qc diff --git a/qiskit/circuit/library/standard_gates/y.py b/qiskit/circuit/library/standard_gates/y.py index eb5d1cb255b1..d66263687e35 100644 --- a/qiskit/circuit/library/standard_gates/y.py +++ b/qiskit/circuit/library/standard_gates/y.py @@ -68,16 +68,16 @@ def __init__(self, label=None): """Create new Y gate.""" super().__init__('y', 1, [], label=label) - def _define(self): - from .u3 import U3Gate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (U3Gate(pi, pi / 2, pi / 2), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # from .u3 import U3Gate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (U3Gate(pi, pi / 2, pi / 2), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-Y gate. @@ -187,22 +187,22 @@ def __init__(self, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = YGate() - def _define(self): - """ - gate cy a,b { sdg b; cx a,b; s b; } - """ - from .s import SGate, SdgGate - from .x import CXGate - definition = [] - q = QuantumRegister(2, 'q') - rule = [ - (SdgGate(), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (SGate(), [q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate cy a,b { sdg b; cx a,b; s b; } + # """ + # from .s import SGate, SdgGate + # from .x import CXGate + # definition = [] + # q = QuantumRegister(2, 'q') + # rule = [ + # (SdgGate(), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (SGate(), [q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverted CY gate (itself).""" diff --git a/qiskit/circuit/library/standard_gates/z.py b/qiskit/circuit/library/standard_gates/z.py index 2001f03e6412..820d0e38ff33 100644 --- a/qiskit/circuit/library/standard_gates/z.py +++ b/qiskit/circuit/library/standard_gates/z.py @@ -68,16 +68,16 @@ def __init__(self, label=None): """Create new Z gate.""" super().__init__('z', 1, [], label=label) - def _define(self): - from .u1 import U1Gate - definition = [] - q = QuantumRegister(1, 'q') - rule = [ - (U1Gate(pi), [q[0]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # from .u1 import U1Gate + # definition = [] + # q = QuantumRegister(1, 'q') + # rule = [ + # (U1Gate(pi), [q[0]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-Z gate. @@ -155,22 +155,22 @@ def __init__(self, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = ZGate() - def _define(self): - """ - gate cz a,b { h b; cx a,b; h b; } - """ - from .h import HGate - from .x import CXGate - definition = [] - q = QuantumRegister(2, 'q') - rule = [ - (HGate(), [q[1]], []), - (CXGate(), [q[0], q[1]], []), - (HGate(), [q[1]], []) - ] - for inst in rule: - definition.append(inst) - self.definition = definition + # def _define(self): + # """ + # gate cz a,b { h b; cx a,b; h b; } + # """ + # from .h import HGate + # from .x import CXGate + # definition = [] + # q = QuantumRegister(2, 'q') + # rule = [ + # (HGate(), [q[1]], []), + # (CXGate(), [q[0], q[1]], []), + # (HGate(), [q[1]], []) + # ] + # for inst in rule: + # definition.append(inst) + # self.definition = definition def inverse(self): """Return inverted CZ gate (itself).""" diff --git a/qiskit/converters/ast_to_dag.py b/qiskit/converters/ast_to_dag.py index 235291f7b6e8..2a9192e56f1d 100644 --- a/qiskit/converters/ast_to_dag.py +++ b/qiskit/converters/ast_to_dag.py @@ -21,7 +21,7 @@ from qiskit.dagcircuit import DAGCircuit from qiskit.exceptions import QiskitError -from qiskit.circuit import QuantumRegister, ClassicalRegister, Gate +from qiskit.circuit import QuantumRegister, ClassicalRegister, Gate, QuantumCircuit from qiskit.qasm.node.real import Real from qiskit.circuit.instruction import Instruction from qiskit.circuit.measure import Measure @@ -363,9 +363,9 @@ def _process_node(self, node): "file=%s" % node.file) return None - def _gate_definition_to_qiskit_definition(self, node, params): - """From a gate definition in qasm, to a gate.definition format.""" - definition = [] + def _gate_rules_to_qiskit_circuit(self, node, params): + """From a gate definition in qasm, to a QuantumCircuit format.""" + rules = [] qreg = QuantumRegister(node['n_bits']) bit_args = {node['bits'][i]: q for i, q in enumerate(qreg)} exp_args = {node['args'][i]: Real(q) for i, q in enumerate(params)} @@ -380,8 +380,10 @@ def _gate_definition_to_qiskit_definition(self, node, params): for param in param_list.children: eparams.append(param.sym(nested_scope=[exp_args])) op = self._create_op(child_op.name, params=eparams) - definition.append((op, qparams, [])) - return definition + rules.append((op, qparams, [])) + circ = QuantumCircuit(qreg) + circ.data = rules + return circ def _create_dag_op(self, name, params, qargs): """ @@ -411,8 +413,8 @@ def _create_op(self, name, params): num_qubits=self.gates[name]['n_bits'], num_clbits=0, params=params) - op.definition = self._gate_definition_to_qiskit_definition(self.gates[name], - params=params) + op.definition = self._gate_rules_to_qiskit_circuit(self.gates[name], + params=params) else: raise QiskitError("unknown operation for ast node name %s" % name) return op diff --git a/qiskit/converters/circuit_to_gate.py b/qiskit/converters/circuit_to_gate.py index ac0d0e36877d..d9234e83556c 100644 --- a/qiskit/converters/circuit_to_gate.py +++ b/qiskit/converters/circuit_to_gate.py @@ -15,6 +15,7 @@ """Helper function for converting a circuit to a gate""" +from qiskit.circuit import QuantumCircuit from qiskit.circuit.gate import Gate from qiskit.circuit.quantumregister import QuantumRegister, Qubit from qiskit.exceptions import QiskitError @@ -86,7 +87,7 @@ def find_bit_position(bit): if equivalence_library is not None: equivalence_library.add_equivalence(gate, target) - definition = target.data + rules = target.data if gate.num_qubits > 0: q = QuantumRegister(gate.num_qubits, 'q') @@ -94,11 +95,12 @@ def find_bit_position(bit): # The 3rd parameter in the output tuple) is hard coded to [] because # Gate objects do not have cregs set and we've verified that all # instructions are gates - definition = list(map( + rules = list(map( lambda x: (x[0], list(map(lambda y: q[find_bit_position(y)], x[1])), []), - definition)) - gate.definition = definition - + rules)) + qc = QuantumCircuit(q, name=gate.name) + qc.data = rules + gate.definition = qc return gate diff --git a/qiskit/converters/circuit_to_instruction.py b/qiskit/converters/circuit_to_instruction.py index e4411f0b257e..ebb830c3ecab 100644 --- a/qiskit/converters/circuit_to_instruction.py +++ b/qiskit/converters/circuit_to_instruction.py @@ -15,6 +15,7 @@ """Helper function for converting a circuit to an instruction.""" from qiskit.exceptions import QiskitError +from qiskit.circuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumregister import QuantumRegister, Qubit from qiskit.circuit.classicalregister import ClassicalRegister @@ -95,15 +96,22 @@ def find_bit_position(bit): definition = target.data + qregs = [] if instruction.num_qubits > 0: q = QuantumRegister(instruction.num_qubits, 'q') + qregs.append(q) + if instruction.num_clbits > 0: c = ClassicalRegister(instruction.num_clbits, 'c') - + qregs.append(c) + definition = list(map(lambda x: (x[0], list(map(lambda y: q[find_bit_position(y)], x[1])), list(map(lambda y: c[find_bit_position(y)], x[2]))), definition)) - instruction.definition = definition + + qc = QuantumCircuit(*qregs, name=instruction.name) + qc.data = definition + instruction.definition = qc return instruction diff --git a/qiskit/extensions/hamiltonian_gate.py b/qiskit/extensions/hamiltonian_gate.py index 05eef9da2dca..64f956a5e57f 100644 --- a/qiskit/extensions/hamiltonian_gate.py +++ b/qiskit/extensions/hamiltonian_gate.py @@ -107,7 +107,9 @@ def transpose(self): def _define(self): """Calculate a subcircuit that implements this unitary.""" q = QuantumRegister(self.num_qubits, 'q') - self.definition = [(UnitaryGate(self.to_matrix()), q[:], [])] + qc = QuantumCircuit(q, name=self.name) + qc.append(UnitaryGate(self.to_matrix()), qargs=q[:]) + self.definition = qc def qasm(self): """Raise an error, as QASM is not defined for the HamiltonianGate.""" diff --git a/qiskit/extensions/quantum_initializer/diagonal.py b/qiskit/extensions/quantum_initializer/diagonal.py index 1083ffd36946..e90a45fd375c 100644 --- a/qiskit/extensions/quantum_initializer/diagonal.py +++ b/qiskit/extensions/quantum_initializer/diagonal.py @@ -77,7 +77,7 @@ def _define(self): q = QuantumRegister(self.num_qubits) diag_circuit = QuantumCircuit(q) diag_circuit.append(gate, q[:]) - self.definition = diag_circuit.data + self.definition = diag_circuit def _dec_diag(self): """ diff --git a/qiskit/extensions/quantum_initializer/initializer.py b/qiskit/extensions/quantum_initializer/initializer.py index 900f9a996d2f..f4dcd0b00ef1 100644 --- a/qiskit/extensions/quantum_initializer/initializer.py +++ b/qiskit/extensions/quantum_initializer/initializer.py @@ -84,7 +84,7 @@ def _define(self): initialize_circuit.append(Reset(), [qubit]) initialize_circuit.append(initialize_instr, q[:]) - self.definition = initialize_circuit.data + self.definition = initialize_circuit def gates_to_uncompute(self): """Call to create a circuit with gates that take the desired vector to zero. diff --git a/qiskit/extensions/quantum_initializer/isometry.py b/qiskit/extensions/quantum_initializer/isometry.py index 24c64ccbeeda..7e48ab28011e 100644 --- a/qiskit/extensions/quantum_initializer/isometry.py +++ b/qiskit/extensions/quantum_initializer/isometry.py @@ -104,7 +104,7 @@ def _define(self): q = QuantumRegister(self.num_qubits) iso_circuit = QuantumCircuit(q) iso_circuit.append(gate, q[:]) - self.definition = iso_circuit.data + self.definition = iso_circuit def _gates_to_uncompute(self): """ diff --git a/qiskit/extensions/quantum_initializer/mcg_up_to_diagonal.py b/qiskit/extensions/quantum_initializer/mcg_up_to_diagonal.py index 01f71829eacf..6fb841cfa8e2 100644 --- a/qiskit/extensions/quantum_initializer/mcg_up_to_diagonal.py +++ b/qiskit/extensions/quantum_initializer/mcg_up_to_diagonal.py @@ -73,7 +73,7 @@ def _define(self): q = QuantumRegister(self.num_qubits) mcg_up_diag_circuit = QuantumCircuit(q) mcg_up_diag_circuit.append(gate, q[:]) - self.definition = mcg_up_diag_circuit.data + self.definition = mcg_up_diag_circuit # Returns the diagonal up to which the gate is implemented. def _get_diagonal(self): diff --git a/qiskit/extensions/quantum_initializer/squ.py b/qiskit/extensions/quantum_initializer/squ.py index 0fbc182de230..817224ca5216 100644 --- a/qiskit/extensions/quantum_initializer/squ.py +++ b/qiskit/extensions/quantum_initializer/squ.py @@ -79,32 +79,34 @@ def _define(self): """Define the gate using the decomposition.""" if self.mode == 'ZYZ': - rule, diag = self._zyz_rule() + circuit, diag = self._zyz_circuit() else: raise QiskitError('The decomposition mode is not known.') self._diag = diag - self.definition = rule + + self.definition = circuit - def _zyz_rule(self): - """Get the circuit rule for the ZYZ decomposition.""" + def _zyz_circuit(self): + """Get the circuit for the ZYZ decomposition.""" q = QuantumRegister(self.num_qubits) + qc = QuantumCircuit(q, name=self.name) rule = [] diag = [1., 1.] alpha, beta, gamma, _ = self._zyz_dec() if abs(alpha) > _EPS: - rule += [(RZGate(alpha), [q[0]], [])] + qc.rz(alpha, q[0]) if abs(beta) > _EPS: - rule += [(RYGate(beta), [q[0]], [])] + qc.ry(beta, q[0]) if abs(gamma) > _EPS: if self.up_to_diagonal: diag = [np.exp(-1j * gamma / 2.), np.exp(1j * gamma / 2.)] else: - rule += [(RZGate(gamma), [q[0]], [])] + qc.rz(gamma, q[0]) - return rule, diag + return qc, diag def _zyz_dec(self): """Finds rotation angles (a,b,c,d) in the decomposition u=exp(id)*Rz(c).Ry(b).Rz(a). diff --git a/qiskit/extensions/quantum_initializer/uc.py b/qiskit/extensions/quantum_initializer/uc.py index bfba80c691b0..1654d2d48e31 100644 --- a/qiskit/extensions/quantum_initializer/uc.py +++ b/qiskit/extensions/quantum_initializer/uc.py @@ -117,7 +117,7 @@ def _get_diagonal(self): def _define(self): ucg_circuit, _ = self._dec_ucg() - self.definition = ucg_circuit.data + self.definition = ucg_circuit def _dec_ucg(self): """ diff --git a/qiskit/extensions/quantum_initializer/uc_pauli_rot.py b/qiskit/extensions/quantum_initializer/uc_pauli_rot.py index d2487f84e0bb..6271d3ba2084 100644 --- a/qiskit/extensions/quantum_initializer/uc_pauli_rot.py +++ b/qiskit/extensions/quantum_initializer/uc_pauli_rot.py @@ -85,7 +85,7 @@ def _define(self): q = QuantumRegister(self.num_qubits) ucr_circuit = QuantumCircuit(q) ucr_circuit.append(gate, q[:]) - self.definition = ucr_circuit.data + self.definition = ucr_circuit def _dec_ucrot(self): """ diff --git a/qiskit/extensions/unitary.py b/qiskit/extensions/unitary.py index 4f48f5f81b2b..271080106a97 100644 --- a/qiskit/extensions/unitary.py +++ b/qiskit/extensions/unitary.py @@ -107,14 +107,17 @@ def _define(self): """Calculate a subcircuit that implements this unitary.""" if self.num_qubits == 1: q = QuantumRegister(1, "q") + qc = QuantumCircuit(q, name=self.name) theta, phi, lam = _DECOMPOSER1Q.angles(self.to_matrix()) - self.definition = [(U3Gate(theta, phi, lam), [q[0]], [])] + qc.u3(theta, phi, lam, q[0]) + self.definition = qc elif self.num_qubits == 2: - self.definition = two_qubit_cnot_decompose(self.to_matrix()).data + self.definition = two_qubit_cnot_decompose(self.to_matrix()) else: q = QuantumRegister(self.num_qubits, "q") - self.definition = [(isometry.Isometry(self.to_matrix(), 0, 0), - q[:], [])] + qc = QuantumCircuit(q, name=self.name) + qc.append(isometry.Isometry(self.to_matrix(), 0, 0), qargs=q[:]) + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): r"""Return controlled version of gate @@ -166,7 +169,7 @@ def qasm(self): current_reg = 0 gates_def = "" - for gate in self.definition: + for gate in self.definition.data: # add regs from this gate to the overall set of params for reg in gate[1] + gate[2]: diff --git a/qiskit/quantum_info/operators/channel/superop.py b/qiskit/quantum_info/operators/channel/superop.py index 399847a9e626..5952cf653ae1 100644 --- a/qiskit/quantum_info/operators/channel/superop.py +++ b/qiskit/quantum_info/operators/channel/superop.py @@ -391,7 +391,10 @@ def _append_instruction(self, obj, qargs=None): if obj.definition is None: raise QiskitError('Cannot apply Instruction: {}'.format( obj.name)) - for instr, qregs, cregs in obj.definition: + if not isinstance(obj.definition, QuantumCircuit): + raise QiskitError('{0} instruction definition is {1}; expected QuantumCircuit'.format( + obj.name, type(obj.definition))) + for instr, qregs, cregs in obj.definition.data: if cregs: raise QiskitError( 'Cannot apply instruction with classical registers: {}' diff --git a/qiskit/quantum_info/operators/operator.py b/qiskit/quantum_info/operators/operator.py index 2d2b9000932b..1478f788939d 100644 --- a/qiskit/quantum_info/operators/operator.py +++ b/qiskit/quantum_info/operators/operator.py @@ -522,7 +522,12 @@ def _append_instruction(self, obj, qargs=None): # cannot compose this gate and raise an error. if obj.definition is None: raise QiskitError('Cannot apply Instruction: {}'.format(obj.name)) - for instr, qregs, cregs in obj.definition: + if not isinstance(obj.definition, QuantumCircuit): + raise QiskitError('Instruction "{}" ' + 'definition is {} but expected QuantumCircuit.'.format( + obj.name, type(obj.definition))) + flat_instr = obj.definition.to_instruction() + for instr, qregs, cregs in flat_instr.definition.data: if cregs: raise QiskitError( 'Cannot apply instruction with classical registers: {}'.format( diff --git a/qiskit/quantum_info/operators/symplectic/clifford_circuits.py b/qiskit/quantum_info/operators/symplectic/clifford_circuits.py index 447e70acaa13..a7b41d4e9b4b 100644 --- a/qiskit/quantum_info/operators/symplectic/clifford_circuits.py +++ b/qiskit/quantum_info/operators/symplectic/clifford_circuits.py @@ -84,7 +84,10 @@ def _append_circuit(clifford, circuit, qargs=None): # are a single qubit Clifford gate rather than raise an exception. if gate.definition is None: raise QiskitError('Cannot apply Instruction: {}'.format(gate.name)) - for instr, qregs, cregs in gate.definition: + if not isinstance(gate.definition, QuantumCircuit): + raise QiskitError('{0} instruction definition is {1}; expected QuantumCircuit'.format( + gate.name, type(gate.definition))) + for instr, qregs, cregs in gate.definition.data: if cregs: raise QiskitError( 'Cannot apply Instruction with classical registers: {}'.format( diff --git a/qiskit/quantum_info/states/densitymatrix.py b/qiskit/quantum_info/states/densitymatrix.py index a200eb1fa8e3..809e336143f7 100644 --- a/qiskit/quantum_info/states/densitymatrix.py +++ b/qiskit/quantum_info/states/densitymatrix.py @@ -575,7 +575,10 @@ def _append_instruction(self, other, qargs=None): if other.definition is None: raise QiskitError('Cannot apply Instruction: {}'.format( other.name)) - for instr, qregs, cregs in other.definition: + if not isinstance(other.definition, QuantumCircuit): + raise QiskitError('{0} instruction definition is {1}; expected QuantumCircuit'.format( + other.name, type(other.definition))) + for instr, qregs, cregs in other.definition.data: if cregs: raise QiskitError( 'Cannot apply instruction with classical registers: {}'. diff --git a/qiskit/quantum_info/states/statevector.py b/qiskit/quantum_info/states/statevector.py index ee457ae55d8e..8503c1f5450a 100644 --- a/qiskit/quantum_info/states/statevector.py +++ b/qiskit/quantum_info/states/statevector.py @@ -617,8 +617,10 @@ def _append_instruction(self, obj, qargs=None): # cannot compose this gate and raise an error. if obj.definition is None: raise QiskitError('Cannot apply Instruction: {}'.format(obj.name)) - - for instr, qregs, cregs in obj.definition: + if not isinstance(obj.definition, QuantumCircuit): + raise QiskitError('{0} instruction definition is {1}; expected QuantumCircuit'.format( + obj.name, type(obj.definition))) + for instr, qregs, cregs in obj.definition.data: if cregs: raise QiskitError( 'Cannot apply instruction with classical registers: {}'.format( diff --git a/qiskit/transpiler/passes/basis/decompose.py b/qiskit/transpiler/passes/basis/decompose.py index 3125874e7c08..3517b6f0c40d 100644 --- a/qiskit/transpiler/passes/basis/decompose.py +++ b/qiskit/transpiler/passes/basis/decompose.py @@ -48,7 +48,7 @@ def run(self, dag: DAGCircuit) -> DAGCircuit: if not node.op.definition: continue # TODO: allow choosing among multiple decomposition rules - rule = node.op.definition + rule = node.op.definition.data if len(rule) == 1 and len(node.qargs) == len(rule[0][1]): dag.substitute_node(node, rule[0][0], inplace=True) diff --git a/qiskit/transpiler/passes/basis/unroll_3q_or_more.py b/qiskit/transpiler/passes/basis/unroll_3q_or_more.py index 968e74011ed3..b95e01998702 100644 --- a/qiskit/transpiler/passes/basis/unroll_3q_or_more.py +++ b/qiskit/transpiler/passes/basis/unroll_3q_or_more.py @@ -34,7 +34,7 @@ def run(self, dag): """ for node in dag.multi_qubit_ops(): # TODO: allow choosing other possible decompositions - rule = node.op.definition + rule = node.op.definition.data if not rule: if rule == []: # empty node dag.remove_op_node(node) diff --git a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py index 4d4e9373d717..8e9bc90dc7a8 100644 --- a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py +++ b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py @@ -66,9 +66,12 @@ def run(self, dag): continue try: - rule = node.op.definition + rule = node.op.definition.data except TypeError as err: raise QiskitError('Error decomposing node {}: {}'.format(node.name, err)) + except AttributeError as aerr: + # definition is None + rule = None if not rule: if rule == []: diff --git a/qiskit/transpiler/passes/basis/unroller.py b/qiskit/transpiler/passes/basis/unroller.py index de878c6f4dad..0763236e1d3c 100644 --- a/qiskit/transpiler/passes/basis/unroller.py +++ b/qiskit/transpiler/passes/basis/unroller.py @@ -69,7 +69,7 @@ def run(self, dag): # TODO: allow choosing other possible decompositions try: - rule = node.op.definition + rule = node.op.definition.data except TypeError as err: raise QiskitError('Error decomposing node {}: {}'.format(node.name, err)) @@ -82,7 +82,7 @@ def run(self, dag): dag.substitute_node(node, rule[0][0], inplace=True) break try: - rule = rule[0][0].definition + rule = rule[0][0].definition.data except TypeError as err: raise QiskitError('Error decomposing node {}: {}'.format(node.name, err)) diff --git a/test/python/circuit/test_controlled_gate.py b/test/python/circuit/test_controlled_gate.py index a9c89863e2ee..5e305614e211 100644 --- a/test/python/circuit/test_controlled_gate.py +++ b/test/python/circuit/test_controlled_gate.py @@ -574,7 +574,9 @@ def test_mcx_gates(self, num_ctrl_qubits): i = int(bin(i)[2:].zfill(circuit.num_qubits)[gate.num_ancilla_qubits:], 2) corrected[i] += statevector_amplitude statevector = corrected - + np.set_printoptions(precision=3, linewidth=200, suppress=True) + # if isinstance(gate, MCXRecursive): + # import ipdb;ipdb.set_trace() np.testing.assert_array_almost_equal(statevector.real, reference) @data(1, 2, 3, 4) @@ -1010,10 +1012,12 @@ def test_controlled_standard_gates(self, num_ctrl_qubits, gate_class): for ctrl_state in {ctrl_state_ones, ctrl_state_zeros, ctrl_state_mixed}: with self.subTest(i='{0}, ctrl_state={1}'.format(gate_class.__name__, ctrl_state)): + np.set_printoptions(precision=3, linewidth=200, suppress=True) if hasattr(gate, 'num_ancilla_qubits') and gate.num_ancilla_qubits > 0: # skip matrices that include ancilla qubits continue try: + #import ipdb;ipdb.set_trace() cgate = gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) except (AttributeError, QiskitError): # 'object has no attribute "control"' @@ -1027,6 +1031,9 @@ def test_controlled_standard_gates(self, num_ctrl_qubits, gate_class): base_mat = Operator(gate).data target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) + + #import ipdb;ipdb.set_trace() + src_mat = Operator(cgate).data self.assertTrue(matrix_equal(Operator(cgate).data, target_mat, ignore_phase=True)) diff --git a/test/python/circuit/test_gate_definitions.py b/test/python/circuit/test_gate_definitions.py index 02673e5fc669..c23c8ce0ecde 100644 --- a/test/python/circuit/test_gate_definitions.py +++ b/test/python/circuit/test_gate_definitions.py @@ -136,7 +136,7 @@ def test_definition_parameters(self, gate_class): param_entry = std_eqlib.get_entry(param_gate) float_entry = std_eqlib.get_entry(float_gate) - if not param_gate.definition: + if not param_gate.definition or not param_gate.definition.data: self.assertEqual(len(param_entry), 0) self.assertEqual(len(float_entry), 0) return diff --git a/test/python/quantum_info/operators/symplectic/test_clifford.py b/test/python/quantum_info/operators/symplectic/test_clifford.py index 971a9fd528ae..8cf3af2252b8 100644 --- a/test/python/quantum_info/operators/symplectic/test_clifford.py +++ b/test/python/quantum_info/operators/symplectic/test_clifford.py @@ -42,7 +42,9 @@ def __init__(self): def _define(self): """V Gate definition.""" q = QuantumRegister(1, 'q') - self.definition = [(SdgGate(), [q[0]], []), (HGate(), [q[0]], [])] + qc = QuantumCircuit(q) + qc.data = [(SdgGate(), [q[0]], []), (HGate(), [q[0]], [])] + self.definition = qc class WGate(Gate): @@ -54,7 +56,9 @@ def __init__(self): def _define(self): """W Gate definition.""" q = QuantumRegister(1, 'q') - self.definition = [(VGate(), [q[0]], []), (VGate(), [q[0]], [])] + qc = QuantumCircuit(q) + qc.data = [(VGate(), [q[0]], []), (VGate(), [q[0]], [])] + self.definition = qc def random_clifford_circuit(num_qubits, num_gates, gates='all', seed=None): diff --git a/test/python/transpiler/test_unroll_custom_definitions.py b/test/python/transpiler/test_unroll_custom_definitions.py index c14c7460ed0b..d90e3b2eb63f 100644 --- a/test/python/transpiler/test_unroll_custom_definitions.py +++ b/test/python/transpiler/test_unroll_custom_definitions.py @@ -92,11 +92,11 @@ def test_unroll_gate_until_reach_basis_gates(self): eq_lib = EquivalenceLibrary() gate = TestCompositeGate() - q = QuantumRegister(1, 'q') - gate.definition = [(TestGate(), [q[0]], [])] + gate.definition = QuantumCircuit(q) + gate.definition.data = [(TestGate(), [q[0]], [])] - qc = QuantumCircuit(1) + qc = QuantumCircuit(q) qc.append(gate, [0]) dag = circuit_to_dag(qc) @@ -121,7 +121,8 @@ def test_unroll_twice_until_we_get_to_eqlib(self): gate = TestCompositeGate() q = QuantumRegister(1, 'q') - gate.definition = [(TestGate(), [q[0]], [])] + gate.definition = QuantumCircuit(q) + gate.definition.data = [(TestGate(), [q[0]], [])] qc = QuantumCircuit(1) qc.append(gate, [0]) From 4a636fa15f3dbc754c573eb8961239a14dcdf8d7 Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Tue, 30 Jun 2020 10:29:16 -0400 Subject: [PATCH 02/11] resolve c_if register conversion --- qiskit/circuit/instruction.py | 9 +- qiskit/circuit/library/standard_gates/x.py | 190 +++++++++--------- qiskit/circuit/quantumcircuit.py | 1 + qiskit/converters/circuit_to_dag.py | 3 + qiskit/converters/circuit_to_instruction.py | 20 +- qiskit/dagcircuit/dagcircuit.py | 1 + qiskit/transpiler/passes/basis/unroller.py | 2 +- .../python/circuit/test_circuit_operations.py | 1 - test/python/circuit/test_controlled_gate.py | 9 +- test/python/circuit/test_instructions.py | 3 +- 10 files changed, 134 insertions(+), 105 deletions(-) diff --git a/qiskit/circuit/instruction.py b/qiskit/circuit/instruction.py index 1e099f29ff64..e16f618a5e17 100644 --- a/qiskit/circuit/instruction.py +++ b/qiskit/circuit/instruction.py @@ -387,6 +387,11 @@ def repeat(self, n): if instruction.definition is None: from qiskit import QuantumCircuit - instruction.definition = QuantumCircuit(self.num_qubits) - instruction.definition.data = [(self, qargs[:], cargs[:])] * n + qc = QuantumCircuit() + if qargs: + qc.add_register(qargs) + if cargs: + qc.add_register(cargs) + qc.data = [(self, qargs[:], cargs[:])] * n + instruction.definition = qc return instruction diff --git a/qiskit/circuit/library/standard_gates/x.py b/qiskit/circuit/library/standard_gates/x.py index e59b7dd5dbf4..03baefa791be 100644 --- a/qiskit/circuit/library/standard_gates/x.py +++ b/qiskit/circuit/library/standard_gates/x.py @@ -471,57 +471,60 @@ def __init__(self, angle=numpy.pi/4, label=None, ctrl_state=None): self.base_gate = XGate() self._angle = angle - # def _define(self): - # """ - # gate c3x a,b,c,d - # { - # h d; cu1(-pi/4) a,d; h d; - # cx a,b; - # h d; cu1(pi/4) b,d; h d; - # cx a,b; - # h d; cu1(-pi/4) b,d; h d; - # cx b,c; - # h d; cu1(pi/4) c,d; h d; - # cx a,c; - # h d; cu1(-pi/4) c,d; h d; - # cx b,c; - # h d; cu1(pi/4) c,d; h d; - # cx a,c; - # h d; cu1(-pi/4) c,d; h d; - # } - # """ - # from .u1 import CU1Gate - # q = QuantumRegister(4, name='q') - # definition = [ - # (HGate(), [q[3]], []), - # (CU1Gate(-self._angle), [q[0], q[3]], []), - # (HGate(), [q[3]], []), - # (CXGate(), [q[0], q[1]], []), - # (HGate(), [q[3]], []), - # (CU1Gate(self._angle), [q[1], q[3]], []), - # (HGate(), [q[3]], []), - # (CXGate(), [q[0], q[1]], []), - # (HGate(), [q[3]], []), - # (CU1Gate(-self._angle), [q[1], q[3]], []), - # (HGate(), [q[3]], []), - # (CXGate(), [q[1], q[2]], []), - # (HGate(), [q[3]], []), - # (CU1Gate(self._angle), [q[2], q[3]], []), - # (HGate(), [q[3]], []), - # (CXGate(), [q[0], q[2]], []), - # (HGate(), [q[3]], []), - # (CU1Gate(-self._angle), [q[2], q[3]], []), - # (HGate(), [q[3]], []), - # (CXGate(), [q[1], q[2]], []), - # (HGate(), [q[3]], []), - # (CU1Gate(self._angle), [q[2], q[3]], []), - # (HGate(), [q[3]], []), - # (CXGate(), [q[0], q[2]], []), - # (HGate(), [q[3]], []), - # (CU1Gate(-self._angle), [q[2], q[3]], []), - # (HGate(), [q[3]], []) - # ] - # self.definition = definition + def _define(self): + """ + gate c3x a,b,c,d + { + h d; cu1(-pi/4) a,d; h d; + cx a,b; + h d; cu1(pi/4) b,d; h d; + cx a,b; + h d; cu1(-pi/4) b,d; h d; + cx b,c; + h d; cu1(pi/4) c,d; h d; + cx a,c; + h d; cu1(-pi/4) c,d; h d; + cx b,c; + h d; cu1(pi/4) c,d; h d; + cx a,c; + h d; cu1(-pi/4) c,d; h d; + } + """ + from qiskit import QuantumCircuit + from .u1 import CU1Gate + q = QuantumRegister(4, name='q') + definition = [ + (HGate(), [q[3]], []), + (CU1Gate(-self._angle), [q[0], q[3]], []), + (HGate(), [q[3]], []), + (CXGate(), [q[0], q[1]], []), + (HGate(), [q[3]], []), + (CU1Gate(self._angle), [q[1], q[3]], []), + (HGate(), [q[3]], []), + (CXGate(), [q[0], q[1]], []), + (HGate(), [q[3]], []), + (CU1Gate(-self._angle), [q[1], q[3]], []), + (HGate(), [q[3]], []), + (CXGate(), [q[1], q[2]], []), + (HGate(), [q[3]], []), + (CU1Gate(self._angle), [q[2], q[3]], []), + (HGate(), [q[3]], []), + (CXGate(), [q[0], q[2]], []), + (HGate(), [q[3]], []), + (CU1Gate(-self._angle), [q[2], q[3]], []), + (HGate(), [q[3]], []), + (CXGate(), [q[1], q[2]], []), + (HGate(), [q[3]], []), + (CU1Gate(self._angle), [q[2], q[3]], []), + (HGate(), [q[3]], []), + (CXGate(), [q[0], q[2]], []), + (HGate(), [q[3]], []), + (CU1Gate(-self._angle), [q[2], q[3]], []), + (HGate(), [q[3]], []) + ] + qc = QuantumCircuit(q) + qc.data = definition + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Controlled version of this gate. @@ -664,47 +667,50 @@ def __init__(self, label=None, ctrl_state=None): self.base_gate = XGate() # seems like open controls not hapening? - # def _define(self): - # """ - # gate c3sqrtx a,b,c,d - # { - # h d; cu1(-pi/8) a,d; h d; - # cx a,b; - # h d; cu1(pi/8) b,d; h d; - # cx a,b; - # h d; cu1(-pi/8) b,d; h d; - # cx b,c; - # h d; cu1(pi/8) c,d; h d; - # cx a,c; - # h d; cu1(-pi/8) c,d; h d; - # cx b,c; - # h d; cu1(pi/8) c,d; h d; - # cx a,c; - # h d; cu1(-pi/8) c,d; h d; - # } - # gate c4x a,b,c,d,e - # { - # h e; cu1(-pi/2) d,e; h e; - # c3x a,b,c,d; - # h d; cu1(pi/4) d,e; h d; - # c3x a,b,c,d; - # c3sqrtx a,b,c,e; - # } - # """ - # from .u1 import CU1Gate - # q = QuantumRegister(5, name='q') - # definition = [ - # (HGate(), [q[4]], []), - # (CU1Gate(-numpy.pi / 2), [q[3], q[4]], []), - # (HGate(), [q[4]], []), - # (C3XGate(), [q[0], q[1], q[2], q[3]], []), - # (HGate(), [q[4]], []), - # (CU1Gate(numpy.pi / 2), [q[3], q[4]], []), - # (HGate(), [q[4]], []), - # (C3XGate(), [q[0], q[1], q[2], q[3]], []), - # (C3XGate(numpy.pi / 8), [q[0], q[1], q[2], q[4]], []), - # ] - # self.definition = definition + def _define(self): + """ + gate c3sqrtx a,b,c,d + { + h d; cu1(-pi/8) a,d; h d; + cx a,b; + h d; cu1(pi/8) b,d; h d; + cx a,b; + h d; cu1(-pi/8) b,d; h d; + cx b,c; + h d; cu1(pi/8) c,d; h d; + cx a,c; + h d; cu1(-pi/8) c,d; h d; + cx b,c; + h d; cu1(pi/8) c,d; h d; + cx a,c; + h d; cu1(-pi/8) c,d; h d; + } + gate c4x a,b,c,d,e + { + h e; cu1(-pi/2) d,e; h e; + c3x a,b,c,d; + h d; cu1(pi/4) d,e; h d; + c3x a,b,c,d; + c3sqrtx a,b,c,e; + } + """ + from qiskit import QuantumCircuit + from .u1 import CU1Gate + q = QuantumRegister(5, name='q') + definition = [ + (HGate(), [q[4]], []), + (CU1Gate(-numpy.pi / 2), [q[3], q[4]], []), + (HGate(), [q[4]], []), + (C3XGate(), [q[0], q[1], q[2], q[3]], []), + (HGate(), [q[4]], []), + (CU1Gate(numpy.pi / 2), [q[3], q[4]], []), + (HGate(), [q[4]], []), + (C3XGate(), [q[0], q[1], q[2], q[3]], []), + (C3XGate(numpy.pi / 8), [q[0], q[1], q[2], q[4]], []), + ] + qc = QuantumCircuit(q) + qc.data = definition + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Controlled version of this gate. diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index 6b417641387b..391a8172f083 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -769,6 +769,7 @@ def _check_cargs(self, cargs): if not all(isinstance(i, Clbit) for i in cargs): raise CircuitError("carg is not a Clbit") if not all(self.has_register(i.register) for i in cargs): + #import ipdb;ipdb.set_trace() raise CircuitError("register not in this circuit") def to_instruction(self, parameter_map=None): diff --git a/qiskit/converters/circuit_to_dag.py b/qiskit/converters/circuit_to_dag.py index eaac9e13e96b..a5a7931bd508 100644 --- a/qiskit/converters/circuit_to_dag.py +++ b/qiskit/converters/circuit_to_dag.py @@ -53,6 +53,9 @@ def circuit_to_dag(circuit): dagcircuit.add_creg(register) for instruction, qargs, cargs in circuit.data: + # print(instruction.name, qargs, cargs) + # if instruction.name == 'h': + # import ipdb;ipdb.set_trace() dagcircuit.apply_operation_back(instruction.copy(), qargs, cargs, instruction.condition) return dagcircuit diff --git a/qiskit/converters/circuit_to_instruction.py b/qiskit/converters/circuit_to_instruction.py index ebb830c3ecab..69b48e8f21c8 100644 --- a/qiskit/converters/circuit_to_instruction.py +++ b/qiskit/converters/circuit_to_instruction.py @@ -78,7 +78,7 @@ def circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None params=sorted(parameter_dict.values(), key=lambda p: p.name)) instruction.condition = None - def find_bit_position(bit): + def find_bit_position(bit): # """find the index of a given bit (Register, int) within a flat ordered list of bits of the circuit """ @@ -96,21 +96,31 @@ def find_bit_position(bit): definition = target.data - qregs = [] + regs = [] if instruction.num_qubits > 0: q = QuantumRegister(instruction.num_qubits, 'q') - qregs.append(q) + regs.append(q) if instruction.num_clbits > 0: c = ClassicalRegister(instruction.num_clbits, 'c') - qregs.append(c) + regs.append(c) definition = list(map(lambda x: (x[0], list(map(lambda y: q[find_bit_position(y)], x[1])), list(map(lambda y: c[find_bit_position(y)], x[2]))), definition)) - qc = QuantumCircuit(*qregs, name=instruction.name) + # fix condition + for rule in definition: + condition = rule[0].condition + if condition: + reg, val = condition + if reg.size == c.size: + rule[0].condition = (c, val) + else: + raise CircuitError('Cannot convert condition in circuit with multiple classical registers to instruction') + + qc = QuantumCircuit(*regs, name=instruction.name) qc.data = definition instruction.definition = qc diff --git a/qiskit/dagcircuit/dagcircuit.py b/qiskit/dagcircuit/dagcircuit.py index d0efbd18911b..75cc5e8b25ca 100644 --- a/qiskit/dagcircuit/dagcircuit.py +++ b/qiskit/dagcircuit/dagcircuit.py @@ -283,6 +283,7 @@ def _check_condition(self, name, condition): """ # Verify creg exists if condition is not None and condition[0].name not in self.cregs: + #import ipdb;ipdb.set_trace() raise DAGCircuitError("invalid creg in condition for %s" % name) def _check_bits(self, args, amap): diff --git a/qiskit/transpiler/passes/basis/unroller.py b/qiskit/transpiler/passes/basis/unroller.py index 0763236e1d3c..2ca85e6df77c 100644 --- a/qiskit/transpiler/passes/basis/unroller.py +++ b/qiskit/transpiler/passes/basis/unroller.py @@ -83,7 +83,7 @@ def run(self, dag): break try: rule = rule[0][0].definition.data - except TypeError as err: + except (TypeError, AttributeError) as err: raise QiskitError('Error decomposing node {}: {}'.format(node.name, err)) else: diff --git a/test/python/circuit/test_circuit_operations.py b/test/python/circuit/test_circuit_operations.py index 85965c3c80c5..01dc94bd74e3 100644 --- a/test/python/circuit/test_circuit_operations.py +++ b/test/python/circuit/test_circuit_operations.py @@ -392,7 +392,6 @@ def test_repeat(self): ref = QuantumCircuit(qr, cr) for _ in range(3): ref.append(inst, ref.qubits, ref.clbits) - rep = qc.repeat(3) self.assertEqual(rep, ref) diff --git a/test/python/circuit/test_controlled_gate.py b/test/python/circuit/test_controlled_gate.py index 5e305614e211..663f126835b4 100644 --- a/test/python/circuit/test_controlled_gate.py +++ b/test/python/circuit/test_controlled_gate.py @@ -211,7 +211,8 @@ def test_multi_control_u3(self): result = job.result() # Circuit unitaries - mat_cnu3 = result.get_unitary(0) + #mat_cnu3 = result.get_unitary(0) # unitary_simulator is giving different output than Operator?? + mat_cnu3 = Operator(qcnu3).data mat_u3 = result.get_unitary(1) mat_cu3 = result.get_unitary(2) @@ -231,8 +232,10 @@ def test_multi_control_u3(self): for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): - self.log.info(info) - self.assertTrue(matrix_equal(target, decomp, ignore_phase=True)) + if info == 'check unitary of cnu3 against tensored unitary of u3': + np.set_printoptions(precision=2, linewidth=300, suppress=True) + import ipdb;ipdb.set_trace() + self.assertTrue(matrix_equal(target, decomp, ignore_phase=True, atol=1e-8, rtol=1e-5)) def test_multi_control_u1(self): """Test the matrix representation of the controlled and controlled-controlled U1 gate.""" diff --git a/test/python/circuit/test_instructions.py b/test/python/circuit/test_instructions.py index 59a50b68bc7f..43b375415a50 100644 --- a/test/python/circuit/test_instructions.py +++ b/test/python/circuit/test_instructions.py @@ -187,7 +187,7 @@ def test_reverse_instruction(self): circ.measure(q[0], c[0]) circ.rz(0.8, q[0]).c_if(c, 6) inst = circ.to_instruction() - + circ = QuantumCircuit(q, c, name='circ') circ.rz(0.8, q[0]).c_if(c, 6) circ.measure(q[0], c[0]) @@ -195,6 +195,7 @@ def test_reverse_instruction(self): circ.u3(0.1, 0.2, -0.2, q[0]) circ.t(q[1]) inst_reverse = circ.to_instruction() + self.assertEqual(inst.reverse_ops().definition, inst_reverse.definition) def test_reverse_opaque(self): From 202d4334ea78e054fc54bb75cbeaf61198fabb51 Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Tue, 30 Jun 2020 22:41:24 -0400 Subject: [PATCH 03/11] revert removal of _define in standard gates --- qiskit/circuit/add_control.py | 1 - qiskit/circuit/controlledgate.py | 4 +- qiskit/circuit/instruction.py | 12 +- qiskit/circuit/library/standard_gates/dcx.py | 24 +- qiskit/circuit/library/standard_gates/h.py | 82 +++--- .../circuit/library/standard_gates/iswap.py | 51 ++-- qiskit/circuit/library/standard_gates/ms.py | 24 +- qiskit/circuit/library/standard_gates/r.py | 31 ++- qiskit/circuit/library/standard_gates/rx.py | 76 ++--- qiskit/circuit/library/standard_gates/rxx.py | 41 +-- qiskit/circuit/library/standard_gates/ry.py | 66 ++--- qiskit/circuit/library/standard_gates/ryy.py | 43 +-- qiskit/circuit/library/standard_gates/rz.py | 68 ++--- qiskit/circuit/library/standard_gates/rzx.py | 29 +- qiskit/circuit/library/standard_gates/rzz.py | 33 +-- qiskit/circuit/library/standard_gates/s.py | 54 ++-- qiskit/circuit/library/standard_gates/swap.py | 70 ++--- qiskit/circuit/library/standard_gates/t.py | 54 ++-- qiskit/circuit/library/standard_gates/u1.py | 65 ++--- qiskit/circuit/library/standard_gates/u2.py | 17 +- qiskit/circuit/library/standard_gates/u3.py | 53 ++-- qiskit/circuit/library/standard_gates/x.py | 261 ++++++++++-------- qiskit/circuit/library/standard_gates/y.py | 55 ++-- qiskit/circuit/library/standard_gates/z.py | 54 ++-- qiskit/circuit/quantumcircuit.py | 1 - qiskit/converters/circuit_to_dag.py | 3 - qiskit/converters/circuit_to_instruction.py | 7 +- qiskit/dagcircuit/dagcircuit.py | 1 - qiskit/extensions/quantum_initializer/squ.py | 6 +- qiskit/extensions/unitary.py | 1 - .../quantum_info/operators/channel/superop.py | 5 +- .../passes/basis/unroll_custom_definitions.py | 2 +- test/python/circuit/test_controlled_gate.py | 36 +-- test/python/circuit/test_instructions.py | 2 +- test/python/circuit/test_library.py | 1 - 35 files changed, 678 insertions(+), 655 deletions(-) diff --git a/qiskit/circuit/add_control.py b/qiskit/circuit/add_control.py index 7ea93e100a3c..1209ad92b05f 100644 --- a/qiskit/circuit/add_control.py +++ b/qiskit/circuit/add_control.py @@ -129,7 +129,6 @@ def control(operation: Union[Gate, ControlledGate], else: bgate = _unroll_gate(operation, ['u1', 'u3', 'cx']) # now we have a bunch of single qubit rotation gates and cx - bgate.definition.data for rule in bgate.definition.data: if rule[0].name == 'u3': theta, phi, lamb = rule[0].params diff --git a/qiskit/circuit/controlledgate.py b/qiskit/circuit/controlledgate.py index 4794a7c41736..4ae456aec9bc 100644 --- a/qiskit/circuit/controlledgate.py +++ b/qiskit/circuit/controlledgate.py @@ -14,13 +14,11 @@ """Controlled unitary gate.""" -from typing import Tuple, List, Optional, Union +from typing import List, Optional, Union from qiskit.circuit.exceptions import CircuitError from .gate import Gate from .quantumregister import QuantumRegister -from .quantumregister import Qubit -from .classicalregister import Clbit # pylint: disable=missing-return-doc diff --git a/qiskit/circuit/instruction.py b/qiskit/circuit/instruction.py index e16f618a5e17..ea7eb4807c06 100644 --- a/qiskit/circuit/instruction.py +++ b/qiskit/circuit/instruction.py @@ -128,11 +128,7 @@ def __eq__(self, other): def _define(self): """Populates self.definition with a decomposition of this gate.""" - try: - self._definition = self.decompositions[0] - except IndexError: - # u3 or cx - pass + pass @property def params(self): @@ -183,10 +179,11 @@ def definition(self): @definition.setter def definition(self, definition): """Set gate representation""" + # pylint: disable=cyclic-import from qiskit import QuantumCircuit if not isinstance(definition, QuantumCircuit) and definition is not None: - raise CircuitError('Instruction definition must be QuantumCircuit. Got {}'.format( - type(definition))) + raise CircuitError('Instruction "{}" definition must be QuantumCircuit. Got {}'.format( + self.name, type(definition))) self._definition = definition @property @@ -386,6 +383,7 @@ def repeat(self, n): cargs = [] if self.num_clbits == 0 else ClassicalRegister(self.num_clbits, 'c') if instruction.definition is None: + # pylint: disable=cyclic-import from qiskit import QuantumCircuit qc = QuantumCircuit() if qargs: diff --git a/qiskit/circuit/library/standard_gates/dcx.py b/qiskit/circuit/library/standard_gates/dcx.py index a54146f0bd19..1b681ae22268 100644 --- a/qiskit/circuit/library/standard_gates/dcx.py +++ b/qiskit/circuit/library/standard_gates/dcx.py @@ -50,16 +50,20 @@ def __init__(self): """Create new DCX gate.""" super().__init__('dcx', 2, []) - # def _define(self): - # """ - # gate dcx a, b { cx a, b; cx a, b; } - # """ - # from .x import CXGate - # q = QuantumRegister(2, 'q') - # self.definition = [ - # (CXGate(), [q[0], q[1]], []), - # (CXGate(), [q[1], q[0]], []) - # ] + def _define(self): + """ + gate dcx a, b { cx a, b; cx a, b; } + """ + from qiskit import QuantumCircuit + from .x import CXGate + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (CXGate(), [q[0], q[1]], []), + (CXGate(), [q[1], q[0]], []) + ] + qc.data = rules + self.definition = qc def to_matrix(self): """Return a numpy.array for the DCX gate.""" diff --git a/qiskit/circuit/library/standard_gates/h.py b/qiskit/circuit/library/standard_gates/h.py index bead4fc368e2..0249ce57a03a 100644 --- a/qiskit/circuit/library/standard_gates/h.py +++ b/qiskit/circuit/library/standard_gates/h.py @@ -53,19 +53,20 @@ def __init__(self, label=None): """Create new H gate.""" super().__init__('h', 1, [], label=label) - # def _define(self): - # """ - # gate h a { u2(0,pi) a; } - # """ - # from .u2 import U2Gate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (U2Gate(0, pi), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate h a { u2(0,pi) a; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u2 import U2Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U2Gate(0, pi), [q[0]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (multi-)controlled-H gate. @@ -169,33 +170,34 @@ def __init__(self, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = HGate() - # def _define(self): - # """ - # gate ch a,b { - # s b; - # h b; - # t b; - # cx a, b; - # tdg b; - # h b; - # sdg b; - # } - # """ - # from .x import CXGate # pylint: disable=cyclic-import - # definition = [] - # q = QuantumRegister(2, 'q') - # rule = [ - # (SGate(), [q[1]], []), - # (HGate(), [q[1]], []), - # (TGate(), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (TdgGate(), [q[1]], []), - # (HGate(), [q[1]], []), - # (SdgGate(), [q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate ch a,b { + s b; + h b; + t b; + cx a, b; + tdg b; + h b; + sdg b; + } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .x import CXGate # pylint: disable=cyclic-import + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (SGate(), [q[1]], []), + (HGate(), [q[1]], []), + (TGate(), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (TdgGate(), [q[1]], []), + (HGate(), [q[1]], []), + (SdgGate(), [q[1]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverted CH gate (itself).""" diff --git a/qiskit/circuit/library/standard_gates/iswap.py b/qiskit/circuit/library/standard_gates/iswap.py index 3567d23c23b8..cfaa76c0f34a 100644 --- a/qiskit/circuit/library/standard_gates/iswap.py +++ b/qiskit/circuit/library/standard_gates/iswap.py @@ -81,29 +81,34 @@ def __init__(self): """Create new iSwap gate.""" super().__init__('iswap', 2, []) - # def _define(self): - # """ - # gate iswap a,b { - # s q[0]; - # s q[1]; - # h q[0]; - # cx q[0],q[1]; - # cx q[1],q[0]; - # h q[1]; - # } - # """ - # from .h import HGate - # from .s import SGate - # from .x import CXGate - # q = QuantumRegister(2, 'q') - # self.definition = [ - # (SGate(), [q[0]], []), - # (SGate(), [q[1]], []), - # (HGate(), [q[0]], []), - # (CXGate(), [q[0], q[1]], []), - # (CXGate(), [q[1], q[0]], []), - # (HGate(), [q[1]], []) - # ] + def _define(self): + """ + gate iswap a,b { + s q[0]; + s q[1]; + h q[0]; + cx q[0],q[1]; + cx q[1],q[0]; + h q[1]; + } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .h import HGate + from .s import SGate + from .x import CXGate + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (SGate(), [q[0]], []), + (SGate(), [q[1]], []), + (HGate(), [q[0]], []), + (CXGate(), [q[0], q[1]], []), + (CXGate(), [q[1], q[0]], []), + (HGate(), [q[1]], []) + ] + qc.data = rules + self.definition = qc def to_matrix(self): """Return a numpy.array for the iSWAP gate.""" diff --git a/qiskit/circuit/library/standard_gates/ms.py b/qiskit/circuit/library/standard_gates/ms.py index 20b3a9043750..e987cb232ff8 100644 --- a/qiskit/circuit/library/standard_gates/ms.py +++ b/qiskit/circuit/library/standard_gates/ms.py @@ -35,15 +35,15 @@ def __init__(self, num_qubits, theta, *, n_qubits=None, # pylint:disable=unused """Create new MS gate.""" super().__init__('ms', num_qubits, [theta], label=label) - # def _define(self): - # from .rxx import RXXGate - # definition = [] - # q = QuantumRegister(self.num_qubits, 'q') - # rule = [] - # for i in range(self.num_qubits): - # for j in range(i + 1, self.num_qubits): - # rule += [(RXXGate(self.params[0]), [q[i], q[j]], [])] - - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .rxx import RXXGate + q = QuantumRegister(self.num_qubits, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [] + for i in range(self.num_qubits): + for j in range(i + 1, self.num_qubits): + rules += [(RXXGate(self.params[0]), [q[i], q[j]], [])] + qc.data = rules + self.definition = qc diff --git a/qiskit/circuit/library/standard_gates/r.py b/qiskit/circuit/library/standard_gates/r.py index 43780ec47122..76c16e4cdce2 100644 --- a/qiskit/circuit/library/standard_gates/r.py +++ b/qiskit/circuit/library/standard_gates/r.py @@ -48,21 +48,22 @@ def __init__(self, theta, phi): """Create new r single-qubit gate.""" super().__init__('r', 1, [theta, phi]) - # def _define(self): - # """ - # gate r(θ, φ) a {u3(θ, φ - π/2, -φ + π/2) a;} - # """ - # from .u3 import U3Gate - # definition = [] - # q = QuantumRegister(1, 'q') - # theta = self.params[0] - # phi = self.params[1] - # rule = [ - # (U3Gate(theta, phi - pi / 2, -phi + pi / 2), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate r(θ, φ) a {u3(θ, φ - π/2, -φ + π/2) a;} + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u3 import U3Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + theta = self.params[0] + phi = self.params[1] + rules = [ + (U3Gate(theta, phi - pi / 2, -phi + pi / 2), [q[0]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Invert this gate. diff --git a/qiskit/circuit/library/standard_gates/rx.py b/qiskit/circuit/library/standard_gates/rx.py index bfdb142c1ac8..d006aeed8048 100644 --- a/qiskit/circuit/library/standard_gates/rx.py +++ b/qiskit/circuit/library/standard_gates/rx.py @@ -50,19 +50,19 @@ def __init__(self, theta, label=None): """Create new RX gate.""" super().__init__('rx', 1, [theta], label=label) - # def _define(self): - # """ - # gate rx(theta) a {r(theta, 0) a;} - # """ - # from .r import RGate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (RGate(self.params[0], 0), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate rx(theta) a {r(theta, 0) a;} + """ + from qiskit import QuantumCircuit + from .r import RGate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (RGate(self.params[0], 0), [q[0]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-RX gate. @@ -168,31 +168,31 @@ def __init__(self, theta, label=None, ctrl_state=None): label=label, ctrl_state=ctrl_state) self.base_gate = RXGate(theta) - # def _define(self): - # """ - # gate cu3(theta,phi,lambda) c, t - # { u1(pi/2) t; - # cx c,t; - # u3(-theta/2,0,0) t; - # cx c,t; - # u3(theta/2,-pi/2,0) t; - # } - # """ - # from .u1 import U1Gate - # from .u3 import U3Gate - # from .x import CXGate - # definition = [] - # q = QuantumRegister(2, 'q') - # rule = [ - # (U1Gate(pi / 2), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (U3Gate(-self.params[0] / 2, 0, 0), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (U3Gate(self.params[0] / 2, -pi / 2, 0), [q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate cu3(theta,phi,lambda) c, t + { u1(pi/2) t; + cx c,t; + u3(-theta/2,0,0) t; + cx c,t; + u3(theta/2,-pi/2,0) t; + } + """ + from qiskit import QuantumCircuit + from .u1 import U1Gate + from .u3 import U3Gate + from .x import CXGate + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U1Gate(pi / 2), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (U3Gate(-self.params[0] / 2, 0, 0), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (U3Gate(self.params[0] / 2, -pi / 2, 0), [q[1]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse RX gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/rxx.py b/qiskit/circuit/library/standard_gates/rxx.py index 31955469507b..942c38e7d850 100644 --- a/qiskit/circuit/library/standard_gates/rxx.py +++ b/qiskit/circuit/library/standard_gates/rxx.py @@ -72,26 +72,27 @@ def __init__(self, theta): """Create new RXX gate.""" super().__init__('rxx', 2, [theta]) - # def _define(self): - # """Calculate a subcircuit that implements this unitary.""" - # from .x import CXGate - # from .u1 import U1Gate - # from .h import HGate - # definition = [] - # q = QuantumRegister(2, 'q') - # theta = self.params[0] - # rule = [ - # (HGate(), [q[0]], []), - # (HGate(), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (U1Gate(theta), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (HGate(), [q[1]], []), - # (HGate(), [q[0]], []), - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """Calculate a subcircuit that implements this unitary.""" + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .x import CXGate + from .u1 import U1Gate + from .h import HGate + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + theta = self.params[0] + rules = [ + (HGate(), [q[0]], []), + (HGate(), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (U1Gate(theta), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (HGate(), [q[1]], []), + (HGate(), [q[0]], []), + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse RXX gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/ry.py b/qiskit/circuit/library/standard_gates/ry.py index f66438c52902..4088b2956006 100644 --- a/qiskit/circuit/library/standard_gates/ry.py +++ b/qiskit/circuit/library/standard_gates/ry.py @@ -50,19 +50,19 @@ def __init__(self, theta, label=None): """Create new RY gate.""" super().__init__('ry', 1, [theta], label=label) - # def _define(self): - # """ - # gate ry(theta) a { r(theta, pi/2) a; } - # """ - # from .r import RGate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (RGate(self.params[0], pi / 2), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate ry(theta) a { r(theta, pi/2) a; } + """ + from qiskit import QuantumCircuit + from .r import RGate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (RGate(self.params[0], pi / 2), [q[0]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-RY gate. @@ -168,26 +168,26 @@ def __init__(self, theta, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = RYGate(theta) - # def _define(self): - # """ - # gate cry(lambda) a,b - # { u3(lambda/2,0,0) b; cx a,b; - # u3(-lambda/2,0,0) b; cx a,b; - # } - # """ - # from .u3 import U3Gate - # from .x import CXGate - # definition = [] - # q = QuantumRegister(2, 'q') - # rule = [ - # (U3Gate(self.params[0] / 2, 0, 0), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (U3Gate(-self.params[0] / 2, 0, 0), [q[1]], []), - # (CXGate(), [q[0], q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate cry(lambda) a,b + { u3(lambda/2,0,0) b; cx a,b; + u3(-lambda/2,0,0) b; cx a,b; + } + """ + from qiskit import QuantumCircuit + from .u3 import U3Gate + from .x import CXGate + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U3Gate(self.params[0] / 2, 0, 0), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (U3Gate(-self.params[0] / 2, 0, 0), [q[1]], []), + (CXGate(), [q[0], q[1]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse RY gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/ryy.py b/qiskit/circuit/library/standard_gates/ryy.py index 5e4b2ac45dc4..09c45a6352e7 100644 --- a/qiskit/circuit/library/standard_gates/ryy.py +++ b/qiskit/circuit/library/standard_gates/ryy.py @@ -73,27 +73,28 @@ def __init__(self, theta): """Create new RYY gate.""" super().__init__('ryy', 2, [theta]) - # def _define(self): - # """Calculate a subcircuit that implements this unitary.""" - # from .x import CXGate - # from .rx import RXGate - # from .rz import RZGate - - # definition = [] - # q = QuantumRegister(2, 'q') - # theta = self.params[0] - # rule = [ - # (RXGate(np.pi / 2), [q[0]], []), - # (RXGate(np.pi / 2), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (RZGate(theta), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (RXGate(-np.pi / 2), [q[0]], []), - # (RXGate(-np.pi / 2), [q[1]], []), - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """Calculate a subcircuit that implements this unitary.""" + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .x import CXGate + from .rx import RXGate + from .rz import RZGate + + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + theta = self.params[0] + rules = [ + (RXGate(np.pi / 2), [q[0]], []), + (RXGate(np.pi / 2), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (RZGate(theta), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (RXGate(-np.pi / 2), [q[0]], []), + (RXGate(-np.pi / 2), [q[1]], []), + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse RYY gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/rz.py b/qiskit/circuit/library/standard_gates/rz.py index 1c0d13bfe738..5a506ef52627 100644 --- a/qiskit/circuit/library/standard_gates/rz.py +++ b/qiskit/circuit/library/standard_gates/rz.py @@ -60,19 +60,20 @@ def __init__(self, phi, label=None): """Create new RZ gate.""" super().__init__('rz', 1, [phi], label=label) - # def _define(self): - # """ - # gate rz(phi) a { u1(phi) a; } - # """ - # from .u1 import U1Gate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (U1Gate(self.params[0]), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate rz(phi) a { u1(phi) a; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u1 import U1Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U1Gate(self.params[0]), [q[0]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-RZ gate. @@ -186,26 +187,27 @@ def __init__(self, theta, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = RZGate(theta) - # def _define(self): - # """ - # gate crz(lambda) a,b - # { u1(lambda/2) b; cx a,b; - # u1(-lambda/2) b; cx a,b; - # } - # """ - # from .u1 import U1Gate - # from .x import CXGate - # definition = [] - # q = QuantumRegister(2, 'q') - # rule = [ - # (U1Gate(self.params[0] / 2), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (U1Gate(-self.params[0] / 2), [q[1]], []), - # (CXGate(), [q[0], q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate crz(lambda) a,b + { u1(lambda/2) b; cx a,b; + u1(-lambda/2) b; cx a,b; + } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u1 import U1Gate + from .x import CXGate + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U1Gate(self.params[0] / 2), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (U1Gate(-self.params[0] / 2), [q[1]], []), + (CXGate(), [q[0], q[1]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse RZ gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/rzx.py b/qiskit/circuit/library/standard_gates/rzx.py index 1d3ae2e99cc1..4f4236e4c8c8 100644 --- a/qiskit/circuit/library/standard_gates/rzx.py +++ b/qiskit/circuit/library/standard_gates/rzx.py @@ -121,18 +121,23 @@ def __init__(self, theta): """Create new RZX gate.""" super().__init__('rzx', 2, [theta]) - # def _define(self): - # """ - # gate rzx(theta) a, b { h b; cx a, b; u1(theta) b; cx a, b; h b;} - # """ - # q = QuantumRegister(2, 'q') - # self.definition = [ - # (HGate(), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (RZGate(self.params[0]), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (HGate(), [q[1]], []) - # ] + def _define(self): + """ + gate rzx(theta) a, b { h b; cx a, b; u1(theta) b; cx a, b; h b;} + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (HGate(), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (RZGate(self.params[0]), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (HGate(), [q[1]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse RZX gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/rzz.py b/qiskit/circuit/library/standard_gates/rzz.py index b426434fbf3f..1acf95b9a897 100644 --- a/qiskit/circuit/library/standard_gates/rzz.py +++ b/qiskit/circuit/library/standard_gates/rzz.py @@ -85,22 +85,23 @@ def __init__(self, theta): """Create new RZZ gate.""" super().__init__('rzz', 2, [theta]) - # def _define(self): - # """ - # gate rzz(theta) a, b { cx a, b; u1(theta) b; cx a, b; } - # """ - # from .u1 import U1Gate - # from .x import CXGate - # definition = [] - # q = QuantumRegister(2, 'q') - # rule = [ - # (CXGate(), [q[0], q[1]], []), - # (U1Gate(self.params[0]), [q[1]], []), - # (CXGate(), [q[0], q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate rzz(theta) a, b { cx a, b; u1(theta) b; cx a, b; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u1 import U1Gate + from .x import CXGate + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (CXGate(), [q[0], q[1]], []), + (U1Gate(self.params[0]), [q[1]], []), + (CXGate(), [q[0], q[1]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse RZZ gate (i.e. with the negative rotation angle).""" diff --git a/qiskit/circuit/library/standard_gates/s.py b/qiskit/circuit/library/standard_gates/s.py index 497b7ec675c2..16b8239caadc 100644 --- a/qiskit/circuit/library/standard_gates/s.py +++ b/qiskit/circuit/library/standard_gates/s.py @@ -51,19 +51,20 @@ def __init__(self, label=None): """Create new S gate.""" super().__init__('s', 1, [], label=label) - # def _define(self): - # """ - # gate s a { u1(pi/2) a; } - # """ - # from .u1 import U1Gate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (U1Gate(pi / 2), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate s a { u1(pi/2) a; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u1 import U1Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U1Gate(pi / 2), [q[0]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse of S (SdgGate).""" @@ -106,19 +107,20 @@ def __init__(self, label=None): """Create new Sdg gate.""" super().__init__('sdg', 1, [], label=label) - # def _define(self): - # """ - # gate sdg a { u1(-pi/2) a; } - # """ - # from .u1 import U1Gate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (U1Gate(-pi / 2), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate sdg a { u1(-pi/2) a; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u1 import U1Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U1Gate(-pi / 2), [q[0]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse of Sdg (SGate).""" diff --git a/qiskit/circuit/library/standard_gates/swap.py b/qiskit/circuit/library/standard_gates/swap.py index 864ffc2e0502..4b2f9e95c952 100644 --- a/qiskit/circuit/library/standard_gates/swap.py +++ b/qiskit/circuit/library/standard_gates/swap.py @@ -56,21 +56,22 @@ def __init__(self, label=None): """Create new SWAP gate.""" super().__init__('swap', 2, [], label=label) - # def _define(self): - # """ - # gate swap a,b { cx a,b; cx b,a; cx a,b; } - # """ - # from .x import CXGate - # definition = [] - # q = QuantumRegister(2, 'q') - # rule = [ - # (CXGate(), [q[0], q[1]], []), - # (CXGate(), [q[1], q[0]], []), - # (CXGate(), [q[0], q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate swap a,b { cx a,b; cx b,a; cx a,b; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .x import CXGate + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (CXGate(), [q[0], q[1]], []), + (CXGate(), [q[1], q[0]], []), + (CXGate(), [q[0], q[1]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (multi-)controlled-SWAP gate. @@ -210,25 +211,26 @@ def __init__(self, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = SwapGate() - # def _define(self): - # """ - # gate cswap a,b,c - # { cx c,b; - # ccx a,b,c; - # cx c,b; - # } - # """ - # from .x import CXGate, CCXGate - # definition = [] - # q = QuantumRegister(3, 'q') - # rule = [ - # (CXGate(), [q[2], q[1]], []), - # (CCXGate(), [q[0], q[1], q[2]], []), - # (CXGate(), [q[2], q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate cswap a,b,c + { cx c,b; + ccx a,b,c; + cx c,b; + } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .x import CXGate, CCXGate + q = QuantumRegister(3, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (CXGate(), [q[2], q[1]], []), + (CCXGate(), [q[0], q[1], q[2]], []), + (CXGate(), [q[2], q[1]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse CSwap gate (itself).""" diff --git a/qiskit/circuit/library/standard_gates/t.py b/qiskit/circuit/library/standard_gates/t.py index 8950a6efeecb..9d6b4aa71213 100644 --- a/qiskit/circuit/library/standard_gates/t.py +++ b/qiskit/circuit/library/standard_gates/t.py @@ -52,19 +52,20 @@ def __init__(self, label=None): """Create new T gate.""" super().__init__('t', 1, [], label=label) - # def _define(self): - # """ - # gate t a { u1(pi/4) a; } - # """ - # from .u1 import U1Gate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (U1Gate(pi / 4), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate t a { u1(pi/4) a; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u1 import U1Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U1Gate(pi / 4), [q[0]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse T gate (i.e. Tdg).""" @@ -107,19 +108,20 @@ def __init__(self, label=None): """Create new Tdg gate.""" super().__init__('tdg', 1, [], label=label) - # def _define(self): - # """ - # gate tdg a { u1(pi/4) a; } - # """ - # from .u1 import U1Gate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (U1Gate(-pi / 4), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate tdg a { u1(pi/4) a; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u1 import U1Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U1Gate(-pi / 4), [q[0]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverse Tdg gate (i.e. T).""" diff --git a/qiskit/circuit/library/standard_gates/u1.py b/qiskit/circuit/library/standard_gates/u1.py index b5939b5fa8cc..74f72a08c9a6 100644 --- a/qiskit/circuit/library/standard_gates/u1.py +++ b/qiskit/circuit/library/standard_gates/u1.py @@ -79,16 +79,17 @@ def __init__(self, theta, label=None): """Create new U1 gate.""" super().__init__('u1', 1, [theta], label=label) - # def _define(self): - # from .u3 import U3Gate # pylint: disable=cyclic-import - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (U3Gate(0, 0, self.params[0]), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u3 import U3Gate # pylint: disable=cyclic-import + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U3Gate(0, 0, self.params[0]), [q[0]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-U1 gate. @@ -175,27 +176,28 @@ def __init__(self, theta, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = U1Gate(theta) - # def _define(self): - # """ - # gate cu1(lambda) a,b - # { u1(lambda/2) a; cx a,b; - # u1(-lambda/2) b; cx a,b; - # u1(lambda/2) b; - # } - # """ - # from .x import CXGate # pylint: disable=cyclic-import - # definition = [] - # q = QuantumRegister(2, 'q') - # rule = [ - # (U1Gate(self.params[0] / 2), [q[0]], []), - # (CXGate(), [q[0], q[1]], []), - # (U1Gate(-self.params[0] / 2), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (U1Gate(self.params[0] / 2), [q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate cu1(lambda) a,b + { u1(lambda/2) a; cx a,b; + u1(-lambda/2) b; cx a,b; + u1(lambda/2) b; + } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .x import CXGate # pylint: disable=cyclic-import + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U1Gate(self.params[0] / 2), [q[0]], []), + (CXGate(), [q[0], q[1]], []), + (U1Gate(-self.params[0] / 2), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (U1Gate(self.params[0] / 2), [q[1]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Controlled version of this gate. @@ -275,6 +277,7 @@ def __init__(self, lam, num_ctrl_qubits, label=None): self.base_gate = U1Gate(lam) def _define(self): + # pylint: disable=cyclic-import from qiskit import QuantumCircuit q = QuantumRegister(self.num_qubits, 'q') qc = QuantumCircuit(q, name=self.name) diff --git a/qiskit/circuit/library/standard_gates/u2.py b/qiskit/circuit/library/standard_gates/u2.py index ea299cc68fa2..c6ee740becf5 100644 --- a/qiskit/circuit/library/standard_gates/u2.py +++ b/qiskit/circuit/library/standard_gates/u2.py @@ -63,14 +63,15 @@ def __init__(self, phi, lam, label=None): """Create new U2 gate.""" super().__init__('u2', 1, [phi, lam], label=label) - # def _define(self): - # from .u3 import U3Gate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [(U3Gate(pi / 2, self.params[0], self.params[1]), [q[0]], [])] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u3 import U3Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [(U3Gate(pi / 2, self.params[0], self.params[1]), [q[0]], [])] + qc.data = rules + self.definition = qc def inverse(self): r"""Return inverted U2 gate. diff --git a/qiskit/circuit/library/standard_gates/u3.py b/qiskit/circuit/library/standard_gates/u3.py index f05772b64f76..ae58f0738b42 100644 --- a/qiskit/circuit/library/standard_gates/u3.py +++ b/qiskit/circuit/library/standard_gates/u3.py @@ -180,32 +180,33 @@ def __init__(self, theta, phi, lam, label=None, ctrl_state=None): label=label, ctrl_state=ctrl_state) self.base_gate = U3Gate(theta, phi, lam) - # def _define(self): - # """ - # gate cu3(theta,phi,lambda) c, t - # { u1((lambda+phi)/2) c; - # u1((lambda-phi)/2) t; - # cx c,t; - # u3(-theta/2,0,-(phi+lambda)/2) t; - # cx c,t; - # u3(theta/2,phi,0) t; - # } - # """ - # from .u1 import U1Gate - # from .x import CXGate # pylint: disable=cyclic-import - # definition = [] - # q = QuantumRegister(2, 'q') - # rule = [ - # (U1Gate((self.params[2] + self.params[1]) / 2), [q[0]], []), - # (U1Gate((self.params[2] - self.params[1]) / 2), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (U3Gate(-self.params[0] / 2, 0, -(self.params[1] + self.params[2]) / 2), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (U3Gate(self.params[0] / 2, self.params[1], 0), [q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate cu3(theta,phi,lambda) c, t + { u1((lambda+phi)/2) c; + u1((lambda-phi)/2) t; + cx c,t; + u3(-theta/2,0,-(phi+lambda)/2) t; + cx c,t; + u3(theta/2,phi,0) t; + } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u1 import U1Gate + from .x import CXGate # pylint: disable=cyclic-import + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U1Gate((self.params[2] + self.params[1]) / 2), [q[0]], []), + (U1Gate((self.params[2] - self.params[1]) / 2), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (U3Gate(-self.params[0] / 2, 0, -(self.params[1] + self.params[2]) / 2), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (U3Gate(self.params[0] / 2, self.params[1], 0), [q[1]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): r"""Return inverted CU3 gate. diff --git a/qiskit/circuit/library/standard_gates/x.py b/qiskit/circuit/library/standard_gates/x.py index 03baefa791be..1afef22c3e92 100644 --- a/qiskit/circuit/library/standard_gates/x.py +++ b/qiskit/circuit/library/standard_gates/x.py @@ -74,11 +74,20 @@ def __init__(self, label=None): """Create new X gate.""" super().__init__('x', 1, [], label=label) - # def _define(self): - # """ - # gate x a { u3(pi,0,pi) a; } - # """ - # self.definition = self.decompositions[0] + def _define(self): + """ + gate x a { u3(pi,0,pi) a; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u3 import U3Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U3Gate(pi, 0, pi), [q[0]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-X gate. @@ -312,41 +321,38 @@ def __init__(self, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = XGate() - # def _define(self): - # circ = self.decompositions[0] - # self._definition = circ - - # def _define(self): - # """ - # gate ccx a,b,c - # { - # h c; cx b,c; tdg c; cx a,c; - # t c; cx b,c; tdg c; cx a,c; - # t b; t c; h c; cx a,b; - # t a; tdg b; cx a,b;} - # """ - # definition = [] - # q = QuantumRegister(3, 'q') - # rule = [ - # (HGate(), [q[2]], []), - # (CXGate(), [q[1], q[2]], []), - # (TdgGate(), [q[2]], []), - # (CXGate(), [q[0], q[2]], []), - # (TGate(), [q[2]], []), - # (CXGate(), [q[1], q[2]], []), - # (TdgGate(), [q[2]], []), - # (CXGate(), [q[0], q[2]], []), - # (TGate(), [q[1]], []), - # (TGate(), [q[2]], []), - # (HGate(), [q[2]], []), - # (CXGate(), [q[0], q[1]], []), - # (TGate(), [q[0]], []), - # (TdgGate(), [q[1]], []), - # (CXGate(), [q[0], q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate ccx a,b,c + { + h c; cx b,c; tdg c; cx a,c; + t c; cx b,c; tdg c; cx a,c; + t b; t c; h c; cx a,b; + t a; tdg b; cx a,b;} + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + q = QuantumRegister(3, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (HGate(), [q[2]], []), + (CXGate(), [q[1], q[2]], []), + (TdgGate(), [q[2]], []), + (CXGate(), [q[0], q[2]], []), + (TGate(), [q[2]], []), + (CXGate(), [q[1], q[2]], []), + (TdgGate(), [q[2]], []), + (CXGate(), [q[0], q[2]], []), + (TGate(), [q[1]], []), + (TGate(), [q[2]], []), + (HGate(), [q[2]], []), + (CXGate(), [q[0], q[1]], []), + (TGate(), [q[0]], []), + (TdgGate(), [q[1]], []), + (CXGate(), [q[0], q[1]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Controlled version of this gate. @@ -407,34 +413,37 @@ def __init__(self, label=None): """Create a new simplified CCX gate.""" super().__init__('rccx', 3, [], label=label) - # def _define(self): - # """ - # gate rccx a,b,c - # { u2(0,pi) c; - # u1(pi/4) c; - # cx b, c; - # u1(-pi/4) c; - # cx a, c; - # u1(pi/4) c; - # cx b, c; - # u1(-pi/4) c; - # u2(0,pi) c; - # } - # """ - # definition = [] - # q = QuantumRegister(3, 'q') - # definition = [ - # (U2Gate(0, pi), [q[2]], []), # H gate - # (U1Gate(pi / 4), [q[2]], []), # T gate - # (CXGate(), [q[1], q[2]], []), - # (U1Gate(-pi / 4), [q[2]], []), # inverse T gate - # (CXGate(), [q[0], q[2]], []), - # (U1Gate(pi / 4), [q[2]], []), - # (CXGate(), [q[1], q[2]], []), - # (U1Gate(-pi / 4), [q[2]], []), # inverse T gate - # (U2Gate(0, pi), [q[2]], []), # H gate - # ] - # self.definition = definition + def _define(self): + """ + gate rccx a,b,c + { u2(0,pi) c; + u1(pi/4) c; + cx b, c; + u1(-pi/4) c; + cx a, c; + u1(pi/4) c; + cx b, c; + u1(-pi/4) c; + u2(0,pi) c; + } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + q = QuantumRegister(3, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U2Gate(0, pi), [q[2]], []), # H gate + (U1Gate(pi / 4), [q[2]], []), # T gate + (CXGate(), [q[1], q[2]], []), + (U1Gate(-pi / 4), [q[2]], []), # inverse T gate + (CXGate(), [q[0], q[2]], []), + (U1Gate(pi / 4), [q[2]], []), + (CXGate(), [q[1], q[2]], []), + (U1Gate(-pi / 4), [q[2]], []), # inverse T gate + (U2Gate(0, pi), [q[2]], []), # H gate + ] + qc.data = rules + self.definition = qc def to_matrix(self): """Return a numpy.array for the simplified CCX gate.""" @@ -490,10 +499,11 @@ def _define(self): h d; cu1(-pi/4) c,d; h d; } """ + # pylint: disable=cyclic-import from qiskit import QuantumCircuit from .u1 import CU1Gate q = QuantumRegister(4, name='q') - definition = [ + rules = [ (HGate(), [q[3]], []), (CU1Gate(-self._angle), [q[0], q[3]], []), (HGate(), [q[3]], []), @@ -523,7 +533,7 @@ def _define(self): (HGate(), [q[3]], []) ] qc = QuantumCircuit(q) - qc.data = definition + qc.data = rules self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): @@ -585,52 +595,55 @@ def __init__(self, label=None): """Create a new RC3X gate.""" super().__init__('rcccx', 4, [], label=label) - # def _define(self): - # """ - # gate rc3x a,b,c,d - # { u2(0,pi) d; - # u1(pi/4) d; - # cx c,d; - # u1(-pi/4) d; - # u2(0,pi) d; - # cx a,d; - # u1(pi/4) d; - # cx b,d; - # u1(-pi/4) d; - # cx a,d; - # u1(pi/4) d; - # cx b,d; - # u1(-pi/4) d; - # u2(0,pi) d; - # u1(pi/4) d; - # cx c,d; - # u1(-pi/4) d; - # u2(0,pi) d; - # } - # """ - # q = QuantumRegister(4, 'q') - - # definition = [ - # (U2Gate(0, pi), [q[3]], []), # H gate - # (U1Gate(pi / 4), [q[3]], []), # T gate - # (CXGate(), [q[2], q[3]], []), - # (U1Gate(-pi / 4), [q[3]], []), # inverse T gate - # (U2Gate(0, pi), [q[3]], []), - # (CXGate(), [q[0], q[3]], []), - # (U1Gate(pi / 4), [q[3]], []), - # (CXGate(), [q[1], q[3]], []), - # (U1Gate(-pi / 4), [q[3]], []), - # (CXGate(), [q[0], q[3]], []), - # (U1Gate(pi / 4), [q[3]], []), - # (CXGate(), [q[1], q[3]], []), - # (U1Gate(-pi / 4), [q[3]], []), - # (U2Gate(0, pi), [q[3]], []), - # (U1Gate(pi / 4), [q[3]], []), - # (CXGate(), [q[2], q[3]], []), - # (U1Gate(-pi / 4), [q[3]], []), - # (U2Gate(0, pi), [q[3]], []), - # ] - # self.definition = definition + def _define(self): + """ + gate rc3x a,b,c,d + { u2(0,pi) d; + u1(pi/4) d; + cx c,d; + u1(-pi/4) d; + u2(0,pi) d; + cx a,d; + u1(pi/4) d; + cx b,d; + u1(-pi/4) d; + cx a,d; + u1(pi/4) d; + cx b,d; + u1(-pi/4) d; + u2(0,pi) d; + u1(pi/4) d; + cx c,d; + u1(-pi/4) d; + u2(0,pi) d; + } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + q = QuantumRegister(4, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U2Gate(0, pi), [q[3]], []), # H gate + (U1Gate(pi / 4), [q[3]], []), # T gate + (CXGate(), [q[2], q[3]], []), + (U1Gate(-pi / 4), [q[3]], []), # inverse T gate + (U2Gate(0, pi), [q[3]], []), + (CXGate(), [q[0], q[3]], []), + (U1Gate(pi / 4), [q[3]], []), + (CXGate(), [q[1], q[3]], []), + (U1Gate(-pi / 4), [q[3]], []), + (CXGate(), [q[0], q[3]], []), + (U1Gate(pi / 4), [q[3]], []), + (CXGate(), [q[1], q[3]], []), + (U1Gate(-pi / 4), [q[3]], []), + (U2Gate(0, pi), [q[3]], []), + (U1Gate(pi / 4), [q[3]], []), + (CXGate(), [q[2], q[3]], []), + (U1Gate(-pi / 4), [q[3]], []), + (U2Gate(0, pi), [q[3]], []), + ] + qc.data = rules + self.definition = qc def to_matrix(self): """Return a numpy.array for the RC3X gate.""" @@ -694,10 +707,12 @@ def _define(self): c3sqrtx a,b,c,e; } """ + # pylint: disable=cyclic-import from qiskit import QuantumCircuit from .u1 import CU1Gate q = QuantumRegister(5, name='q') - definition = [ + qc = QuantumCircuit(q, name=self.name) + rules = [ (HGate(), [q[4]], []), (CU1Gate(-numpy.pi / 2), [q[3], q[4]], []), (HGate(), [q[4]], []), @@ -708,8 +723,7 @@ def _define(self): (C3XGate(), [q[0], q[1], q[2], q[3]], []), (C3XGate(numpy.pi / 8), [q[0], q[1], q[2], q[4]], []), ] - qc = QuantumCircuit(q) - qc.data = definition + qc.data = rules self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): @@ -785,6 +799,7 @@ def get_num_ancilla_qubits(num_ctrl_qubits, mode='noancilla'): def _define(self): """The standard definition used the Gray code implementation.""" + # pylint: disable=cyclic-import from qiskit import QuantumCircuit q = QuantumRegister(self.num_qubits, name='q') qc = QuantumCircuit(q) @@ -828,6 +843,7 @@ def __init__(self, num_ctrl_qubits, label=None, ctrl_state=None): def _define(self): """Define the MCX gate using the Gray code.""" + # pylint: disable=cyclic-import from qiskit import QuantumCircuit from .u1 import MCU1Gate q = QuantumRegister(self.num_qubits, name='q') @@ -856,12 +872,12 @@ def get_num_ancilla_qubits(num_ctrl_qubits, mode='recursion'): def _define(self): """Define the MCX gate using recursion.""" + # pylint: disable=cyclic-import from qiskit import QuantumCircuit - #import ipdb;ipdb.set_trace() q = QuantumRegister(self.num_qubits, name='q') qc = QuantumCircuit(q, name=self.name) if self.num_qubits == 4: - qc.append(C3XGate(), qargs=q[:]) + qc.append(C3XGate(), qargs=q[:]) self.definition = qc elif self.num_qubits == 5: qc.append(C4XGate(), qargs=q[:]) @@ -916,7 +932,8 @@ def get_num_ancilla_qubits(num_ctrl_qubits, mode='v-chain'): def _define(self): """Define the MCX gate using a V-chain of CX gates.""" - from qiskit import QuantumCircuit + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit q = QuantumRegister(self.num_qubits, name='q') qc = QuantumCircuit(q, name=self.name) q_controls = q[:self.num_ctrl_qubits] diff --git a/qiskit/circuit/library/standard_gates/y.py b/qiskit/circuit/library/standard_gates/y.py index d66263687e35..51bf88ccf22d 100644 --- a/qiskit/circuit/library/standard_gates/y.py +++ b/qiskit/circuit/library/standard_gates/y.py @@ -16,6 +16,7 @@ import numpy from qiskit.qasm import pi +# pylint: disable=cyclic-import from qiskit.circuit.controlledgate import ControlledGate from qiskit.circuit.gate import Gate from qiskit.circuit.quantumregister import QuantumRegister @@ -68,16 +69,17 @@ def __init__(self, label=None): """Create new Y gate.""" super().__init__('y', 1, [], label=label) - # def _define(self): - # from .u3 import U3Gate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (U3Gate(pi, pi / 2, pi / 2), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u3 import U3Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U3Gate(pi, pi / 2, pi / 2), [q[0]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-Y gate. @@ -187,22 +189,23 @@ def __init__(self, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = YGate() - # def _define(self): - # """ - # gate cy a,b { sdg b; cx a,b; s b; } - # """ - # from .s import SGate, SdgGate - # from .x import CXGate - # definition = [] - # q = QuantumRegister(2, 'q') - # rule = [ - # (SdgGate(), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (SGate(), [q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate cy a,b { sdg b; cx a,b; s b; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .s import SGate, SdgGate + from .x import CXGate + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (SdgGate(), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (SGate(), [q[1]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverted CY gate (itself).""" diff --git a/qiskit/circuit/library/standard_gates/z.py b/qiskit/circuit/library/standard_gates/z.py index 820d0e38ff33..1723b6eff74e 100644 --- a/qiskit/circuit/library/standard_gates/z.py +++ b/qiskit/circuit/library/standard_gates/z.py @@ -68,16 +68,17 @@ def __init__(self, label=None): """Create new Z gate.""" super().__init__('z', 1, [], label=label) - # def _define(self): - # from .u1 import U1Gate - # definition = [] - # q = QuantumRegister(1, 'q') - # rule = [ - # (U1Gate(pi), [q[0]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .u1 import U1Gate + q = QuantumRegister(1, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (U1Gate(pi), [q[0]], []) + ] + qc.data = rules + self.definition = qc def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return a (mutli-)controlled-Z gate. @@ -155,22 +156,23 @@ def __init__(self, label=None, ctrl_state=None): ctrl_state=ctrl_state) self.base_gate = ZGate() - # def _define(self): - # """ - # gate cz a,b { h b; cx a,b; h b; } - # """ - # from .h import HGate - # from .x import CXGate - # definition = [] - # q = QuantumRegister(2, 'q') - # rule = [ - # (HGate(), [q[1]], []), - # (CXGate(), [q[0], q[1]], []), - # (HGate(), [q[1]], []) - # ] - # for inst in rule: - # definition.append(inst) - # self.definition = definition + def _define(self): + """ + gate cz a,b { h b; cx a,b; h b; } + """ + # pylint: disable=cyclic-import + from qiskit import QuantumCircuit + from .h import HGate + from .x import CXGate + q = QuantumRegister(2, 'q') + qc = QuantumCircuit(q, name=self.name) + rules = [ + (HGate(), [q[1]], []), + (CXGate(), [q[0], q[1]], []), + (HGate(), [q[1]], []) + ] + qc.data = rules + self.definition = qc def inverse(self): """Return inverted CZ gate (itself).""" diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index 391a8172f083..6b417641387b 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -769,7 +769,6 @@ def _check_cargs(self, cargs): if not all(isinstance(i, Clbit) for i in cargs): raise CircuitError("carg is not a Clbit") if not all(self.has_register(i.register) for i in cargs): - #import ipdb;ipdb.set_trace() raise CircuitError("register not in this circuit") def to_instruction(self, parameter_map=None): diff --git a/qiskit/converters/circuit_to_dag.py b/qiskit/converters/circuit_to_dag.py index a5a7931bd508..eaac9e13e96b 100644 --- a/qiskit/converters/circuit_to_dag.py +++ b/qiskit/converters/circuit_to_dag.py @@ -53,9 +53,6 @@ def circuit_to_dag(circuit): dagcircuit.add_creg(register) for instruction, qargs, cargs in circuit.data: - # print(instruction.name, qargs, cargs) - # if instruction.name == 'h': - # import ipdb;ipdb.set_trace() dagcircuit.apply_operation_back(instruction.copy(), qargs, cargs, instruction.condition) return dagcircuit diff --git a/qiskit/converters/circuit_to_instruction.py b/qiskit/converters/circuit_to_instruction.py index 69b48e8f21c8..545490982265 100644 --- a/qiskit/converters/circuit_to_instruction.py +++ b/qiskit/converters/circuit_to_instruction.py @@ -78,7 +78,7 @@ def circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None params=sorted(parameter_dict.values(), key=lambda p: p.name)) instruction.condition = None - def find_bit_position(bit): # + def find_bit_position(bit): """find the index of a given bit (Register, int) within a flat ordered list of bits of the circuit """ @@ -104,7 +104,7 @@ def find_bit_position(bit): # if instruction.num_clbits > 0: c = ClassicalRegister(instruction.num_clbits, 'c') regs.append(c) - + definition = list(map(lambda x: (x[0], list(map(lambda y: q[find_bit_position(y)], x[1])), @@ -118,7 +118,8 @@ def find_bit_position(bit): # if reg.size == c.size: rule[0].condition = (c, val) else: - raise CircuitError('Cannot convert condition in circuit with multiple classical registers to instruction') + raise QiskitError('Cannot convert condition in circuit with ' + 'multiple classical registers to instruction') qc = QuantumCircuit(*regs, name=instruction.name) qc.data = definition diff --git a/qiskit/dagcircuit/dagcircuit.py b/qiskit/dagcircuit/dagcircuit.py index 75cc5e8b25ca..d0efbd18911b 100644 --- a/qiskit/dagcircuit/dagcircuit.py +++ b/qiskit/dagcircuit/dagcircuit.py @@ -283,7 +283,6 @@ def _check_condition(self, name, condition): """ # Verify creg exists if condition is not None and condition[0].name not in self.cregs: - #import ipdb;ipdb.set_trace() raise DAGCircuitError("invalid creg in condition for %s" % name) def _check_bits(self, args, amap): diff --git a/qiskit/extensions/quantum_initializer/squ.py b/qiskit/extensions/quantum_initializer/squ.py index 817224ca5216..8f77d1de816a 100644 --- a/qiskit/extensions/quantum_initializer/squ.py +++ b/qiskit/extensions/quantum_initializer/squ.py @@ -27,9 +27,6 @@ from qiskit.circuit.gate import Gate from qiskit.quantum_info.operators.predicates import is_unitary_matrix from qiskit.exceptions import QiskitError -from qiskit.circuit.library.standard_gates.ry import RYGate -from qiskit.circuit.library.standard_gates.rz import RZGate - from qiskit.util import deprecate_arguments _EPS = 1e-10 # global variable used to chop very small numbers to zero @@ -84,14 +81,13 @@ def _define(self): raise QiskitError('The decomposition mode is not known.') self._diag = diag - + self.definition = circuit def _zyz_circuit(self): """Get the circuit for the ZYZ decomposition.""" q = QuantumRegister(self.num_qubits) qc = QuantumCircuit(q, name=self.name) - rule = [] diag = [1., 1.] alpha, beta, gamma, _ = self._zyz_dec() diff --git a/qiskit/extensions/unitary.py b/qiskit/extensions/unitary.py index 271080106a97..35297d5f37e1 100644 --- a/qiskit/extensions/unitary.py +++ b/qiskit/extensions/unitary.py @@ -23,7 +23,6 @@ from qiskit.circuit import QuantumCircuit from qiskit.circuit import QuantumRegister from qiskit.circuit._utils import _compute_control_matrix -from qiskit.circuit.library.standard_gates import U3Gate from qiskit.extensions.quantum_initializer import isometry from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info.operators.predicates import is_unitary_matrix diff --git a/qiskit/quantum_info/operators/channel/superop.py b/qiskit/quantum_info/operators/channel/superop.py index 5952cf653ae1..6012bfd2364f 100644 --- a/qiskit/quantum_info/operators/channel/superop.py +++ b/qiskit/quantum_info/operators/channel/superop.py @@ -392,8 +392,9 @@ def _append_instruction(self, obj, qargs=None): raise QiskitError('Cannot apply Instruction: {}'.format( obj.name)) if not isinstance(obj.definition, QuantumCircuit): - raise QiskitError('{0} instruction definition is {1}; expected QuantumCircuit'.format( - obj.name, type(obj.definition))) + raise QiskitError('{0} instruction definition is {1}; ' + 'expected QuantumCircuit'.format( + obj.name, type(obj.definition))) for instr, qregs, cregs in obj.definition.data: if cregs: raise QiskitError( diff --git a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py index 8e9bc90dc7a8..feeaef493480 100644 --- a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py +++ b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py @@ -69,7 +69,7 @@ def run(self, dag): rule = node.op.definition.data except TypeError as err: raise QiskitError('Error decomposing node {}: {}'.format(node.name, err)) - except AttributeError as aerr: + except AttributeError: # definition is None rule = None diff --git a/test/python/circuit/test_controlled_gate.py b/test/python/circuit/test_controlled_gate.py index 663f126835b4..c4a890dcc40c 100644 --- a/test/python/circuit/test_controlled_gate.py +++ b/test/python/circuit/test_controlled_gate.py @@ -146,10 +146,9 @@ def test_multi_controlled_composite_gate(self): target = QuantumRegister(num_target) qc = QuantumCircuit(control, target) qc.append(cont_gate, control[:] + target[:]) - simulator = BasicAer.get_backend('unitary_simulator') - op_mat = execute(cgate, simulator).result().get_unitary(0) + op_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) - ref_mat = execute(qc, simulator).result().get_unitary(0) + ref_mat = Operator(qc).data self.assertTrue(matrix_equal(cop_mat, ref_mat, ignore_phase=True)) def test_single_controlled_composite_gate(self): @@ -167,10 +166,9 @@ def test_single_controlled_composite_gate(self): target = QuantumRegister(num_target, 'target') qc = QuantumCircuit(control, target) qc.append(cont_gate, control[:] + target[:]) - simulator = BasicAer.get_backend('unitary_simulator') - op_mat = execute(cgate, simulator).result().get_unitary(0) + op_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) - ref_mat = execute(qc, simulator).result().get_unitary(0) + ref_mat = Operator(qc).data self.assertTrue(matrix_equal(cop_mat, ref_mat, ignore_phase=True)) def test_multi_control_u3(self): @@ -206,17 +204,11 @@ def test_multi_control_u3(self): c_cu3 = cu3gate.control(1) qc_cu3.append(c_cu3, qr, []) - job = execute([qcnu3, qu3, qcu3, qc_cu3], BasicAer.get_backend('unitary_simulator'), - basis_gates=['u1', 'u2', 'u3', 'id', 'cx']) - result = job.result() - # Circuit unitaries - #mat_cnu3 = result.get_unitary(0) # unitary_simulator is giving different output than Operator?? mat_cnu3 = Operator(qcnu3).data - - mat_u3 = result.get_unitary(1) - mat_cu3 = result.get_unitary(2) - mat_c_cu3 = result.get_unitary(3) + mat_u3 = Operator(qu3).data + mat_cu3 = Operator(qcu3).data + mat_c_cu3 = Operator(qc_cu3).data # Target Controlled-U3 unitary target_cnu3 = _compute_control_matrix(mat_u3, num_ctrl) @@ -232,10 +224,8 @@ def test_multi_control_u3(self): for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): - if info == 'check unitary of cnu3 against tensored unitary of u3': - np.set_printoptions(precision=2, linewidth=300, suppress=True) - import ipdb;ipdb.set_trace() - self.assertTrue(matrix_equal(target, decomp, ignore_phase=True, atol=1e-8, rtol=1e-5)) + self.assertTrue(matrix_equal(target, decomp, ignore_phase=True, + atol=1e-8, rtol=1e-5)) def test_multi_control_u1(self): """Test the matrix representation of the controlled and controlled-controlled U1 gate.""" @@ -577,9 +567,6 @@ def test_mcx_gates(self, num_ctrl_qubits): i = int(bin(i)[2:].zfill(circuit.num_qubits)[gate.num_ancilla_qubits:], 2) corrected[i] += statevector_amplitude statevector = corrected - np.set_printoptions(precision=3, linewidth=200, suppress=True) - # if isinstance(gate, MCXRecursive): - # import ipdb;ipdb.set_trace() np.testing.assert_array_almost_equal(statevector.real, reference) @data(1, 2, 3, 4) @@ -1015,12 +1002,10 @@ def test_controlled_standard_gates(self, num_ctrl_qubits, gate_class): for ctrl_state in {ctrl_state_ones, ctrl_state_zeros, ctrl_state_mixed}: with self.subTest(i='{0}, ctrl_state={1}'.format(gate_class.__name__, ctrl_state)): - np.set_printoptions(precision=3, linewidth=200, suppress=True) if hasattr(gate, 'num_ancilla_qubits') and gate.num_ancilla_qubits > 0: # skip matrices that include ancilla qubits continue try: - #import ipdb;ipdb.set_trace() cgate = gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) except (AttributeError, QiskitError): # 'object has no attribute "control"' @@ -1034,9 +1019,6 @@ def test_controlled_standard_gates(self, num_ctrl_qubits, gate_class): base_mat = Operator(gate).data target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) - - #import ipdb;ipdb.set_trace() - src_mat = Operator(cgate).data self.assertTrue(matrix_equal(Operator(cgate).data, target_mat, ignore_phase=True)) diff --git a/test/python/circuit/test_instructions.py b/test/python/circuit/test_instructions.py index 43b375415a50..fa25211b9b18 100644 --- a/test/python/circuit/test_instructions.py +++ b/test/python/circuit/test_instructions.py @@ -187,7 +187,7 @@ def test_reverse_instruction(self): circ.measure(q[0], c[0]) circ.rz(0.8, q[0]).c_if(c, 6) inst = circ.to_instruction() - + circ = QuantumCircuit(q, c, name='circ') circ.rz(0.8, q[0]).c_if(c, 6) circ.measure(q[0], c[0]) diff --git a/test/python/circuit/test_library.py b/test/python/circuit/test_library.py index e0a3d719f347..5f7b936f1e27 100644 --- a/test/python/circuit/test_library.py +++ b/test/python/circuit/test_library.py @@ -640,7 +640,6 @@ def pw_linear(x): pw_linear_rotations = PiecewiseLinearPauliRotations(num_state_qubits, breakpoints, [2 * slope for slope in slopes], [2 * offset for offset in offsets]) - self.assertFunctionIsCorrect(pw_linear_rotations, pw_linear) def test_piecewise_linear_rotations_mutability(self): From 87db6327c94a03f9fce31f0528b0bce7f30bd641 Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Tue, 30 Jun 2020 23:35:14 -0400 Subject: [PATCH 04/11] linting --- qiskit/circuit/controlledgate.py | 1 + qiskit/circuit/library/standard_gates/dcx.py | 3 ++- qiskit/circuit/library/standard_gates/h.py | 4 ++-- .../circuit/library/standard_gates/iswap.py | 2 +- qiskit/circuit/library/standard_gates/ms.py | 2 +- qiskit/circuit/library/standard_gates/r.py | 2 +- qiskit/circuit/library/standard_gates/rx.py | 6 ++++-- qiskit/circuit/library/standard_gates/rxx.py | 2 +- qiskit/circuit/library/standard_gates/ry.py | 6 ++++-- qiskit/circuit/library/standard_gates/ryy.py | 2 +- qiskit/circuit/library/standard_gates/rz.py | 4 ++-- qiskit/circuit/library/standard_gates/rzx.py | 2 +- qiskit/circuit/library/standard_gates/rzz.py | 2 +- qiskit/circuit/library/standard_gates/s.py | 4 ++-- qiskit/circuit/library/standard_gates/swap.py | 4 ++-- qiskit/circuit/library/standard_gates/t.py | 4 ++-- qiskit/circuit/library/standard_gates/u1.py | 6 +++--- qiskit/circuit/library/standard_gates/u2.py | 2 +- qiskit/circuit/library/standard_gates/u3.py | 2 +- qiskit/circuit/library/standard_gates/x.py | 20 +++++++++---------- qiskit/circuit/library/standard_gates/y.py | 4 ++-- qiskit/circuit/library/standard_gates/z.py | 4 ++-- qiskit/converters/circuit_to_gate.py | 3 ++- qiskit/converters/circuit_to_instruction.py | 3 ++- 24 files changed, 51 insertions(+), 43 deletions(-) diff --git a/qiskit/circuit/controlledgate.py b/qiskit/circuit/controlledgate.py index 4ae456aec9bc..e49062bfc92f 100644 --- a/qiskit/circuit/controlledgate.py +++ b/qiskit/circuit/controlledgate.py @@ -106,6 +106,7 @@ def definition(self) -> List: definition is conjugated with X without changing the internal `_definition`. """ + # pylint: disable=cyclic-import from qiskit import QuantumCircuit if self._open_ctrl: closed_gate = self.copy() diff --git a/qiskit/circuit/library/standard_gates/dcx.py b/qiskit/circuit/library/standard_gates/dcx.py index 1b681ae22268..7767fe38cfa4 100644 --- a/qiskit/circuit/library/standard_gates/dcx.py +++ b/qiskit/circuit/library/standard_gates/dcx.py @@ -54,7 +54,8 @@ def _define(self): """ gate dcx a, b { cx a, b; cx a, b; } """ - from qiskit import QuantumCircuit + # pylint: disable=cyclic-import + from qiskit.circuit.quantumcircuit import QuantumCircuit from .x import CXGate q = QuantumRegister(2, 'q') qc = QuantumCircuit(q, name=self.name) diff --git a/qiskit/circuit/library/standard_gates/h.py b/qiskit/circuit/library/standard_gates/h.py index 0249ce57a03a..20dab2abbd31 100644 --- a/qiskit/circuit/library/standard_gates/h.py +++ b/qiskit/circuit/library/standard_gates/h.py @@ -58,7 +58,7 @@ def _define(self): gate h a { u2(0,pi) a; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u2 import U2Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) @@ -183,7 +183,7 @@ def _define(self): } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .x import CXGate # pylint: disable=cyclic-import q = QuantumRegister(2, 'q') qc = QuantumCircuit(q, name=self.name) diff --git a/qiskit/circuit/library/standard_gates/iswap.py b/qiskit/circuit/library/standard_gates/iswap.py index cfaa76c0f34a..6df3dcd55ef9 100644 --- a/qiskit/circuit/library/standard_gates/iswap.py +++ b/qiskit/circuit/library/standard_gates/iswap.py @@ -93,7 +93,7 @@ def _define(self): } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .h import HGate from .s import SGate from .x import CXGate diff --git a/qiskit/circuit/library/standard_gates/ms.py b/qiskit/circuit/library/standard_gates/ms.py index e987cb232ff8..fae673c52c98 100644 --- a/qiskit/circuit/library/standard_gates/ms.py +++ b/qiskit/circuit/library/standard_gates/ms.py @@ -37,7 +37,7 @@ def __init__(self, num_qubits, theta, *, n_qubits=None, # pylint:disable=unused def _define(self): # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .rxx import RXXGate q = QuantumRegister(self.num_qubits, 'q') qc = QuantumCircuit(q, name=self.name) diff --git a/qiskit/circuit/library/standard_gates/r.py b/qiskit/circuit/library/standard_gates/r.py index 76c16e4cdce2..bcac9b868eb6 100644 --- a/qiskit/circuit/library/standard_gates/r.py +++ b/qiskit/circuit/library/standard_gates/r.py @@ -53,7 +53,7 @@ def _define(self): gate r(θ, φ) a {u3(θ, φ - π/2, -φ + π/2) a;} """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u3 import U3Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) diff --git a/qiskit/circuit/library/standard_gates/rx.py b/qiskit/circuit/library/standard_gates/rx.py index d006aeed8048..5f3011288ec8 100644 --- a/qiskit/circuit/library/standard_gates/rx.py +++ b/qiskit/circuit/library/standard_gates/rx.py @@ -54,7 +54,8 @@ def _define(self): """ gate rx(theta) a {r(theta, 0) a;} """ - from qiskit import QuantumCircuit + # pylint: disable=cyclic-import + from qiskit.circuit.quantumcircuit import QuantumCircuit from .r import RGate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) @@ -178,7 +179,8 @@ def _define(self): u3(theta/2,-pi/2,0) t; } """ - from qiskit import QuantumCircuit + # pylint: disable=cyclic-import + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import U1Gate from .u3 import U3Gate from .x import CXGate diff --git a/qiskit/circuit/library/standard_gates/rxx.py b/qiskit/circuit/library/standard_gates/rxx.py index 942c38e7d850..352692523ad0 100644 --- a/qiskit/circuit/library/standard_gates/rxx.py +++ b/qiskit/circuit/library/standard_gates/rxx.py @@ -75,7 +75,7 @@ def __init__(self, theta): def _define(self): """Calculate a subcircuit that implements this unitary.""" # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .x import CXGate from .u1 import U1Gate from .h import HGate diff --git a/qiskit/circuit/library/standard_gates/ry.py b/qiskit/circuit/library/standard_gates/ry.py index 4088b2956006..76889b77db87 100644 --- a/qiskit/circuit/library/standard_gates/ry.py +++ b/qiskit/circuit/library/standard_gates/ry.py @@ -54,7 +54,8 @@ def _define(self): """ gate ry(theta) a { r(theta, pi/2) a; } """ - from qiskit import QuantumCircuit + # pylint: disable=cyclic-import + from qiskit.circuit.quantumcircuit import QuantumCircuit from .r import RGate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) @@ -175,7 +176,8 @@ def _define(self): u3(-lambda/2,0,0) b; cx a,b; } """ - from qiskit import QuantumCircuit + # pylint: disable=cyclic-import + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u3 import U3Gate from .x import CXGate q = QuantumRegister(2, 'q') diff --git a/qiskit/circuit/library/standard_gates/ryy.py b/qiskit/circuit/library/standard_gates/ryy.py index 09c45a6352e7..4c50bc8ef7d6 100644 --- a/qiskit/circuit/library/standard_gates/ryy.py +++ b/qiskit/circuit/library/standard_gates/ryy.py @@ -76,7 +76,7 @@ def __init__(self, theta): def _define(self): """Calculate a subcircuit that implements this unitary.""" # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .x import CXGate from .rx import RXGate from .rz import RZGate diff --git a/qiskit/circuit/library/standard_gates/rz.py b/qiskit/circuit/library/standard_gates/rz.py index 5a506ef52627..1da5bd692164 100644 --- a/qiskit/circuit/library/standard_gates/rz.py +++ b/qiskit/circuit/library/standard_gates/rz.py @@ -65,7 +65,7 @@ def _define(self): gate rz(phi) a { u1(phi) a; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import U1Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) @@ -195,7 +195,7 @@ def _define(self): } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import U1Gate from .x import CXGate q = QuantumRegister(2, 'q') diff --git a/qiskit/circuit/library/standard_gates/rzx.py b/qiskit/circuit/library/standard_gates/rzx.py index 4f4236e4c8c8..aa69d0b27d70 100644 --- a/qiskit/circuit/library/standard_gates/rzx.py +++ b/qiskit/circuit/library/standard_gates/rzx.py @@ -126,7 +126,7 @@ def _define(self): gate rzx(theta) a, b { h b; cx a, b; u1(theta) b; cx a, b; h b;} """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit q = QuantumRegister(2, 'q') qc = QuantumCircuit(q, name=self.name) rules = [ diff --git a/qiskit/circuit/library/standard_gates/rzz.py b/qiskit/circuit/library/standard_gates/rzz.py index 1acf95b9a897..8a78ad47c323 100644 --- a/qiskit/circuit/library/standard_gates/rzz.py +++ b/qiskit/circuit/library/standard_gates/rzz.py @@ -90,7 +90,7 @@ def _define(self): gate rzz(theta) a, b { cx a, b; u1(theta) b; cx a, b; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import U1Gate from .x import CXGate q = QuantumRegister(2, 'q') diff --git a/qiskit/circuit/library/standard_gates/s.py b/qiskit/circuit/library/standard_gates/s.py index 16b8239caadc..ce94e06de0fe 100644 --- a/qiskit/circuit/library/standard_gates/s.py +++ b/qiskit/circuit/library/standard_gates/s.py @@ -56,7 +56,7 @@ def _define(self): gate s a { u1(pi/2) a; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import U1Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) @@ -112,7 +112,7 @@ def _define(self): gate sdg a { u1(-pi/2) a; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import U1Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) diff --git a/qiskit/circuit/library/standard_gates/swap.py b/qiskit/circuit/library/standard_gates/swap.py index 4b2f9e95c952..1c0c94d7d3cb 100644 --- a/qiskit/circuit/library/standard_gates/swap.py +++ b/qiskit/circuit/library/standard_gates/swap.py @@ -61,7 +61,7 @@ def _define(self): gate swap a,b { cx a,b; cx b,a; cx a,b; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .x import CXGate q = QuantumRegister(2, 'q') qc = QuantumCircuit(q, name=self.name) @@ -220,7 +220,7 @@ def _define(self): } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .x import CXGate, CCXGate q = QuantumRegister(3, 'q') qc = QuantumCircuit(q, name=self.name) diff --git a/qiskit/circuit/library/standard_gates/t.py b/qiskit/circuit/library/standard_gates/t.py index 9d6b4aa71213..8a6f683c0268 100644 --- a/qiskit/circuit/library/standard_gates/t.py +++ b/qiskit/circuit/library/standard_gates/t.py @@ -57,7 +57,7 @@ def _define(self): gate t a { u1(pi/4) a; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import U1Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) @@ -113,7 +113,7 @@ def _define(self): gate tdg a { u1(pi/4) a; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import U1Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) diff --git a/qiskit/circuit/library/standard_gates/u1.py b/qiskit/circuit/library/standard_gates/u1.py index 74f72a08c9a6..7a7f47446922 100644 --- a/qiskit/circuit/library/standard_gates/u1.py +++ b/qiskit/circuit/library/standard_gates/u1.py @@ -81,7 +81,7 @@ def __init__(self, theta, label=None): def _define(self): # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u3 import U3Gate # pylint: disable=cyclic-import q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) @@ -185,7 +185,7 @@ def _define(self): } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .x import CXGate # pylint: disable=cyclic-import q = QuantumRegister(2, 'q') qc = QuantumCircuit(q, name=self.name) @@ -278,7 +278,7 @@ def __init__(self, lam, num_ctrl_qubits, label=None): def _define(self): # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit q = QuantumRegister(self.num_qubits, 'q') qc = QuantumCircuit(q, name=self.name) diff --git a/qiskit/circuit/library/standard_gates/u2.py b/qiskit/circuit/library/standard_gates/u2.py index c6ee740becf5..427c9a4dcad8 100644 --- a/qiskit/circuit/library/standard_gates/u2.py +++ b/qiskit/circuit/library/standard_gates/u2.py @@ -65,7 +65,7 @@ def __init__(self, phi, lam, label=None): def _define(self): # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u3 import U3Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) diff --git a/qiskit/circuit/library/standard_gates/u3.py b/qiskit/circuit/library/standard_gates/u3.py index ae58f0738b42..21e4b25a3ed9 100644 --- a/qiskit/circuit/library/standard_gates/u3.py +++ b/qiskit/circuit/library/standard_gates/u3.py @@ -192,7 +192,7 @@ def _define(self): } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import U1Gate from .x import CXGate # pylint: disable=cyclic-import q = QuantumRegister(2, 'q') diff --git a/qiskit/circuit/library/standard_gates/x.py b/qiskit/circuit/library/standard_gates/x.py index 1afef22c3e92..719e3b64982e 100644 --- a/qiskit/circuit/library/standard_gates/x.py +++ b/qiskit/circuit/library/standard_gates/x.py @@ -79,7 +79,7 @@ def _define(self): gate x a { u3(pi,0,pi) a; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u3 import U3Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) @@ -331,7 +331,7 @@ def _define(self): t a; tdg b; cx a,b;} """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit q = QuantumRegister(3, 'q') qc = QuantumCircuit(q, name=self.name) rules = [ @@ -428,7 +428,7 @@ def _define(self): } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit q = QuantumRegister(3, 'q') qc = QuantumCircuit(q, name=self.name) rules = [ @@ -500,7 +500,7 @@ def _define(self): } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import CU1Gate q = QuantumRegister(4, name='q') rules = [ @@ -619,7 +619,7 @@ def _define(self): } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit q = QuantumRegister(4, 'q') qc = QuantumCircuit(q, name=self.name) rules = [ @@ -708,7 +708,7 @@ def _define(self): } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import CU1Gate q = QuantumRegister(5, name='q') qc = QuantumCircuit(q, name=self.name) @@ -800,7 +800,7 @@ def get_num_ancilla_qubits(num_ctrl_qubits, mode='noancilla'): def _define(self): """The standard definition used the Gray code implementation.""" # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit q = QuantumRegister(self.num_qubits, name='q') qc = QuantumCircuit(q) qc.append(MCXGrayCode(self.num_ctrl_qubits), qargs=q[:]) @@ -844,7 +844,7 @@ def __init__(self, num_ctrl_qubits, label=None, ctrl_state=None): def _define(self): """Define the MCX gate using the Gray code.""" # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import MCU1Gate q = QuantumRegister(self.num_qubits, name='q') qc = QuantumCircuit(q, name=self.name) @@ -873,7 +873,7 @@ def get_num_ancilla_qubits(num_ctrl_qubits, mode='recursion'): def _define(self): """Define the MCX gate using recursion.""" # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit q = QuantumRegister(self.num_qubits, name='q') qc = QuantumCircuit(q, name=self.name) if self.num_qubits == 4: @@ -933,7 +933,7 @@ def get_num_ancilla_qubits(num_ctrl_qubits, mode='v-chain'): def _define(self): """Define the MCX gate using a V-chain of CX gates.""" # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit q = QuantumRegister(self.num_qubits, name='q') qc = QuantumCircuit(q, name=self.name) q_controls = q[:self.num_ctrl_qubits] diff --git a/qiskit/circuit/library/standard_gates/y.py b/qiskit/circuit/library/standard_gates/y.py index 51bf88ccf22d..5c19c366ad3f 100644 --- a/qiskit/circuit/library/standard_gates/y.py +++ b/qiskit/circuit/library/standard_gates/y.py @@ -71,7 +71,7 @@ def __init__(self, label=None): def _define(self): # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u3 import U3Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) @@ -194,7 +194,7 @@ def _define(self): gate cy a,b { sdg b; cx a,b; s b; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .s import SGate, SdgGate from .x import CXGate q = QuantumRegister(2, 'q') diff --git a/qiskit/circuit/library/standard_gates/z.py b/qiskit/circuit/library/standard_gates/z.py index 1723b6eff74e..b649d65d9617 100644 --- a/qiskit/circuit/library/standard_gates/z.py +++ b/qiskit/circuit/library/standard_gates/z.py @@ -70,7 +70,7 @@ def __init__(self, label=None): def _define(self): # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .u1 import U1Gate q = QuantumRegister(1, 'q') qc = QuantumCircuit(q, name=self.name) @@ -161,7 +161,7 @@ def _define(self): gate cz a,b { h b; cx a,b; h b; } """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + from qiskit.circuit.quantumcircuit import QuantumCircuit from .h import HGate from .x import CXGate q = QuantumRegister(2, 'q') diff --git a/qiskit/converters/circuit_to_gate.py b/qiskit/converters/circuit_to_gate.py index d9234e83556c..ab90dab97729 100644 --- a/qiskit/converters/circuit_to_gate.py +++ b/qiskit/converters/circuit_to_gate.py @@ -15,7 +15,6 @@ """Helper function for converting a circuit to a gate""" -from qiskit.circuit import QuantumCircuit from qiskit.circuit.gate import Gate from qiskit.circuit.quantumregister import QuantumRegister, Qubit from qiskit.exceptions import QiskitError @@ -46,6 +45,8 @@ def circuit_to_gate(circuit, parameter_map=None, equivalence_library=None): input circuit. Upon decomposition, this gate will yield the components comprising the original circuit. """ + # pylint: disable=cyclic-import + from qiskit.circuit.quantumcircuit import QuantumCircuit if circuit.clbits: raise QiskitError('Circuit with classical bits cannot be converted ' 'to gate.') diff --git a/qiskit/converters/circuit_to_instruction.py b/qiskit/converters/circuit_to_instruction.py index 545490982265..9d7f4d521875 100644 --- a/qiskit/converters/circuit_to_instruction.py +++ b/qiskit/converters/circuit_to_instruction.py @@ -15,7 +15,6 @@ """Helper function for converting a circuit to an instruction.""" from qiskit.exceptions import QiskitError -from qiskit.circuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumregister import QuantumRegister, Qubit from qiskit.circuit.classicalregister import ClassicalRegister @@ -61,6 +60,8 @@ def circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None circ.rz(0.5, q[1]).c_if(c, 2) circuit_to_instruction(circ) """ + # pylint: disable=cyclic-import + from qiskit.circuit.quantumcircuit import QuantumCircuit if parameter_map is None: parameter_dict = {p: p for p in circuit.parameters} From c3b377617fafb136f0275ade8e8e1411886fa98c Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Fri, 3 Jul 2020 00:08:15 -0400 Subject: [PATCH 05/11] resolve qreg bug in transpiler --- qiskit/circuit/add_control.py | 14 ++++- qiskit/transpiler/passes/basis/decompose.py | 9 +-- .../passes/basis/unroll_3q_or_more.py | 9 +-- .../passes/basis/unroll_custom_definitions.py | 9 +-- qiskit/transpiler/passes/basis/unroller.py | 13 +--- test/python/circuit/test_controlled_gate.py | 60 +++++++++++++++++++ test/python/circuit/test_library.py | 1 + 7 files changed, 81 insertions(+), 34 deletions(-) diff --git a/qiskit/circuit/add_control.py b/qiskit/circuit/add_control.py index b70816b4a77c..ecdceca40089 100644 --- a/qiskit/circuit/add_control.py +++ b/qiskit/circuit/add_control.py @@ -184,7 +184,7 @@ def _gate_to_circuit(operation): qr = QuantumRegister(operation.num_qubits) qc = QuantumCircuit(qr, name=operation.name) if hasattr(operation, 'definition') and operation.definition: - for rule in operation.definition: + for rule in operation.definition.data: if rule[0].name in {'id', 'barrier', 'measure', 'snapshot'}: raise CircuitError('Cannot make controlled gate with {} instruction'.format( rule[0].name)) @@ -193,12 +193,20 @@ def _gate_to_circuit(operation): qc.append(operation, qargs=qr, cargs=[]) return qc +def _gate_to_dag(operation): + from qiskit.converters.circuit_to_dag import circuit_to_dag + if hasattr(operation, 'definition') and operation.definition: + return circuit_to_dag(operation.definition) + else: + qr = QuantumRegister(operation.num_qubits) + qc = QuantumCircuit(qr, name=operation.name) + qc.append(operation, qr) + return circuit_to_dag(qc) def _unroll_gate(operation, basis_gates): - from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit from qiskit.transpiler.passes import Unroller unroller = Unroller(basis_gates) - dag = circuit_to_dag(_gate_to_circuit(operation)) + dag = _gate_to_dag(operation) qc = dag_to_circuit(unroller.run(dag)) return qc.to_gate() diff --git a/qiskit/transpiler/passes/basis/decompose.py b/qiskit/transpiler/passes/basis/decompose.py index 3517b6f0c40d..0e60ba980999 100644 --- a/qiskit/transpiler/passes/basis/decompose.py +++ b/qiskit/transpiler/passes/basis/decompose.py @@ -19,6 +19,7 @@ from qiskit.circuit.gate import Gate from qiskit.transpiler.basepasses import TransformationPass from qiskit.dagcircuit.dagcircuit import DAGCircuit +from qiskit.transpiler.passes.utils.ordered_regs import _make_ordered_regs class Decompose(TransformationPass): @@ -53,14 +54,10 @@ def run(self, dag: DAGCircuit) -> DAGCircuit: if len(rule) == 1 and len(node.qargs) == len(rule[0][1]): dag.substitute_node(node, rule[0][0], inplace=True) else: - # hacky way to build a dag on the same register as the rule is defined - # TODO: need anonymous rules to address wires by index decomposition = DAGCircuit() - qregs = {qb.register for inst in rule for qb in inst[1]} - cregs = {cb.register for inst in rule for cb in inst[2]} - for qreg in qregs: + for qreg in node.op.definition.qregs: decomposition.add_qreg(qreg) - for creg in cregs: + for creg in node.op.definition.cregs: decomposition.add_creg(creg) for inst in rule: decomposition.apply_operation_back(*inst) diff --git a/qiskit/transpiler/passes/basis/unroll_3q_or_more.py b/qiskit/transpiler/passes/basis/unroll_3q_or_more.py index b95e01998702..8f7eb52da64c 100644 --- a/qiskit/transpiler/passes/basis/unroll_3q_or_more.py +++ b/qiskit/transpiler/passes/basis/unroll_3q_or_more.py @@ -42,15 +42,10 @@ def run(self, dag): raise QiskitError("Cannot unroll all 3q or more gates. " "No rule to expand instruction %s." % node.op.name) - - # hacky way to build a dag on the same register as the rule is defined - # TODO: need anonymous rules to address wires by index decomposition = DAGCircuit() - qregs = {qb.register for inst in rule for qb in inst[1]} - cregs = {cb.register for inst in rule for cb in inst[2]} - for qreg in qregs: + for qreg in node.op.definition.qregs: decomposition.add_qreg(qreg) - for creg in cregs: + for creg in node.op.definition.cregs: decomposition.add_creg(creg) for inst in rule: decomposition.apply_operation_back(*inst) diff --git a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py index feeaef493480..0b9780218145 100644 --- a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py +++ b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py @@ -83,15 +83,10 @@ def run(self, dag): "Instruction %s not found in equivalence library " "and no rule found to expand." % (str(self._basis_gates), node.op.name)) - - # hacky way to build a dag on the same register as the rule is defined - # TODO: need anonymous rules to address wires by index decomposition = DAGCircuit() - qregs = {qb.register for inst in rule for qb in inst[1]} - cregs = {cb.register for inst in rule for cb in inst[2]} - for qreg in qregs: + for qreg in node.op.definition.qregs: decomposition.add_qreg(qreg) - for creg in cregs: + for creg in node.op.definition.cregs: decomposition.add_creg(creg) for inst in rule: decomposition.apply_operation_back(*inst) diff --git a/qiskit/transpiler/passes/basis/unroller.py b/qiskit/transpiler/passes/basis/unroller.py index 2ca85e6df77c..b635a9539b83 100644 --- a/qiskit/transpiler/passes/basis/unroller.py +++ b/qiskit/transpiler/passes/basis/unroller.py @@ -52,7 +52,6 @@ def run(self, dag): """ if self.basis is None: return dag - # Walk through the DAG and expand each non-basis node for node in dag.op_nodes(): basic_insts = ['measure', 'reset', 'barrier', 'snapshot'] @@ -66,7 +65,6 @@ def run(self, dag): pass else: continue - # TODO: allow choosing other possible decompositions try: rule = node.op.definition.data @@ -95,20 +93,13 @@ def run(self, dag): raise QiskitError("Cannot unroll the circuit to the given basis, %s. " "No rule to expand instruction %s." % (str(self.basis), node.op.name)) - - # hacky way to build a dag on the same register as the rule is defined - # TODO: need anonymous rules to address wires by index decomposition = DAGCircuit() - qregs = {qb.register for inst in rule for qb in inst[1]} - cregs = {cb.register for inst in rule for cb in inst[2]} - for qreg in qregs: + for qreg in node.op.definition.qregs: decomposition.add_qreg(qreg) - for creg in cregs: + for creg in node.op.definition.cregs: decomposition.add_creg(creg) for inst in rule: decomposition.apply_operation_back(*inst) - unrolled_dag = self.run(decomposition) # recursively unroll ops dag.substitute_node_with_dag(node, unrolled_dag) - return dag diff --git a/test/python/circuit/test_controlled_gate.py b/test/python/circuit/test_controlled_gate.py index aa88e8adbda1..b4bc8acf0418 100644 --- a/test/python/circuit/test_controlled_gate.py +++ b/test/python/circuit/test_controlled_gate.py @@ -226,6 +226,66 @@ def test_multi_control_u3(self): with self.subTest(i=info): self.assertTrue(matrix_equal(target, decomp, ignore_phase=True, atol=1e-8, rtol=1e-5)) + # def test_multi_control_u3_2(self): + # """Test the matrix representation of the controlled and controlled-controlled U3 gate.""" + # import qiskit.circuit.library.standard_gates.u3 as u3 + + # num_ctrl = 3 + # # U3 gate params + # alpha, beta, gamma = 0.2, 0.3, 0.4 + + # # cnu3 gate + # u3gate = u3.U3Gate(alpha, beta, gamma) + # cnu3 = u3gate.control(num_ctrl) + # width = cnu3.num_qubits + # qr = QuantumRegister(width) + # qcnu3 = QuantumCircuit(qr) + # qcnu3.append(cnu3, qr, []) + + # # U3 gate + # qu3 = QuantumCircuit(1) + # qu3.u3(alpha, beta, gamma, 0) + + # # CU3 gate + # qcu3 = QuantumCircuit(2) + # qcu3.cu3(alpha, beta, gamma, 0, 1) + + # # c-cu3 gate + # width = 3 + # qr = QuantumRegister(width) + # qc_cu3 = QuantumCircuit(qr) + # cu3gate = u3.CU3Gate(alpha, beta, gamma) + + # c_cu3 = cu3gate.control(1) + # qc_cu3.append(c_cu3, qr, []) + + # job = execute([qcnu3, qu3, qcu3, qc_cu3], BasicAer.get_backend('unitary_simulator'), + # basis_gates=['u1', 'u2', 'u3', 'id', 'cx']) + # result = job.result() + + # # Circuit unitaries + # mat_cnu3 = result.get_unitary(0) + + # mat_u3 = result.get_unitary(1) + # mat_cu3 = result.get_unitary(2) + # mat_c_cu3 = result.get_unitary(3) + + # # Target Controlled-U3 unitary + # target_cnu3 = _compute_control_matrix(mat_u3, num_ctrl) + # target_cu3 = np.kron(mat_u3, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) + # target_c_cu3 = np.kron(mat_cu3, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) + + # tests = [('check unitary of u3.control against tensored unitary of u3', + # target_cu3, mat_cu3), + # ('check unitary of cu3.control against tensored unitary of cu3', + # target_c_cu3, mat_c_cu3), + # ('check unitary of cnu3 against tensored unitary of u3', + # target_cnu3, mat_cnu3)] + # for itest in tests: + # info, target, decomp = itest[0], itest[1], itest[2] + # with self.subTest(i=info): + # self.log.info(info) + # self.assertTrue(matrix_equal(target, decomp, ignore_phase=True)) def test_multi_control_u1(self): """Test the matrix representation of the controlled and controlled-controlled U1 gate.""" diff --git a/test/python/circuit/test_library.py b/test/python/circuit/test_library.py index 5f7b936f1e27..e0a3d719f347 100644 --- a/test/python/circuit/test_library.py +++ b/test/python/circuit/test_library.py @@ -640,6 +640,7 @@ def pw_linear(x): pw_linear_rotations = PiecewiseLinearPauliRotations(num_state_qubits, breakpoints, [2 * slope for slope in slopes], [2 * offset for offset in offsets]) + self.assertFunctionIsCorrect(pw_linear_rotations, pw_linear) def test_piecewise_linear_rotations_mutability(self): From 2320aa592596ab2f50c7348fc8f720a7e5a123b8 Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Fri, 3 Jul 2020 10:31:04 -0400 Subject: [PATCH 06/11] simplify unroller passes a bit --- qiskit/circuit/instruction.py | 19 +++--- qiskit/transpiler/passes/basis/decompose.py | 10 +--- .../passes/basis/unroll_3q_or_more.py | 9 +-- .../passes/basis/unroll_custom_definitions.py | 10 +--- qiskit/transpiler/passes/basis/unroller.py | 9 +-- test/python/circuit/test_controlled_gate.py | 60 ------------------- 6 files changed, 20 insertions(+), 97 deletions(-) diff --git a/qiskit/circuit/instruction.py b/qiskit/circuit/instruction.py index ea7eb4807c06..66bf5576ddc6 100644 --- a/qiskit/circuit/instruction.py +++ b/qiskit/circuit/instruction.py @@ -177,14 +177,19 @@ def definition(self): return self._definition @definition.setter - def definition(self, definition): + def definition(self, array): """Set gate representation""" - # pylint: disable=cyclic-import - from qiskit import QuantumCircuit - if not isinstance(definition, QuantumCircuit) and definition is not None: - raise CircuitError('Instruction "{}" definition must be QuantumCircuit. Got {}'.format( - self.name, type(definition))) - self._definition = definition + self._definition = array + + # @definition.setter + # def definition(self, definition): + # """Set gate representation""" + # # pylint: disable=cyclic-import + # from qiskit import QuantumCircuit + # if not isinstance(definition, QuantumCircuit) and definition is not None: + # raise CircuitError('Instruction "{}" definition must be QuantumCircuit. Got {}'.format( + # self.name, type(definition))) + # self._definition = definition @property def decompositions(self): diff --git a/qiskit/transpiler/passes/basis/decompose.py b/qiskit/transpiler/passes/basis/decompose.py index 0e60ba980999..aa5bd12819b5 100644 --- a/qiskit/transpiler/passes/basis/decompose.py +++ b/qiskit/transpiler/passes/basis/decompose.py @@ -19,7 +19,7 @@ from qiskit.circuit.gate import Gate from qiskit.transpiler.basepasses import TransformationPass from qiskit.dagcircuit.dagcircuit import DAGCircuit -from qiskit.transpiler.passes.utils.ordered_regs import _make_ordered_regs +from qiskit.converters.circuit_to_dag import circuit_to_dag class Decompose(TransformationPass): @@ -54,12 +54,6 @@ def run(self, dag: DAGCircuit) -> DAGCircuit: if len(rule) == 1 and len(node.qargs) == len(rule[0][1]): dag.substitute_node(node, rule[0][0], inplace=True) else: - decomposition = DAGCircuit() - for qreg in node.op.definition.qregs: - decomposition.add_qreg(qreg) - for creg in node.op.definition.cregs: - decomposition.add_creg(creg) - for inst in rule: - decomposition.apply_operation_back(*inst) + decomposition = circuit_to_dag(node.op.definition) dag.substitute_node_with_dag(node, decomposition) return dag diff --git a/qiskit/transpiler/passes/basis/unroll_3q_or_more.py b/qiskit/transpiler/passes/basis/unroll_3q_or_more.py index 8f7eb52da64c..1b8d93d6dc15 100644 --- a/qiskit/transpiler/passes/basis/unroll_3q_or_more.py +++ b/qiskit/transpiler/passes/basis/unroll_3q_or_more.py @@ -17,6 +17,7 @@ from qiskit.transpiler.basepasses import TransformationPass from qiskit.dagcircuit import DAGCircuit from qiskit.exceptions import QiskitError +from qiskit.converters.circuit_to_dag import circuit_to_dag class Unroll3qOrMore(TransformationPass): @@ -42,13 +43,7 @@ def run(self, dag): raise QiskitError("Cannot unroll all 3q or more gates. " "No rule to expand instruction %s." % node.op.name) - decomposition = DAGCircuit() - for qreg in node.op.definition.qregs: - decomposition.add_qreg(qreg) - for creg in node.op.definition.cregs: - decomposition.add_creg(creg) - for inst in rule: - decomposition.apply_operation_back(*inst) + decomposition = circuit_to_dag(node.op.definition) decomposition = self.run(decomposition) # recursively unroll dag.substitute_node_with_dag(node, decomposition) return dag diff --git a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py index 0b9780218145..7037ec4695ac 100644 --- a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py +++ b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py @@ -18,6 +18,7 @@ from qiskit.exceptions import QiskitError from qiskit.transpiler.basepasses import TransformationPass from qiskit.circuit import ControlledGate +from qiskit.converters.circuit_to_dag import circuit_to_dag class UnrollCustomDefinitions(TransformationPass): @@ -83,14 +84,7 @@ def run(self, dag): "Instruction %s not found in equivalence library " "and no rule found to expand." % (str(self._basis_gates), node.op.name)) - decomposition = DAGCircuit() - for qreg in node.op.definition.qregs: - decomposition.add_qreg(qreg) - for creg in node.op.definition.cregs: - decomposition.add_creg(creg) - for inst in rule: - decomposition.apply_operation_back(*inst) - + decomposition = circuit_to_dag(node.op.definition) unrolled_dag = UnrollCustomDefinitions(self._equiv_lib, self._basis_gates).run( decomposition) diff --git a/qiskit/transpiler/passes/basis/unroller.py b/qiskit/transpiler/passes/basis/unroller.py index b635a9539b83..51c0b9990970 100644 --- a/qiskit/transpiler/passes/basis/unroller.py +++ b/qiskit/transpiler/passes/basis/unroller.py @@ -18,6 +18,7 @@ from qiskit.dagcircuit import DAGCircuit from qiskit.exceptions import QiskitError from qiskit.circuit import ControlledGate +from qiskit.converters.circuit_to_dag import circuit_to_dag class Unroller(TransformationPass): @@ -93,13 +94,7 @@ def run(self, dag): raise QiskitError("Cannot unroll the circuit to the given basis, %s. " "No rule to expand instruction %s." % (str(self.basis), node.op.name)) - decomposition = DAGCircuit() - for qreg in node.op.definition.qregs: - decomposition.add_qreg(qreg) - for creg in node.op.definition.cregs: - decomposition.add_creg(creg) - for inst in rule: - decomposition.apply_operation_back(*inst) + decomposition = circuit_to_dag(node.op.definition) unrolled_dag = self.run(decomposition) # recursively unroll ops dag.substitute_node_with_dag(node, unrolled_dag) return dag diff --git a/test/python/circuit/test_controlled_gate.py b/test/python/circuit/test_controlled_gate.py index b4bc8acf0418..aa88e8adbda1 100644 --- a/test/python/circuit/test_controlled_gate.py +++ b/test/python/circuit/test_controlled_gate.py @@ -226,66 +226,6 @@ def test_multi_control_u3(self): with self.subTest(i=info): self.assertTrue(matrix_equal(target, decomp, ignore_phase=True, atol=1e-8, rtol=1e-5)) - # def test_multi_control_u3_2(self): - # """Test the matrix representation of the controlled and controlled-controlled U3 gate.""" - # import qiskit.circuit.library.standard_gates.u3 as u3 - - # num_ctrl = 3 - # # U3 gate params - # alpha, beta, gamma = 0.2, 0.3, 0.4 - - # # cnu3 gate - # u3gate = u3.U3Gate(alpha, beta, gamma) - # cnu3 = u3gate.control(num_ctrl) - # width = cnu3.num_qubits - # qr = QuantumRegister(width) - # qcnu3 = QuantumCircuit(qr) - # qcnu3.append(cnu3, qr, []) - - # # U3 gate - # qu3 = QuantumCircuit(1) - # qu3.u3(alpha, beta, gamma, 0) - - # # CU3 gate - # qcu3 = QuantumCircuit(2) - # qcu3.cu3(alpha, beta, gamma, 0, 1) - - # # c-cu3 gate - # width = 3 - # qr = QuantumRegister(width) - # qc_cu3 = QuantumCircuit(qr) - # cu3gate = u3.CU3Gate(alpha, beta, gamma) - - # c_cu3 = cu3gate.control(1) - # qc_cu3.append(c_cu3, qr, []) - - # job = execute([qcnu3, qu3, qcu3, qc_cu3], BasicAer.get_backend('unitary_simulator'), - # basis_gates=['u1', 'u2', 'u3', 'id', 'cx']) - # result = job.result() - - # # Circuit unitaries - # mat_cnu3 = result.get_unitary(0) - - # mat_u3 = result.get_unitary(1) - # mat_cu3 = result.get_unitary(2) - # mat_c_cu3 = result.get_unitary(3) - - # # Target Controlled-U3 unitary - # target_cnu3 = _compute_control_matrix(mat_u3, num_ctrl) - # target_cu3 = np.kron(mat_u3, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) - # target_c_cu3 = np.kron(mat_cu3, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) - - # tests = [('check unitary of u3.control against tensored unitary of u3', - # target_cu3, mat_cu3), - # ('check unitary of cu3.control against tensored unitary of cu3', - # target_c_cu3, mat_c_cu3), - # ('check unitary of cnu3 against tensored unitary of u3', - # target_cnu3, mat_cnu3)] - # for itest in tests: - # info, target, decomp = itest[0], itest[1], itest[2] - # with self.subTest(i=info): - # self.log.info(info) - # self.assertTrue(matrix_equal(target, decomp, ignore_phase=True)) def test_multi_control_u1(self): """Test the matrix representation of the controlled and controlled-controlled U1 gate.""" From 3be2fddeb1ac7634ab45e0ea706d5e1f563aa071 Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Fri, 3 Jul 2020 10:49:42 -0400 Subject: [PATCH 07/11] linting --- qiskit/circuit/add_control.py | 2 ++ qiskit/circuit/instruction.py | 10 ---------- qiskit/transpiler/passes/basis/unroll_3q_or_more.py | 1 - .../passes/basis/unroll_custom_definitions.py | 1 - qiskit/transpiler/passes/basis/unroller.py | 1 - 5 files changed, 2 insertions(+), 13 deletions(-) diff --git a/qiskit/circuit/add_control.py b/qiskit/circuit/add_control.py index ecdceca40089..3849136fbffe 100644 --- a/qiskit/circuit/add_control.py +++ b/qiskit/circuit/add_control.py @@ -193,6 +193,7 @@ def _gate_to_circuit(operation): qc.append(operation, qargs=qr, cargs=[]) return qc + def _gate_to_dag(operation): from qiskit.converters.circuit_to_dag import circuit_to_dag if hasattr(operation, 'definition') and operation.definition: @@ -203,6 +204,7 @@ def _gate_to_dag(operation): qc.append(operation, qr) return circuit_to_dag(qc) + def _unroll_gate(operation, basis_gates): from qiskit.converters.dag_to_circuit import dag_to_circuit from qiskit.transpiler.passes import Unroller diff --git a/qiskit/circuit/instruction.py b/qiskit/circuit/instruction.py index 66bf5576ddc6..1c148ab28f68 100644 --- a/qiskit/circuit/instruction.py +++ b/qiskit/circuit/instruction.py @@ -181,16 +181,6 @@ def definition(self, array): """Set gate representation""" self._definition = array - # @definition.setter - # def definition(self, definition): - # """Set gate representation""" - # # pylint: disable=cyclic-import - # from qiskit import QuantumCircuit - # if not isinstance(definition, QuantumCircuit) and definition is not None: - # raise CircuitError('Instruction "{}" definition must be QuantumCircuit. Got {}'.format( - # self.name, type(definition))) - # self._definition = definition - @property def decompositions(self): """Get the decompositions of the instruction from the SessionEquivalenceLibrary.""" diff --git a/qiskit/transpiler/passes/basis/unroll_3q_or_more.py b/qiskit/transpiler/passes/basis/unroll_3q_or_more.py index 1b8d93d6dc15..5f4f6fdf7270 100644 --- a/qiskit/transpiler/passes/basis/unroll_3q_or_more.py +++ b/qiskit/transpiler/passes/basis/unroll_3q_or_more.py @@ -15,7 +15,6 @@ """Recursively expands 3q+ gates until the circuit only contains 2q or 1q gates.""" from qiskit.transpiler.basepasses import TransformationPass -from qiskit.dagcircuit import DAGCircuit from qiskit.exceptions import QiskitError from qiskit.converters.circuit_to_dag import circuit_to_dag diff --git a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py index 7037ec4695ac..3aa89beddfd3 100644 --- a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py +++ b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py @@ -14,7 +14,6 @@ """Unrolls instructions with custom definitions.""" -from qiskit.dagcircuit import DAGCircuit from qiskit.exceptions import QiskitError from qiskit.transpiler.basepasses import TransformationPass from qiskit.circuit import ControlledGate diff --git a/qiskit/transpiler/passes/basis/unroller.py b/qiskit/transpiler/passes/basis/unroller.py index 51c0b9990970..7a8158e96d50 100644 --- a/qiskit/transpiler/passes/basis/unroller.py +++ b/qiskit/transpiler/passes/basis/unroller.py @@ -15,7 +15,6 @@ """Unroll a circuit to a given basis.""" from qiskit.transpiler.basepasses import TransformationPass -from qiskit.dagcircuit import DAGCircuit from qiskit.exceptions import QiskitError from qiskit.circuit import ControlledGate from qiskit.converters.circuit_to_dag import circuit_to_dag From 56a21a520ab8fff119ffb4b009899eb186e634ec Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Fri, 3 Jul 2020 11:32:20 -0400 Subject: [PATCH 08/11] resolve doc forward ref --- qiskit/circuit/controlledgate.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/qiskit/circuit/controlledgate.py b/qiskit/circuit/controlledgate.py index a7de5417ceb1..406e55aceb39 100644 --- a/qiskit/circuit/controlledgate.py +++ b/qiskit/circuit/controlledgate.py @@ -17,6 +17,7 @@ from typing import List, Optional, Union from qiskit.circuit.exceptions import CircuitError +import qiskit.circuit.quantumcircuit as quantumcircuit from .gate import Gate from .quantumregister import QuantumRegister @@ -28,7 +29,7 @@ class ControlledGate(Gate): def __init__(self, name: str, num_qubits: int, params: List, label: Optional[str] = None, num_ctrl_qubits: Optional[int] = 1, - definition: Optional['QuantumCircuit'] = None, + definition: Optional['quantumcircuit.QuantumCircuit'] = None, ctrl_state: Optional[Union[int, str]] = None): """Create a new ControlledGate. In the new gate the first ``num_ctrl_qubits`` of the gate are the controls. @@ -105,13 +106,13 @@ def definition(self) -> List: `_definition`. """ # pylint: disable=cyclic-import - from qiskit import QuantumCircuit + #from qiskit import QuantumCircuit if self._open_ctrl: closed_gate = self.copy() closed_gate.ctrl_state = None bit_ctrl_state = bin(self.ctrl_state)[2:].zfill(self.num_ctrl_qubits) qreg = QuantumRegister(self.num_qubits, 'q') - qc_open_ctrl = QuantumCircuit(qreg) + qc_open_ctrl = quantumcircuit.QuantumCircuit(qreg) for qind, val in enumerate(bit_ctrl_state[::-1]): if val == '0': qc_open_ctrl.x(qind) @@ -124,7 +125,7 @@ def definition(self) -> List: return super().definition @definition.setter - def definition(self, excited_def: 'QuantumCircuit'): + def definition(self, excited_def: 'quantumcircuit.QuantumCircuit'): """Set controlled gate definition with closed controls. Args: From c977819b6ba313877e1c7933ab303c712ae8948f Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Fri, 3 Jul 2020 11:51:15 -0400 Subject: [PATCH 09/11] linting --- qiskit/circuit/controlledgate.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/qiskit/circuit/controlledgate.py b/qiskit/circuit/controlledgate.py index 406e55aceb39..a83bf245cde1 100644 --- a/qiskit/circuit/controlledgate.py +++ b/qiskit/circuit/controlledgate.py @@ -105,8 +105,6 @@ def definition(self) -> List: definition is conjugated with X without changing the internal `_definition`. """ - # pylint: disable=cyclic-import - #from qiskit import QuantumCircuit if self._open_ctrl: closed_gate = self.copy() closed_gate.ctrl_state = None From c22682294acd0ab4fea45795bb5e09ccceaf3932 Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Fri, 3 Jul 2020 14:56:14 -0400 Subject: [PATCH 10/11] linting --- qiskit/circuit/controlledgate.py | 1 + 1 file changed, 1 insertion(+) diff --git a/qiskit/circuit/controlledgate.py b/qiskit/circuit/controlledgate.py index a83bf245cde1..b4b33b2ca119 100644 --- a/qiskit/circuit/controlledgate.py +++ b/qiskit/circuit/controlledgate.py @@ -17,6 +17,7 @@ from typing import List, Optional, Union from qiskit.circuit.exceptions import CircuitError +# pylint: disable=cyclic-import import qiskit.circuit.quantumcircuit as quantumcircuit from .gate import Gate from .quantumregister import QuantumRegister From 160002e1d4f7cd88d1296467010b5009234f9454 Mon Sep 17 00:00:00 2001 From: Erick Winston Date: Fri, 3 Jul 2020 16:35:16 -0400 Subject: [PATCH 11/11] linting --- qiskit/circuit/controlledgate.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/qiskit/circuit/controlledgate.py b/qiskit/circuit/controlledgate.py index b4b33b2ca119..9592f0977df4 100644 --- a/qiskit/circuit/controlledgate.py +++ b/qiskit/circuit/controlledgate.py @@ -18,7 +18,7 @@ from qiskit.circuit.exceptions import CircuitError # pylint: disable=cyclic-import -import qiskit.circuit.quantumcircuit as quantumcircuit +from .quantumcircuit import QuantumCircuit from .gate import Gate from .quantumregister import QuantumRegister @@ -30,7 +30,7 @@ class ControlledGate(Gate): def __init__(self, name: str, num_qubits: int, params: List, label: Optional[str] = None, num_ctrl_qubits: Optional[int] = 1, - definition: Optional['quantumcircuit.QuantumCircuit'] = None, + definition: Optional['QuantumCircuit'] = None, ctrl_state: Optional[Union[int, str]] = None): """Create a new ControlledGate. In the new gate the first ``num_ctrl_qubits`` of the gate are the controls. @@ -111,7 +111,7 @@ def definition(self) -> List: closed_gate.ctrl_state = None bit_ctrl_state = bin(self.ctrl_state)[2:].zfill(self.num_ctrl_qubits) qreg = QuantumRegister(self.num_qubits, 'q') - qc_open_ctrl = quantumcircuit.QuantumCircuit(qreg) + qc_open_ctrl = QuantumCircuit(qreg) for qind, val in enumerate(bit_ctrl_state[::-1]): if val == '0': qc_open_ctrl.x(qind) @@ -124,7 +124,7 @@ def definition(self) -> List: return super().definition @definition.setter - def definition(self, excited_def: 'quantumcircuit.QuantumCircuit'): + def definition(self, excited_def: 'QuantumCircuit'): """Set controlled gate definition with closed controls. Args: