def test_3q_schedule(self): """Test a schedule that was recommended by David McKay :D""" # ┌─────────────────┐ # q0_0: ─────────■─────────┤ U3(3.14,1.57,0) ├──────────────────────── # ┌─┴─┐ └┬───────────────┬┘ # q0_1: ───────┤ X ├────────┤ U2(3.14,1.57) ├───■───────────────────── # ┌──────┴───┴──────┐ └───────────────┘ ┌─┴─┐┌─────────────────┐ # q0_2: ┤ U2(0.778,0.122) ├───────────────────┤ X ├┤ U2(0.778,0.122) ├ # └─────────────────┘ └───┘└─────────────────┘ backend = FakeOpenPulse3Q() inst_map = backend.defaults().instruction_schedule_map q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.append(U2Gate(0.778, 0.122), [q[2]]) qc.append(U3Gate(3.14, 1.57, 0), [q[0]]) qc.append(U2Gate(3.14, 1.57), [q[1]]) qc.cx(q[1], q[2]) qc.append(U2Gate(0.778, 0.122), [q[2]]) sched = schedule(qc, backend) expected = Schedule( inst_map.get("cx", [0, 1]), (22, inst_map.get("u2", [1], 3.14, 1.57)), (22, inst_map.get("u2", [2], 0.778, 0.122)), (24, inst_map.get("cx", [1, 2])), (44, inst_map.get("u3", [0], 3.14, 1.57, 0)), (46, inst_map.get("u2", [2], 0.778, 0.122)), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1])
def test_direction_flip(self): """ Flip a CX qr0:----.---- | qr1:---(+)--- CouplingMap map: [0] -> [1] qr0:-[H]-(+)-[H]-- | qr1:-[H]--.--[H]-- """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.append(U2Gate(0, pi), [qr[0]]) expected.append(U2Gate(0, pi), [qr[1]]) expected.cx(qr[0], qr[1]) expected.append(U2Gate(0, pi), [qr[0]]) expected.append(U2Gate(0, pi), [qr[1]]) pass_ = CXDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after)
def test_alap_pass(self): """Test ALAP scheduling.""" # ┌───────────────┐ ░ ┌─┐ # q0_0: ┤ U2(3.14,1.57) ├────────────────────░───■──┤M├─── # └┬──────────────┤ ░ ┌──────────────┐ ░ ┌─┴─┐└╥┘┌─┐ # q0_1: ─┤ U2(0.5,0.25) ├─░─┤ U2(0.5,0.25) ├─░─┤ X ├─╫─┤M├ # └──────────────┘ ░ └──────────────┘ ░ └───┘ ║ └╥┘ # c0: 2/═════════════════════════════════════════════╩══╩═ # 0 1 q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(3.14, 1.57), [q[0]]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[0], [q[1]]) qc.cx(q[0], q[1]) qc.measure(q, c) sched = schedule(qc, self.backend) # X pulse on q0 should end at the start of the CNOT expected = Schedule( (2, self.inst_map.get("u2", [0], 3.14, 1.57)), self.inst_map.get("u2", [1], 0.5, 0.25), (2, self.inst_map.get("u2", [1], 0.5, 0.25)), (4, self.inst_map.get("cx", [0, 1])), (26, self.inst_map.get("measure", [0, 1])), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1])
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 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_adding_gate_and_partially_specified_gate(self): """Verify entries will different numbers of parameters will be returned.""" eq_lib = EquivalenceLibrary() theta = Parameter('theta') phi = Parameter('phi') # e.g. RGate(theta, phi) gate_full = OneQubitTwoParamGate(theta, phi) equiv_full = QuantumCircuit(1) equiv_full.append(U2Gate(theta, phi), [0]) eq_lib.add_equivalence(gate_full, equiv_full) gate_partial = OneQubitTwoParamGate(theta, 0) equiv_partial = QuantumCircuit(1) equiv_partial.rx(theta, 0) eq_lib.add_equivalence(gate_partial, equiv_partial) lam = Parameter('lam') gate_query = OneQubitTwoParamGate(lam, 0) entry = eq_lib.get_entry(gate_query) first_expected = QuantumCircuit(1) first_expected.append(U2Gate(lam, 0), [0]) second_expected = QuantumCircuit(1) second_expected.rx(lam, 0) self.assertEqual(len(entry), 2) self.assertEqual(entry[0], first_expected) self.assertEqual(entry[1], second_expected)
def test_metadata_is_preserved_asap(self): """Test that circuit metadata is preserved in output schedule with asap.""" q = QuantumRegister(2) qc = QuantumCircuit(q) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) qc.metadata = {"experiment_type": "gst", "execution_number": "1234"} sched = schedule(qc, self.backend, method="asap") self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata)
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_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')
def test_metadata_is_preserved_alap(self): """Test that circuit metadata is preserved in output schedule with alap.""" q = QuantumRegister(2) qc = QuantumCircuit(q) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) qc.metadata = {'experiment_type': 'gst', 'execution_number': '1234'} sched = schedule(qc, self.backend, method='alap') self.assertEqual({ 'experiment_type': 'gst', 'execution_number': '1234' }, sched.metadata)
def test_alap_with_barriers(self): """Test that ALAP respects barriers on new qubits.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) sched = schedule(qc, self.backend, method="alap") expected = Schedule(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 test_pulse_gates(self): """Test scheduling calibrated pulse gates.""" q = QuantumRegister(2) qc = QuantumCircuit(q) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) qc.add_calibration('u2', [0], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(0))), [0, 0]) qc.add_calibration('u2', [1], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1))), [0, 0]) sched = schedule(qc, self.backend) expected = Schedule( Play(Gaussian(28, 0.2, 4), DriveChannel(0)), (28, Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1))))) self.assertEqual(sched.instructions, expected.instructions)
def test_u_gates(self): """Test U 1, 2, & 3 gates""" filename = self._get_resource_path('test_latex_u_gates.tex') 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]) circuit_drawer(circuit, filename=filename, output='latex_source') self.assertEqualToReference(filename)
def get_ghz_po_para( self, n: int) -> Tuple[QuantumCircuit, List[Parameter], Dict]: """ Get a parametrized PO circuit. Remember that get_counts() method accepts an index now, not a circuit. The two phase parameters are a quirk of the Parameter module Args: n: number of qubits Returns: A parity oscillation circuit, its Delta/minus-delta parameters, and the initial ghz layout """ circ, initial_layout = self.get_ghz_layout(n) q = QuantumRegister(n, 'q') rotate = QuantumCircuit(q) delta = Parameter('t') deltaneg = Parameter('-t') rotate.barrier() rotate.append(U2Gate(delta, deltaneg), [q]) rotate.barrier() rotate = transpile(rotate, backend=self.backend, initial_layout=initial_layout) meas = self.get_measurement_circ(n, 'q', 'c', True) meas = transpile(meas, backend=self.backend, initial_layout=initial_layout) new_circ = circ + rotate + meas return new_circ, [delta, deltaneg], initial_layout
def test_measure_combined(self): """ Test to check for measure on the same qubit which generated another measure schedule. The measures on different qubits are combined, but measures on the same qubit adds another measure to the schedule. """ q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(3.14, 1.57), [q[0]]) qc.cx(q[0], q[1]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[1], c[1]) sched = schedule(qc, self.backend, method="as_soon_as_possible") expected = Schedule( self.inst_map.get("u2", [0], 3.14, 1.57), (2, self.inst_map.get("cx", [0, 1])), (24, self.inst_map.get("measure", [0, 1])), (34, self.inst_map.get( "measure", [0, 1]).filter(channels=[MeasureChannel(1)])), (34, Acquire(10, AcquireChannel(1), MemorySlot(1))), ) self.assertEqual(sched.instructions, expected.instructions)
def test_custom_multiple_circuits(self): """Test transpiling with custom pass manager and multiple circuits. This tests created a deadlock, so it needs to be monitored for timeout. See: https://github.com/Qiskit/qiskit-terra/issues/3925 """ qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) pm_conf = PassManagerConfig(initial_layout=None, basis_gates=['u1', 'u2', 'u3', 'cx'], coupling_map=CouplingMap([[0, 1]]), backend_properties=None, seed_transpiler=1) passmanager = level_0_pass_manager(pm_conf) transpiled = passmanager.run([qc, qc]) expected = QuantumCircuit(QuantumRegister(2, 'q')) expected.append(U2Gate(0, 3.141592653589793), [0]) expected.cx(0, 1) self.assertEqual(len(transpiled), 2) self.assertEqual(transpiled[0], expected) self.assertEqual(transpiled[1], expected)
def default_gateset_basis(): """Returns a default tomographically-complete gateset basis Return value: The gateset given as example 3.4.1 in arXiv:1509.02921 """ default_gates = { 'Id': lambda circ, qubit: None, 'X_Rot_90': lambda circ, qubit: circ.append(U2Gate(-np.pi / 2, np.pi / 2), [qubit]), 'Y_Rot_90': lambda circ, qubit: circ.append(U2Gate(np.pi, np.pi), [qubit]) } default_spam = { 'F0': ('Id',), 'F1': ('X_Rot_90',), 'F2': ('Y_Rot_90',), 'F3': ('X_Rot_90', 'X_Rot_90') } return GateSetBasis('Default GST', default_gates, default_spam)
def test_layout_2503(self, level): """Test that a user-given initial layout is respected, even if cnots are not in the coupling map. See: https://github.com/Qiskit/qiskit-terra/issues/2503 """ # build a circuit which works as-is on the coupling map, using the initial layout qr = QuantumRegister(3, "q") cr = ClassicalRegister(2) ancilla = QuantumRegister(17, "ancilla") qc = QuantumCircuit(qr, cr) qc.append(U3Gate(0.1, 0.2, 0.3), [qr[0]]) qc.append(U2Gate(0.4, 0.5), [qr[2]]) qc.barrier() qc.cx(qr[0], qr[2]) initial_layout = [6, 7, 12] final_layout = { 0: ancilla[0], 1: ancilla[1], 2: ancilla[2], 3: ancilla[3], 4: ancilla[4], 5: ancilla[5], 6: qr[0], 7: qr[1], 8: ancilla[6], 9: ancilla[7], 10: ancilla[8], 11: ancilla[9], 12: qr[2], 13: ancilla[10], 14: ancilla[11], 15: ancilla[12], 16: ancilla[13], 17: ancilla[14], 18: ancilla[15], 19: ancilla[16], } backend = FakePoughkeepsie() qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) self.assertEqual(qc_b._layout._p2v, final_layout) gate_0, qubits_0, _ = qc_b[0] gate_1, qubits_1, _ = qc_b[1] output_qr = qc_b.qregs[0] self.assertIsInstance(gate_0, U3Gate) self.assertEqual(qubits_0[0], output_qr[6]) self.assertIsInstance(gate_1, U2Gate) self.assertEqual(qubits_1[0], output_qr[12])
def test_preserves_conditions(self): """Verify CXDirection preserves conditional on CX gates. ┌───┐ ┌───┐ q_0: |0>───■────┤ X ├───■──┤ X ├ ┌─┴─┐ └─┬─┘ ┌─┴─┐└─┬─┘ q_1: |0>─┤ X ├────■───┤ X ├──■── └─┬─┘ │ └───┘ ┌──┴──┐┌──┴──┐ c_0: 0 ╡ = 0 ╞╡ = 0 ╞══════════ └─────┘└─────┘ """ qr = QuantumRegister(2, 'q') cr = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[1]).c_if(cr, 0) circuit.cx(qr[1], qr[0]).c_if(cr, 0) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.cx(qr[0], qr[1]).c_if(cr, 0) # Ordering of u2 is important because DAG comparison will consider # different conditional order on a creg to be a different circuit. # See https://github.com/Qiskit/qiskit-terra/issues/3164 expected.append(U2Gate(0, pi), [[qr[1], qr[0]]]).c_if(cr, 0) expected.cx(qr[0], qr[1]).c_if(cr, 0) expected.append(U2Gate(0, pi), [[qr[1], qr[0]]]).c_if(cr, 0) expected.cx(qr[0], qr[1]) expected.append(U2Gate(0, pi), [[qr[1], qr[0]]]) expected.cx(qr[0], qr[1]) expected.append(U2Gate(0, pi), [[qr[1], qr[0]]]) pass_ = CXDirection(coupling) 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_callback(self): """Test the callback parameter.""" qr = QuantumRegister(1, 'qr') circuit = QuantumCircuit(qr, name='MyCircuit') circuit.h(qr[0]) circuit.h(qr[0]) circuit.h(qr[0]) expected_start = QuantumCircuit(qr) expected_start.append(U2Gate(0, np.pi), [qr[0]]) expected_start.append(U2Gate(0, np.pi), [qr[0]]) expected_start.append(U2Gate(0, np.pi), [qr[0]]) expected_start_dag = circuit_to_dag(expected_start) expected_end = QuantumCircuit(qr) expected_end.append(U2Gate(0, np.pi), [qr[0]]) expected_end_dag = circuit_to_dag(expected_end) calls = [] def callback(**kwargs): out_dict = kwargs out_dict['dag'] = copy.deepcopy(kwargs['dag']) calls.append(out_dict) passmanager = PassManager() passmanager.append(Unroller(['u2'])) passmanager.append(Optimize1qGates()) passmanager.run(circuit, callback=callback) self.assertEqual(len(calls), 2) self.assertEqual(len(calls[0]), 5) self.assertEqual(calls[0]['count'], 0) self.assertEqual(calls[0]['pass_'].name(), 'Unroller') self.assertEqual(expected_start_dag, calls[0]['dag']) self.assertIsInstance(calls[0]['time'], float) self.assertEqual(calls[0]['property_set'], PropertySet()) self.assertEqual('MyCircuit', calls[0]['dag'].name) self.assertEqual(len(calls[1]), 5) self.assertEqual(calls[1]['count'], 1) self.assertEqual(calls[1]['pass_'].name(), 'Optimize1qGates') self.assertEqual(expected_end_dag, calls[1]['dag']) self.assertIsInstance(calls[0]['time'], float) self.assertEqual(calls[0]['property_set'], PropertySet()) self.assertEqual('MyCircuit', calls[1]['dag'].name)
def ampcal_1Q_circuits(max_reps, qubits): """ Generates circuit for measuring the amplitude error of the single qubit gates The U2 gate is repeatedly applied (in groups of 2) and we look at the population of the qubit in the xy axis (amplitude erorr amplification sequence) Y90-(Y90-Y90)^n 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 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(xdata): circ = qiskit.QuantumCircuit(qr, cr) circ.name = 'ampcal1Qcircuit_' + str(circ_index) + '_0' for qind, qubit in enumerate(qubits): circ.append(U2Gate(0.0, 0.0), [qr[qubit]]) for _ in range(circ_length): circ.barrier(qr[qubit]) circ.append(U2Gate(0.0, 0.0), [qr[qubit]]) for qind, qubit in enumerate(qubits): circ.measure(qr[qubit], cr[qind]) circuits.append(circ) return circuits, xdata
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_alap_resource_respecting(self): """Test that the ALAP pass properly respects busy resources when backwards scheduling. For instance, a CX on 0 and 1 followed by an X on only 1 must respect both qubits' timeline.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) sched = schedule(qc, self.backend, method="as_late_as_possible") insts = sched.instructions self.assertEqual(insts[0][0], 0) self.assertEqual(insts[6][0], 22) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.measure(q, c) sched = schedule(qc, self.backend, method="as_late_as_possible") self.assertEqual(sched.instructions[-1][0], 24)
def test_u_gates(self): """Test U 1, 2, & 3 gates""" qr = QuantumRegister(4, 'q') circuit = QuantumCircuit(qr) circuit.u1(3 * pi / 2, 0) circuit.u2(3 * pi / 2, 2 * pi / 3, 1) circuit.u3(3 * pi / 2, 4.5, pi / 4, 2) circuit.cu1(pi / 4, 0, 1) circuit.append(U2Gate(pi / 2, 3 * pi / 2).control(1), [qr[2], qr[3]]) circuit.cu3(3 * pi / 2, -3 * pi / 4, -pi / 2, 0, 1) self.circuit_drawer(circuit, filename='u_gates.png')
def test_consolidate_blocks_big(self): """Test ConsolidateBlocks with U2(<big numbers>) https://github.com/Qiskit/qiskit-terra/issues/3637#issuecomment-612954865 """ # ┌────────────────┐ ┌───┐ # q_0: ┤ U2(-804.15,pi) ├──■──┤ X ├ # ├────────────────┤┌─┴─┐└─┬─┘ # q_1: ┤ U2(-6433.2,pi) ├┤ X ├──■── # └────────────────┘└───┘ circuit = QuantumCircuit(2) circuit.append(U2Gate(-804.15, np.pi), [0]) circuit.append(U2Gate(-6433.2, np.pi), [1]) circuit.cx(0, 1) circuit.cx(1, 0) pass_manager = PassManager() pass_manager.append(Collect2qBlocks()) pass_manager.append(ConsolidateBlocks()) result = pass_manager.run(circuit) self.assertEqual(circuit, result)
def test_encoder_instruction(self): """Test encoding and decoding instructions""" subtests = ( { "instruction": CXGate() }, { "instruction": PhaseGate(theta=1) }, { "instruction": U2Gate(phi=1, lam=1) }, { "instruction": U2Gate(phi=Parameter("phi"), lam=Parameter("lambda")) }, ) for obj in subtests: encoded = json.dumps(obj, cls=RuntimeEncoder) self.assertIsInstance(encoded, str) decoded = json.loads(encoded, cls=RuntimeDecoder) self.assertEqual(decoded, obj)
def test_asap_pass(self): """Test ASAP scheduling.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(3.14, 1.57), [q[0]]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[0], q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) sched = schedule(qc, self.backend, method="as_soon_as_possible") # X pulse on q0 should start at t=0 expected = Schedule(self.inst_map.get('u2', [0], 3.14, 1.57), self.inst_map.get('u2', [1], 0.5, 0.25), (2, self.inst_map.get('u2', [1], 0.5, 0.25)), (4, self.inst_map.get('cx', [0, 1])), (26, self.inst_map.get('measure', [0, 1]))) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1])
def test_alap_pass(self): """Test ALAP scheduling.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(3.14, 1.57), [q[0]]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[0], [q[1]]) qc.cx(q[0], q[1]) qc.measure(q, c) sched = schedule(qc, self.backend) # X pulse on q0 should end at the start of the CNOT expected = Schedule((28, self.inst_map.get('u2', [0], 3.14, 1.57)), self.inst_map.get('u2', [1], 0.5, 0.25), (28, self.inst_map.get('u2', [1], 0.5, 0.25)), (56, self.inst_map.get('cx', [0, 1])), (78, self.inst_map.get('measure', [0, 1]))) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1])
def test_barriers_in_middle(self): """As a follow on to `test_can_add_gates_into_free_space`, similar issues arose for barriers, specifically. """ qr = QuantumRegister(2) qc = QuantumCircuit(qr) for i in range(2): qc.append(U2Gate(0, 0), [qr[i]]) qc.barrier(qr[i]) qc.append(U1Gate(3.14), [qr[i]]) qc.barrier(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), (28, self.inst_map.get('u1', [0], 3.14)), (28, self.inst_map.get('u1', [1], 3.14)), (28, self.inst_map.get('u2', [0], 0, 0)), (28, 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])