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.converters.instruction_to_gate import instruction_to_gate from qiskit.transpiler.passes import Unroller unroller = Unroller(basis_gates) dag = circuit_to_dag(_gate_to_circuit(operation)) qc = dag_to_circuit(unroller.run(dag)) return instruction_to_gate(qc.to_instruction())
def test_inverse_circuit(self, num_ctrl_qubits): """test inverting ControlledGate""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.rx(np.pi / 4, [0, 1, 2]) gate = instruction_to_gate(qc.to_instruction()) cgate = gate.q_if(num_ctrl_qubits) inv_cgate = cgate.inverse() result = Operator(cgate).compose(Operator(inv_cgate)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0]))
def test_controlled_unitary(self, num_ctrl_qubits): """test controlled unitary""" num_target = 1 q_target = QuantumRegister(num_target) qc1 = QuantumCircuit(q_target) # for h-rx(pi/2) theta, phi, lamb = 1.57079632679490, 0.0, 4.71238898038469 qc1.u3(theta, phi, lamb, q_target[0]) base_gate = instruction_to_gate(qc1.to_instruction()) # get UnitaryGate version of circuit base_op = Operator(qc1) base_mat = base_op.data cgate = base_gate.q_if(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(is_unitary_matrix(base_mat)) self.assertTrue(matrix_equal(cop_mat, test_op.data, ignore_phase=True))
def test_single_controlled_composite_gate(self): """Test singly controlled composite gate""" num_ctrl = 1 # create composite gate sub_q = QuantumRegister(2) cgate = QuantumCircuit(sub_q, name='cgate') cgate.h(sub_q[0]) cgate.cx(sub_q[0], sub_q[1]) num_target = cgate.width() gate = instruction_to_gate(cgate.to_instruction()) cont_gate = gate.q_if(num_ctrl_qubits=num_ctrl) control = QuantumRegister(num_ctrl) 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) cop_mat = _compute_control_matrix(op_mat, num_ctrl) ref_mat = execute(qc, simulator).result().get_unitary(0) self.assertTrue(matrix_equal(cop_mat, ref_mat, ignore_phase=True))