def anglecal_cx_circuits(max_reps, qubits, control_qubits, angleerr=0.0): """ Generates circuit for measuring the angle error of the cx gate The cx gate is repeatedly applied and we look at the population of the target qubit in the xy axis (amplitude erorr amplification sequence) X(control)-Y90(target)-(CX - Yp(target))^n - X90(target) Note: the circuit may not behave as intended if the target-control pairs are not in the coupling map Args: max_reps (int): the maximum number of repetitions. Circuits will increment by 1 rep up to max_rep qubits (list): a list of integers indices of the qubits to perform the calibration on control_qubits (list): a list of integer indices of the control qubits to perform the calibration on angleerr (float): put in an artificial angle error (for testing) Returns: tuple: A tuple of the form (``circuits``, ``xdata``) where ``circuits`` is a list of QuantumCircuit and ``xdata`` is a list of gate repetitions (number of u2 gates) """ xdata = np.arange(max_reps) qr = qiskit.QuantumRegister(max([max(qubits), max(control_qubits)]) + 1) cr = qiskit.ClassicalRegister(len(qubits)) circuits = [] for circ_index, circ_length in enumerate(xdata): circ = qiskit.QuantumCircuit(qr, cr) circ.name = 'anglecalcxcircuit_' + str(circ_index) + '_0' for qind, qubit in enumerate(qubits): circ.x(qr[control_qubits[qind]]) circ.append(U2Gate(0.0, 0.0), [qr[qubit]]) # Y90p (target) for _ in range(circ_length): if angleerr != 0: circ.append(U1Gate(-angleerr), [qr[qubit]]) circ.barrier([qr[control_qubits[qind]], qr[qubit]]) circ.cx(qr[control_qubits[qind]], qr[qubit]) if angleerr != 0: circ.append(U1Gate(angleerr), [qr[qubit]]) circ.y(qr[qubit]) # Yp (target) circ.append(U2Gate(-np.pi / 2., np.pi / 2.), [qr[qubit]]) # X90p (target) for qind, qubit in enumerate(qubits): circ.measure(qr[qubit], cr[qind]) circuits.append(circ) return circuits, xdata
def test_parameterized_expressions_in_circuits(self): """Expressions of Parameters should be treated as opaque gates.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") phi = Parameter("phi") sum_ = theta + phi product_ = theta * phi qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.4), [qr]) qc.append(U1Gate(theta), [qr]) qc.append(U1Gate(phi), [qr]) qc.append(U1Gate(sum_), [qr]) qc.append(U1Gate(product_), [qr]) qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.2), [qr]) dag = circuit_to_dag(qc) expected = QuantumCircuit(qr) expected.append(U1Gate(2 * theta + 2 * phi + product_ + 1.2), [qr]) after = Optimize1qGates().run(dag) self.assertEqual(circuit_to_dag(expected), after)
def anglecal_1Q_circuits(max_reps, qubits, angleerr=0.0): """ Generates circuit for measuring the angle error of the single qubit gate Y90-(X90-X90-Y90-Y90)^n - X90 Args: max_reps (int): the maximum number of repetitions. Circuits will increment by 1 rep up to max_rep qubits (list): a list of integers indices of the qubits to perform the calibration on angleerr (float): put in an artificial angle error (for testing) Returns: tuple: A tuple of the form (``circuits``, ``xdata``) where ``circuits`` is a list of QuantumCircuit and ``xdata`` is a list of gate repetitions (number of u2 gates) """ xdata = np.arange(max_reps) * 2 qr = qiskit.QuantumRegister(max(qubits) + 1) cr = qiskit.ClassicalRegister(len(qubits)) circuits = [] for circ_index, circ_length in enumerate(np.arange(max_reps)): circ = qiskit.QuantumCircuit(qr, cr) circ.name = 'anglecal1Qcircuit_' + str(circ_index) + '_0' for qind, qubit in enumerate(qubits): circ.append(U2Gate(0.0, 0.0), [qr[qubit]]) # Y90p for _ in range(circ_length): if angleerr != 0: circ.append(U1Gate(-2 * angleerr), [qr[qubit]]) for _ in range(2): circ.barrier(qr[qubit]) circ.append(U2Gate(-np.pi / 2, np.pi / 2), [qr[qubit]]) # Xp if angleerr != 0: circ.append(U1Gate(2 * angleerr), [qr[qubit]]) for _ in range(2): circ.barrier(qr[qubit]) circ.append(U2Gate(0.0, 0.0), [qr[qubit]]) # Yp if angleerr != 0: circ.append(U1Gate(-angleerr), [qr[qubit]]) circ.append(U2Gate(-np.pi / 2, np.pi / 2), [qr[qubit]]) # X90p for qind, qubit in enumerate(qubits): circ.measure(qr[qubit], cr[qind]) circuits.append(circ) return circuits, xdata
def test_commutative_circuit2(self): """ A simple circuit where three CNOTs commute, the first and the last cancel, also two X gates cancel and two Rz gates combine. qr0:----.---------------.-------- qr0:------------- | | qr1:---(+)---(+)--[X]--(+)--[X]-- = qr1:--------(+)-- | | qr2:---[Rz]---.---[Rz]-[T]--[S]-- qr2:--[U1]---.--- """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.cx(qr[2], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.t(qr[2]) circuit.s(qr[2]) circuit.x(qr[1]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi * 17 / 12), [qr[2]]) expected.cx(qr[2], qr[1]) self.assertEqual(expected, new_circuit)
def test_multi_controlled_u1_matrix(self, num_controls): """Test the matrix representation of the multi-controlled CU1 gate. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcu1.py """ # registers for the circuit q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2 ** num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] lam = 0.3165354 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == '0': qc.x(q_controls[idx]) qc.mcu1(lam, q_controls, q_target[0]) # for idx in subset: for idx, bit in enumerate(bitstr): if bit == '0': qc.x(q_controls[idx]) backend = BasicAer.get_backend('unitary_simulator') simulated = execute(qc, backend).result().get_unitary(qc) base = U1Gate(lam).to_matrix() expected = _compute_control_matrix(base, num_controls, ctrl_state=ctrl_state) with self.subTest(msg='control state = {}'.format(ctrl_state)): self.assertTrue(matrix_equal(simulated, expected))
def get_ghz_mqc(n: int, delta: float, full_measurement: bool = True) -> QuantumCircuit: """ This function creates an MQC circuit with n qubits, where the middle phase rotation around the z axis is by delta Args: n: number of qubits delta: the rotation of the middle phase around the z axis full_measurement: Whether to append full measurement, or only on the first qubit. Returns: The MQC circuit """ q = QuantumRegister(n, 'q') circ = get_ghz_simple(n, measure=False) circinv = circ.inverse() circ.barrier() circ.append(U1Gate(delta), [q]) circ.x(q) circ.barrier() circ += circinv meas = get_measurement_circ(n, 'q', 'c', full_measurement) circ = circ + meas return circ
def test_can_add_gates_into_free_space(self): """The scheduler does some time bookkeeping to know when qubits are free to be scheduled. Make sure this works for qubits that are used in the future. This was a bug, uncovered by this example: q0 = - - - - |X| q1 = |X| |u2| |X| In ALAP scheduling, the next operation on qubit 0 would be added at t=0 rather than immediately before the X gate. """ qr = QuantumRegister(2) qc = QuantumCircuit(qr) for i in range(2): qc.append(U2Gate(0, 0), [qr[i]]) qc.append(U1Gate(3.14), [qr[i]]) qc.append(U2Gate(0, 0), [qr[i]]) sched = schedule(qc, self.backend, method="alap") expected = Schedule( self.inst_map.get("u2", [0], 0, 0), self.inst_map.get("u2", [1], 0, 0), (2, self.inst_map.get("u1", [0], 3.14)), (2, self.inst_map.get("u1", [1], 3.14)), (2, self.inst_map.get("u2", [0], 0, 0)), (2, self.inst_map.get("u2", [1], 0, 0)), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1])
def get_ghz_mqc_para( n: int, full_measurement: bool = True) -> Tuple[QuantumCircuit, Parameter]: """ This function creates an MQC circuit with n qubits, where the middle phase rotation around the z axis is parameterized Args: n: number of qubits full_measurement: Whether to append full measurement, or only on the first qubit. Returns: An mqc circuit and its Delta parameter """ q = QuantumRegister(n, 'q') circ = get_ghz_simple(n, measure=False) delta = Parameter('t') circinv = circ.inverse() circ.barrier() circ.append(U1Gate(delta), [q]) circ.x(q) circ.barrier() circ += circinv meas = get_measurement_circ(n, 'q', 'c', full_measurement) circ = circ + meas return circ, delta
def test_unrolling_parameterized_composite_gates(self): """Verify unrolling circuits with parameterized composite gates.""" qr1 = QuantumRegister(2) subqc = QuantumCircuit(qr1) theta = Parameter("theta") subqc.rz(theta, qr1[0]) subqc.cx(qr1[0], qr1[1]) subqc.rz(theta, qr1[1]) # Expanding across register with shared parameter qr2 = QuantumRegister(4) qc = QuantumCircuit(qr2) qc.append(subqc.to_instruction(), [qr2[0], qr2[1]]) qc.append(subqc.to_instruction(), [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "u3", "cx"]).run(dag) # Pick up -1 * theta / 2 global phase four twice (once for each RZ -> P # in each of the two sub_instr instructions). expected = QuantumCircuit(qr2, global_phase=-1 * 4 * theta / 2.0) expected.append(U1Gate(theta), [qr2[0]]) expected.cx(qr2[0], qr2[1]) expected.append(U1Gate(theta), [qr2[1]]) expected.append(U1Gate(theta), [qr2[2]]) expected.cx(qr2[2], qr2[3]) expected.append(U1Gate(theta), [qr2[3]]) self.assertEqual(circuit_to_dag(expected), out_dag) # Expanding across register with shared parameter qc = QuantumCircuit(qr2) phi = Parameter("phi") gamma = Parameter("gamma") qc.append(subqc.to_instruction({theta: phi}), [qr2[0], qr2[1]]) qc.append(subqc.to_instruction({theta: gamma}), [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "u3", "cx"]).run(dag) expected = QuantumCircuit(qr2, global_phase=-1 * (2 * phi + 2 * gamma) / 2.0) expected.append(U1Gate(phi), [qr2[0]]) expected.cx(qr2[0], qr2[1]) expected.append(U1Gate(phi), [qr2[1]]) expected.append(U1Gate(gamma), [qr2[2]]) expected.cx(qr2[2], qr2[3]) expected.append(U1Gate(gamma), [qr2[3]]) self.assertEqual(circuit_to_dag(expected), out_dag)
def test_ignores_conditional_rotations(self): """Conditional rotations should not be considered in the chain. qr0:--[U1]-[U1]-[U1]-[U1]- qr0:--[U1]-[U1]- || || || || cr0:===.================== == cr0:===.====.=== || || cr1:========.============= cr1:========.=== """ qr = QuantumRegister(1, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(U1Gate(0.1), [qr]).c_if(cr, 1) circuit.append(U1Gate(0.2), [qr]).c_if(cr, 3) circuit.append(U1Gate(0.3), [qr]) circuit.append(U1Gate(0.4), [qr]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.append(U1Gate(0.1), [qr]).c_if(cr, 1) expected.append(U1Gate(0.2), [qr]).c_if(cr, 3) expected.append(U1Gate(0.7), [qr]) pass_ = Optimize1qGates() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after)
def test_loading_all_qelib1_gates(self): """Test setting up a circuit with all gates defined in qiskit/qasm/libs/qelib1.inc.""" from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, UGate all_gates_qasm = os.path.join(self.qasm_dir, "all_gates.qasm") qasm_circuit = QuantumCircuit.from_qasm_file(all_gates_qasm) ref_circuit = QuantumCircuit(3, 3) # abstract gates (legacy) ref_circuit.append(UGate(0.2, 0.1, 0.6), [0]) ref_circuit.cx(0, 1) # the hardware primitives ref_circuit.append(U3Gate(0.2, 0.1, 0.6), [0]) ref_circuit.append(U2Gate(0.1, 0.6), [0]) ref_circuit.append(U1Gate(0.6), [0]) ref_circuit.id(0) ref_circuit.cx(0, 1) # the standard single qubit gates ref_circuit.u(0.2, 0.1, 0.6, 0) ref_circuit.p(0.6, 0) ref_circuit.x(0) ref_circuit.y(0) ref_circuit.z(0) ref_circuit.h(0) ref_circuit.s(0) ref_circuit.t(0) ref_circuit.sdg(0) ref_circuit.tdg(0) ref_circuit.sx(0) ref_circuit.sxdg(0) # the standard rotations ref_circuit.rx(0.1, 0) ref_circuit.ry(0.1, 0) ref_circuit.rz(0.1, 0) # the barrier ref_circuit.barrier() # the standard user-defined gates ref_circuit.swap(0, 1) ref_circuit.cswap(0, 1, 2) ref_circuit.cy(0, 1) ref_circuit.cz(0, 1) ref_circuit.ch(0, 1) ref_circuit.csx(0, 1) ref_circuit.append(CU1Gate(0.6), [0, 1]) ref_circuit.append(CU3Gate(0.2, 0.1, 0.6), [0, 1]) ref_circuit.cp(0.6, 0, 1) ref_circuit.cu(0.2, 0.1, 0.6, 0, 0, 1) ref_circuit.ccx(0, 1, 2) ref_circuit.crx(0.6, 0, 1) ref_circuit.cry(0.6, 0, 1) ref_circuit.crz(0.6, 0, 1) ref_circuit.rxx(0.2, 0, 1) ref_circuit.rzz(0.2, 0, 1) ref_circuit.measure([0, 1, 2], [0, 1, 2]) self.assertEqual(qasm_circuit, ref_circuit)
def test_all_gates(self): """Test all gates on 1 and 2 qubits q0:-[H]-[H]--[x]-[x]--[y]-[y]--[rz]-[rz]--[u1]-[u1]-[rx]-[rx]---.--.--.--.--.--.- | | | | | | q1:-------------------------------------------------------------X--X--Y--Y--.--.- = qr0:---[u1]--- qr1:---------- """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.x(qr[0]) circuit.x(qr[0]) circuit.y(qr[0]) circuit.y(qr[0]) circuit.rz(0.5, qr[0]) circuit.rz(0.5, qr[0]) circuit.append(U1Gate(0.5), [qr[0]]) # TODO this should work with Phase gates too circuit.append(U1Gate(0.5), [qr[0]]) circuit.rx(0.5, qr[0]) circuit.rx(0.5, qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(RZGate(2.0), [qr[0]]) expected.rx(1.0, qr[0]) self.assertEqual(expected, new_circuit)
def test_commutative_circuit3(self): """ A simple circuit where three CNOTs commute, the first and the last cancel, also two X gates cancel and two Rz gates combine. qr0:-------.------------------.------------- qr0:------------- | | qr1:------(+)------(+)--[X]--(+)-------[X]-- = qr1:--------(+)-- | | qr2:------[Rz]--.---.----.---[Rz]-[T]--[S]-- qr2:--[U1]---.--- | | qr3:-[Rz]--[X]-(+)------(+)--[X]-[Rz]------- qr3:--[Rz]------- """ qr = QuantumRegister(4, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.rz(np.pi / 3, qr[3]) circuit.x(qr[3]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[2], qr[3]) circuit.rz(np.pi / 3, qr[2]) circuit.t(qr[2]) circuit.x(qr[3]) circuit.rz(np.pi / 3, qr[3]) circuit.s(qr[2]) circuit.x(qr[1]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) passmanager = PassManager() passmanager.append([CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint('size')], do_while=lambda property_set: not property_set['size_fixed_point']) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi * 17 / 12), [qr[2]]) expected.append(U1Gate(np.pi * 2 / 3), [qr[3]]) expected.cx(qr[2], qr[1]) self.assertEqual(expected, new_circuit)
def test_unrolling_parameterized_composite_gates(self): """Verify unrolling circuits with parameterized composite gates.""" qr1 = QuantumRegister(2) subqc = QuantumCircuit(qr1) theta = Parameter('theta') subqc.rz(theta, qr1[0]) subqc.cx(qr1[0], qr1[1]) subqc.rz(theta, qr1[1]) # Expanding across register with shared parameter qr2 = QuantumRegister(4) qc = QuantumCircuit(qr2) qc.append(subqc.to_instruction(), [qr2[0], qr2[1]]) qc.append(subqc.to_instruction(), [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) out_dag = Unroller(['u1', 'u3', 'cx']).run(dag) expected = QuantumCircuit(qr2) expected.append(U1Gate(theta), [qr2[0]]) expected.cx(qr2[0], qr2[1]) expected.append(U1Gate(theta), [qr2[1]]) expected.append(U1Gate(theta), [qr2[2]]) expected.cx(qr2[2], qr2[3]) expected.append(U1Gate(theta), [qr2[3]]) self.assertEqual(circuit_to_dag(expected), out_dag) # Expanding across register with shared parameter qc = QuantumCircuit(qr2) phi = Parameter('phi') gamma = Parameter('gamma') qc.append(subqc.to_instruction({theta: phi}), [qr2[0], qr2[1]]) qc.append(subqc.to_instruction({theta: gamma}), [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) out_dag = Unroller(['u1', 'u3', 'cx']).run(dag) expected = QuantumCircuit(qr2) expected.append(U1Gate(phi), [qr2[0]]) expected.cx(qr2[0], qr2[1]) expected.append(U1Gate(phi), [qr2[1]]) expected.append(U1Gate(gamma), [qr2[2]]) expected.cx(qr2[2], qr2[3]) expected.append(U1Gate(gamma), [qr2[3]]) self.assertEqual(circuit_to_dag(expected), out_dag)
def myR2(i, neighbor_range, cr): qr = QuantumRegister(1) qc = QuantumCircuit(qr) for j in neighbor_range: theta = math.pi / float(2**(j + 1)) gate = U1Gate(theta, i + (j + 1)).c_if(cr, 1) qc.append(gate, qargs=qr[:]) gate = qc.to_gate() gate.name = f'R_{i}' return gate
def test_multi_controlled_rotation_gate_matrices(self, num_controls, base_gate_name, use_basis_gates): """Test the multi controlled rotation gates without ancillas. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == '0': qc.x(q_controls[idx]) # call mcrx/mcry/mcrz if base_gate_name == 'y': qc.mcry(theta, q_controls, q_target[0], None, mode='noancilla', use_basis_gates=use_basis_gates) else: # case 'x' or 'z' only support the noancilla mode and do not have this keyword getattr(qc, 'mcr' + base_gate_name)( theta, q_controls, q_target[0], use_basis_gates=use_basis_gates) for idx, bit in enumerate(bitstr): if bit == '0': qc.x(q_controls[idx]) backend = BasicAer.get_backend('unitary_simulator') simulated = execute(qc, backend).result().get_unitary(qc) if base_gate_name == 'x': rot_mat = RXGate(theta).to_matrix() elif base_gate_name == 'y': rot_mat = RYGate(theta).to_matrix() else: # case 'z' rot_mat = U1Gate(theta).to_matrix() expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg='control state = {}'.format(ctrl_state)): self.assertTrue(matrix_equal(simulated, expected))
def generate_parameterized_circuit(): """Generate a circuit with parameters and parameter expressions.""" param_circuit = QuantumCircuit(1) theta = Parameter("theta") lam = Parameter("λ") theta_pi = 3.14159 * theta pe = theta_pi / lam param_circuit.append(U3Gate(theta, theta_pi, lam), [0]) param_circuit.append(U1Gate(pe), [0]) param_circuit.append(U2Gate(theta_pi, lam), [0]) return param_circuit
def test_no_conflict_backend_passmanager(self): """execute(qc, backend=..., passmanager=...) See: https://github.com/Qiskit/qiskit-terra/issues/5037 """ backend = BasicAer.get_backend('qasm_simulator') qc = QuantumCircuit(2) qc.append(U1Gate(0), [0]) qc.measure_all() job = execute(qc, backend=backend, pass_manager=PassManager()) result = job.result().get_counts() self.assertEqual(result, {'00': 1024})
def gate_to_qiskit(gate2): if gate2.name == 'X': return XGate() elif gate2.name == 'Ry': return RYGate(-gate2.arg) elif gate2.name == 'Rz': return RZGate(-gate2.arg) elif gate2.name == 'R1': return U1Gate(gate2.arg) else: raise RuntimeError("Can't implement: %s" % gate2)
def test_in_the_back(self): """Optimizations can be in the back of the circuit. See https://github.com/Qiskit/qiskit-terra/issues/2004. qr0:--[U1]-[U1]-[H]-- qr0:--[U1]-[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U1Gate(0.3), [qr]) circuit.append(U1Gate(0.4), [qr]) circuit.h(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.append(U1Gate(0.7), [qr]) expected.h(qr) pass_ = Optimize1qGates() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after)
def test_unroll_1q_chain_conditional(self): """Test unroll chain of 1-qubit gates interrupted by conditional. """ qr = QuantumRegister(1, 'qr') cr = ClassicalRegister(1, 'cr') circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.tdg(qr) circuit.z(qr) circuit.t(qr) circuit.ry(0.5, qr) circuit.rz(0.3, qr) circuit.rx(0.1, qr) circuit.measure(qr, cr) circuit.x(qr).c_if(cr, 1) circuit.y(qr).c_if(cr, 1) circuit.z(qr).c_if(cr, 1) dag = circuit_to_dag(circuit) pass_ = UnrollCustomDefinitions(std_eqlib, ['u1', 'u2', 'u3']) dag = pass_.run(dag) pass_ = BasisTranslator(std_eqlib, ['u1', 'u2', 'u3']) unrolled_dag = pass_.run(dag) # Pick up -1 * 0.3 / 2 global phase for one RZ -> U1. ref_circuit = QuantumCircuit(qr, cr, global_phase=-0.3 / 2) ref_circuit.append(U2Gate(0, pi), [qr[0]]) ref_circuit.append(U1Gate(-pi / 4), [qr[0]]) ref_circuit.append(U1Gate(pi), [qr[0]]) ref_circuit.append(U1Gate(pi / 4), [qr[0]]) ref_circuit.append(U3Gate(0.5, 0, 0), [qr[0]]) ref_circuit.append(U1Gate(0.3), [qr[0]]) ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]]) ref_circuit.measure(qr[0], cr[0]) ref_circuit.append(U3Gate(pi, 0, pi), [qr[0]]).c_if(cr, 1) ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[0]]).c_if(cr, 1) ref_circuit.append(U1Gate(pi), [qr[0]]).c_if(cr, 1) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag)
def test_optimize_1q_gates_collapse_identity_equivalent(self): """test optimize_1q_gates removes u1(2*pi) rotations. See: https://github.com/Qiskit/qiskit-terra/issues/159 """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[1], qr[0]) qc.append(U1Gate(2 * np.pi), [qr[0]]) qc.cx(qr[1], qr[0]) qc.append(U1Gate(np.pi / 2), [qr[0]]) # these three should combine qc.append(U1Gate(np.pi), [qr[0]]) # to identity then qc.append(U1Gate(np.pi / 2), [qr[0]]) # optimized away. qc.cx(qr[1], qr[0]) qc.append(U1Gate(np.pi), [qr[1]]) qc.append(U1Gate(np.pi), [qr[1]]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) dag = circuit_to_dag(qc) simplified_dag = Optimize1qGates().run(dag) num_u1_gates_remaining = len(simplified_dag.named_nodes("u1")) self.assertEqual(num_u1_gates_remaining, 0)
def test_global_phase_u_on_left(self): """Check proper phase accumulation with instruction with no definition.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) u1 = U1Gate(0.1) u1.definition.global_phase = np.pi / 2 qc.append(u1, [0]) qc.global_phase = np.pi / 3 qc.append(UGate(0.1, 0.2, 0.3), [0]) dag = circuit_to_dag(qc) after = Optimize1qGates(["u1", "u2", "u", "cx"]).run(dag) self.assertAlmostEqual(after.global_phase, 5 * np.pi / 6, 8)
def test_optimize_u1_basis_u2(self): """U1(pi/4) -> Raises. Basis [u2]""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U1Gate(np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2"])) with self.assertRaises(TranspilerError): _ = passmanager.run(circuit)
def test_u_gates(self): """Test U 1, 2, & 3 gates""" from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate qr = QuantumRegister(4, 'q') circuit = QuantumCircuit(qr) circuit.append(U1Gate(3 * pi / 2), [0]) circuit.append(U2Gate(3 * pi / 2, 2 * pi / 3), [1]) circuit.append(U3Gate(3 * pi / 2, 4.5, pi / 4), [2]) circuit.append(CU1Gate(pi / 4), [0, 1]) circuit.append(U2Gate(pi / 2, 3 * pi / 2).control(1), [2, 3]) circuit.append(CU3Gate(3 * pi / 2, -3 * pi / 4, -pi / 2), [0, 1]) self.circuit_drawer(circuit, filename='u_gates.png')
class TestParameterCtrlState(QiskitTestCase): """Test gate equality with ctrl_state parameter.""" @data((RXGate(0.5), CRXGate(0.5)), (RYGate(0.5), CRYGate(0.5)), (RZGate(0.5), CRZGate(0.5)), (XGate(), CXGate()), (YGate(), CYGate()), (ZGate(), CZGate()), (U1Gate(0.5), CU1Gate(0.5)), (SwapGate(), CSwapGate()), (HGate(), CHGate()), (U3Gate(0.1, 0.2, 0.3), CU3Gate(0.1, 0.2, 0.3))) @unpack def test_ctrl_state_one(self, gate, controlled_gate): """Test controlled gates with ctrl_state See https://github.com/Qiskit/qiskit-terra/pull/4025 """ self.assertEqual(gate.control(1, ctrl_state='1'), controlled_gate)
def test_optimize_u3_to_u1_round(self): """U3(1e-16, 1e-16, pi/4) -> U1(pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(1e-16, 1e-16, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result)
def test_parameterized_circuit_for_simulator(self): """Verify that a parameterized circuit can be transpiled for a simulator backend.""" qr = QuantumRegister(2, name='qr') qc = QuantumCircuit(qr) theta = Parameter('theta') qc.rz(theta, qr[0]) transpiled_qc = transpile(qc, backend=BasicAer.get_backend('qasm_simulator')) expected_qc = QuantumCircuit(qr, global_phase=-1 * theta / 2.0) expected_qc.append(U1Gate(theta), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc)
def test_optimize_u_basis_u1(self): """U(0, 0, pi/4) -> U1(pi/4). Basis [u1].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(UGate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u1"])) result = passmanager.run(circuit) self.assertEqual(expected, result)
def test_optimize_u1_basis_u2_u(self): """U1(pi/4) -> U3(0, 0, pi/4). Basis [u2, u3].""" qr = QuantumRegister(1, 'qr') circuit = QuantumCircuit(qr) circuit.append(U1Gate(np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(UGate(0, 0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(['u2', 'u'])) result = passmanager.run(circuit) self.assertEqual(expected, result)