def test_if_else_invalid_params_setter(self):
        """Verify we catch invalid param settings for IfElseOp."""
        condition = (Clbit(), True)
        true_body = QuantumCircuit(3, 1)
        false_body = QuantumCircuit(3, 1)

        op = IfElseOp(condition, true_body, false_body)

        with self.assertRaisesRegex(
                CircuitError, r"true_body parameter of type QuantumCircuit"):
            op.params = [XGate(), None]

        with self.assertRaisesRegex(
                CircuitError, r"false_body parameter of type QuantumCircuit"):
            op.params = [true_body, XGate()]

        bad_body = QuantumCircuit(4, 2)

        with self.assertRaisesRegex(
                CircuitError,
                r"num_clbits different than that of the IfElseOp"):
            op.params = [true_body, bad_body]

        with self.assertRaisesRegex(
                CircuitError,
                r"num_clbits different than that of the IfElseOp"):
            op.params = [bad_body, false_body]

        with self.assertRaisesRegex(
                CircuitError,
                r"num_clbits different than that of the IfElseOp"):
            op.params = [bad_body, bad_body]
    def test_if_else_invalid_instantiation(self):
        """Verify we catch invalid instantiations of IfElseOp."""
        condition = (Clbit(), True)
        true_body = QuantumCircuit(3, 1)
        false_body = QuantumCircuit(3, 1)

        with self.assertRaisesRegex(
                CircuitError, r"A classical condition should be a 2-tuple"):
            _ = IfElseOp(1, true_body, false_body)

        with self.assertRaisesRegex(
                CircuitError, r"A classical condition should be a 2-tuple"):
            _ = IfElseOp((1, 2), true_body, false_body)

        with self.assertRaisesRegex(
                CircuitError, r"true_body parameter of type QuantumCircuit"):
            _ = IfElseOp(condition, XGate())

        with self.assertRaisesRegex(
                CircuitError, r"false_body parameter of type QuantumCircuit"):
            _ = IfElseOp(condition, true_body, XGate())

        bad_body = QuantumCircuit(4, 2)

        with self.assertRaisesRegex(
                CircuitError,
                r"num_clbits different than that of the IfElseOp"):
            _ = IfElseOp(condition, true_body, bad_body)
 def test_inverse_x(self, num_ctrl_qubits):
     """Test inverting the controlled X gate."""
     cnx = XGate().control(num_ctrl_qubits)
     inv_cnx = cnx.inverse()
     result = Operator(cnx).compose(Operator(inv_cnx))
     np.testing.assert_array_almost_equal(result.data,
                                          np.identity(result.dim[0]))
Beispiel #4
0
    def test_mcmt_label(self, mcmt_class):
        """Test MCMT label remains functional but is deprecated."""
        custom_label = "abc"
        with self.subTest(msg="init with label and get"):
            with self.assertWarns(DeprecationWarning):
                mcmt = mcmt_class(
                    XGate(), num_ctrl_qubits=1, num_target_qubits=1, label=custom_label
                )
            with self.assertWarns(DeprecationWarning):
                self.assertEqual(mcmt.label, custom_label)

        with self.subTest(msg="label set and get"):
            mcmt = mcmt_class(XGate(), num_ctrl_qubits=1, num_target_qubits=1)
            with self.assertWarns(DeprecationWarning):
                mcmt.label = custom_label
            with self.assertWarns(DeprecationWarning):
                self.assertEqual(mcmt.label, custom_label)

        with self.subTest(msg="control gate label"):
            mcmt = mcmt_class(XGate(), num_ctrl_qubits=1, num_target_qubits=1)
            c_mcmt = mcmt.control()
            with self.assertWarns(DeprecationWarning):
                c_mcmt = mcmt.control(label=custom_label)
            with self.assertWarns(DeprecationWarning):
                self.assertEqual(c_mcmt.label, custom_label)
    def test_dd_with_calibrations_with_parameters(self, param_value):
        """Check that calibrations in a circuit with parameters work fine."""

        circ = QuantumCircuit(2)
        circ.x(0)
        circ.cx(0, 1)
        circ.rx(param_value, 1)

        rx_duration = int(param_value * 1000)

        with pulse.build() as rx:
            pulse.play(pulse.Gaussian(rx_duration, 0.1, rx_duration // 4),
                       pulse.DriveChannel(1))

        circ.add_calibration("rx", (1, ), rx, params=[param_value])

        durations = InstructionDurations([("x", None, 100), ("cx", None, 300)])

        dd_sequence = [XGate(), XGate()]
        pm = PassManager([
            ALAPScheduleAnalysis(durations),
            PadDynamicalDecoupling(durations, dd_sequence)
        ])

        self.assertEqual(pm.run(circ).duration, rx_duration + 100 + 300)
Beispiel #6
0
 def test_different_gate_types(self):
     """Test the different supported input types for the target gate."""
     x_circ = QuantumCircuit(1)
     x_circ.x(0)
     for input_gate in [x_circ, QuantumCircuit.cx, QuantumCircuit.x, "cx", "x", CXGate()]:
         with self.subTest(input_gate=input_gate):
             mcmt = MCMT(input_gate, 2, 2)
             if isinstance(input_gate, QuantumCircuit):
                 self.assertEqual(mcmt.gate.definition[0][0], XGate())
                 self.assertEqual(len(mcmt.gate.definition), 1)
             else:
                 self.assertEqual(mcmt.gate, XGate())
 def test_standard_gate_with_label(self):
     """Test a standard gate with a label."""
     qc = QuantumCircuit(1)
     gate = XGate()
     gate.label = "My special X gate"
     qc.append(gate, [0])
     qpy_file = io.BytesIO()
     dump(qc, qpy_file)
     qpy_file.seek(0)
     new_circ = load(qpy_file)[0]
     self.assertEqual(qc, new_circ)
     self.assertEqual([x[0].label for x in qc.data], [x[0].label for x in new_circ.data])
    def test_caching_different_qubit_sets(self):
        """Check that hashing same commutativity results over different qubit sets works as expected."""

        comm_checker = CommutationChecker()

        # All the following should be cached in the same way
        # though each relation gets cached twice: (A, B) and (B, A)
        comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
        comm_checker.commute(XGate(), [10], [], CXGate(), [10, 20], [])
        comm_checker.commute(XGate(), [10], [], CXGate(), [10, 5], [])
        comm_checker.commute(XGate(), [5], [], CXGate(), [5, 7], [])
        self.assertEqual(len(comm_checker.cache), 2)
 def test_circuit_with_conditional_with_label(self):
     """Test that instructions with conditions are correctly serialized."""
     qc = QuantumCircuit(1, 1)
     gate = XGate(label="My conditional x gate")
     gate.c_if(qc.cregs[0], 1)
     qc.append(gate, [0])
     qpy_file = io.BytesIO()
     dump(qc, qpy_file)
     qpy_file.seek(0)
     new_circ = load(qpy_file)[0]
     self.assertEqual(qc, new_circ)
     self.assertEqual([x[0].label for x in qc.data], [x[0].label for x in new_circ.data])
Beispiel #10
0
    def test_insert_dd_ghz_one_qubit(self):
        """Test DD gates are inserted on only one qubit.

                      ┌───┐            ┌────────────────┐      ┌───┐       »
           q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├───────»
                ┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴──────┐»
           q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(300[dt]) ├»
                ├───────────────┴┐└───┘      ┌─┴─┐       └────────────────┘»
           q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■─────────»
                ├────────────────┤           └───┘             ┌─┴─┐       »
           q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├───────»
                └────────────────┘                             └───┘       »
        meas: 4/═══════════════════════════════════════════════════════════»
                                                                           »
        «        ┌────────────────┐┌───┐┌────────────────┐ ░ ┌─┐
        «   q_0: ┤ Delay(200[dt]) ├┤ X ├┤ Delay(100[dt]) ├─░─┤M├─────────
        «        └────────────────┘└───┘└────────────────┘ ░ └╥┘┌─┐
        «   q_1: ──────────────────────────────────────────░──╫─┤M├──────
        «                                                  ░  ║ └╥┘┌─┐
        «   q_2: ──────────────────────────────────────────░──╫──╫─┤M├───
        «                                                  ░  ║  ║ └╥┘┌─┐
        «   q_3: ──────────────────────────────────────────░──╫──╫──╫─┤M├
        «                                                  ░  ║  ║  ║ └╥┘
        «meas: 4/═════════════════════════════════════════════╩══╩══╩══╩═
        «                                                     0  1  2  3
        """
        dd_sequence = [XGate(), XGate()]
        pm = PassManager(
            [
                ALAPSchedule(self.durations),
                DynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
            ]
        )

        ghz4_dd = pm.run(self.ghz4.measure_all(inplace=False))

        expected = self.ghz4.copy()
        expected = expected.compose(Delay(50), [1], front=True)
        expected = expected.compose(Delay(750), [2], front=True)
        expected = expected.compose(Delay(950), [3], front=True)

        expected = expected.compose(Delay(100), [0])
        expected = expected.compose(XGate(), [0])
        expected = expected.compose(Delay(200), [0])
        expected = expected.compose(XGate(), [0])
        expected = expected.compose(Delay(100), [0])

        expected = expected.compose(Delay(300), [1])

        expected.measure_all()

        self.assertEqual(ghz4_dd, expected)
    def test_insert_midmeas_hahn_alap(self):
        """Test a single X gate as Hahn echo can absorb in the downstream circuit.

        global phase: 3π/2
                               ┌────────────────┐       ┌───┐       ┌────────────────┐»
        q_0: ────────■─────────┤ Delay(625[dt]) ├───────┤ X ├───────┤ Delay(625[dt]) ├»
                   ┌─┴─┐       └────────────────┘┌──────┴───┴──────┐└────────────────┘»
        q_1: ──────┤ X ├───────────────■─────────┤ Delay(1000[dt]) ├────────■─────────»
             ┌─────┴───┴──────┐      ┌─┴─┐       └───────┬─┬───────┘      ┌─┴─┐       »
        q_2: ┤ Delay(700[dt]) ├──────┤ X ├───────────────┤M├──────────────┤ X ├───────»
             └────────────────┘      └───┘               └╥┘              └───┘       »
        c: 1/═════════════════════════════════════════════╩═══════════════════════════»
                                                          0                           »
        «     ┌───────────────┐
        «q_0: ┤ U(0,π/2,-π/2) ├───■──
        «     └───────────────┘ ┌─┴─┐
        «q_1: ──────────────────┤ X ├
        «     ┌────────────────┐└───┘
        «q_2: ┤ Delay(700[dt]) ├─────
        «     └────────────────┘
        «c: 1/═══════════════════════
        """
        dd_sequence = [XGate()]
        pm = PassManager([
            ALAPScheduleAnalysis(self.durations),
            PadDynamicalDecoupling(self.durations, dd_sequence),
        ])

        midmeas_dd = pm.run(self.midmeas)

        combined_u = UGate(0, pi / 2, -pi / 2)

        expected = QuantumCircuit(3, 1)
        expected.cx(0, 1)
        expected.delay(625, 0)
        expected.x(0)
        expected.delay(625, 0)
        expected.compose(combined_u, [0], inplace=True)
        expected.delay(700, 2)
        expected.cx(1, 2)
        expected.delay(1000, 1)
        expected.measure(2, 0)
        expected.cx(1, 2)
        expected.cx(0, 1)
        expected.delay(700, 2)
        expected.global_phase = 4.71238898038469

        self.assertEqual(midmeas_dd, expected)
        # check the absorption into U was done correctly
        self.assertEqual(Operator(combined_u),
                         Operator(XGate()) & Operator(XGate()))
    def test_open_controlled_gate(self):
        """
        Test controlled gates with control on '0'
        """
        base_gate = XGate()
        base_mat = base_gate.to_matrix()
        num_ctrl_qubits = 3

        ctrl_state = 5
        cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
        target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state)
        self.assertEqual(Operator(cgate), Operator(target_mat))

        ctrl_state = None
        cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
        target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state)
        self.assertEqual(Operator(cgate), Operator(target_mat))

        ctrl_state = 0
        cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
        target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state)
        self.assertEqual(Operator(cgate), Operator(target_mat))

        ctrl_state = 7
        cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
        target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state)
        self.assertEqual(Operator(cgate), Operator(target_mat))

        ctrl_state = '110'
        cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
        target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state)
        self.assertEqual(Operator(cgate), Operator(target_mat))
    def test_gates_with_parameters(self):
        """Check commutativity between (non-parameterized) gates with parameters."""

        comm_checker = CommutationChecker()
        res = comm_checker.commute(RZGate(0), [0], [], XGate(), [0], [])
        self.assertTrue(res)

        res = comm_checker.commute(RZGate(np.pi / 2), [0], [], XGate(), [0],
                                   [])
        self.assertFalse(res)

        res = comm_checker.commute(RZGate(np.pi / 2), [0], [], RZGate(0), [0],
                                   [])
        self.assertTrue(res)
Beispiel #14
0
 def test_instructions(self):
     self.assertEqual(self.empty_target.instructions, [])
     ibm_expected = [
         (IGate(), (0, )),
         (IGate(), (1, )),
         (IGate(), (2, )),
         (IGate(), (3, )),
         (IGate(), (4, )),
         (RZGate(self.theta), (0, )),
         (RZGate(self.theta), (1, )),
         (RZGate(self.theta), (2, )),
         (RZGate(self.theta), (3, )),
         (RZGate(self.theta), (4, )),
         (SXGate(), (0, )),
         (SXGate(), (1, )),
         (SXGate(), (2, )),
         (SXGate(), (3, )),
         (SXGate(), (4, )),
         (XGate(), (0, )),
         (XGate(), (1, )),
         (XGate(), (2, )),
         (XGate(), (3, )),
         (XGate(), (4, )),
         (CXGate(), (3, 4)),
         (CXGate(), (4, 3)),
         (CXGate(), (3, 1)),
         (CXGate(), (1, 3)),
         (CXGate(), (1, 2)),
         (CXGate(), (2, 1)),
         (CXGate(), (0, 1)),
         (CXGate(), (1, 0)),
         (Measure(), (0, )),
         (Measure(), (1, )),
         (Measure(), (2, )),
         (Measure(), (3, )),
         (Measure(), (4, )),
     ]
     self.assertEqual(ibm_expected, self.ibm_target.instructions)
     ideal_sim_expected = [
         (UGate(self.theta, self.phi, self.lam), None),
         (RXGate(self.theta), None),
         (RYGate(self.theta), None),
         (RZGate(self.theta), None),
         (CXGate(), None),
         (ECRGate(), None),
         (CCXGate(), None),
         (Measure(), None),
     ]
     self.assertEqual(ideal_sim_expected,
                      self.ideal_sim_target.instructions)
    def test_is_identity(self):
        """The is_identity function determines whether a pair of gates
        forms the identity, when ignoring control qubits.
        """
        seq = [DAGOpNode(op=XGate().control()), DAGOpNode(op=XGate().control(2))]
        self.assertTrue(HoareOptimizer()._is_identity(seq))

        seq = [
            DAGOpNode(op=RZGate(-pi / 2).control()),
            DAGOpNode(op=RZGate(pi / 2).control(2)),
        ]
        self.assertTrue(HoareOptimizer()._is_identity(seq))

        seq = [DAGOpNode(op=CSwapGate()), DAGOpNode(op=SwapGate())]
        self.assertTrue(HoareOptimizer()._is_identity(seq))
    def test_is_identity(self):
        """ The is_identity function determines whether a pair of gates
            forms the identity, when ignoring control qubits.
        """
        seq = [DAGNode({'type': 'op', 'op': XGate().control()}),
               DAGNode({'type': 'op', 'op': XGate().control(2)})]
        self.assertTrue(HoareOptimizer()._is_identity(seq))

        seq = [DAGNode({'type': 'op', 'op': RZGate(-pi/2).control()}),
               DAGNode({'type': 'op', 'op': RZGate(pi/2).control(2)})]
        self.assertTrue(HoareOptimizer()._is_identity(seq))

        seq = [DAGNode({'type': 'op', 'op': CSwapGate()}),
               DAGNode({'type': 'op', 'op': SwapGate()})]
        self.assertTrue(HoareOptimizer()._is_identity(seq))
    def test_multi_control_toffoli_matrix_advanced_dirty_ancillas(
            self, num_controls):
        """Test the multi-control Toffoli gate with dirty ancillas (advanced).

        Based on the test moved here from Aqua:
        https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py
        """
        q_controls = QuantumRegister(num_controls)
        q_target = QuantumRegister(1)
        qc = QuantumCircuit(q_controls, q_target)

        q_ancillas = None
        if num_controls <= 4:
            num_ancillas = 0
        else:
            num_ancillas = 1
            q_ancillas = QuantumRegister(num_ancillas)
            qc.add_register(q_ancillas)

        qc.mct(q_controls, q_target[0], q_ancillas, mode='advanced')

        simulated = execute(
            qc,
            BasicAer.get_backend('unitary_simulator')).result().get_unitary(qc)
        if num_ancillas > 0:
            simulated = simulated[:2**(num_controls + 1), :2**(num_controls +
                                                               1)]

        base = XGate().to_matrix()
        expected = _compute_control_matrix(base, num_controls)
        self.assertTrue(matrix_equal(simulated, expected, atol=1e-8))
Beispiel #18
0
 def _load_rb_data(self, rb_exp_data_file_name: str):
     """
     loader for the experiment data and configuration setup.
     Args:
         rb_exp_data_file_name(str): The file name that contain the experiment data.
     Returns:
         list: containing dict of the experiment setup configuration and list of dictionaries
             containing the experiment results.
         ExperimentData:  ExperimentData object that was creates by the analysis function.
     """
     interleaved_gates = {"x": XGate(), "cx": CXGate()}
     data, exp_attributes, expdata1 = self._load_json_data(
         rb_exp_data_file_name)
     rb_exp = InterleavedRB(
         interleaved_gates[exp_attributes["interleaved_element"]],
         exp_attributes["physical_qubits"],
         exp_attributes["lengths"],
         num_samples=exp_attributes["num_samples"],
         seed=exp_attributes["seed"],
     )
     gate_error_ratio = {
         ((0, ), "id"): 1,
         ((0, ), "rz"): 0,
         ((0, ), "sx"): 1,
         ((0, ), "x"): 1,
         ((0, 1), "cx"): 1,
     }
     rb_exp.analysis.set_options(gate_error_ratio=gate_error_ratio)
     analysis_results = rb_exp.analysis.run(expdata1).block_for_results()
     return data, analysis_results
 def __init__(self):
     # |0> Zp rotation
     prep_zp = QuantumCircuit(1, name="PauliPrepZp")
     # |1> Zm rotation
     prep_zm = QuantumCircuit(1, name="PauliPrepZm")
     prep_zm.append(XGate(), [0])
     # |+> Xp rotation
     prep_xp = QuantumCircuit(1, name="PauliPrepXp")
     prep_xp.append(HGate(), [0])
     # |-> Xm rotation
     prep_xm = QuantumCircuit(1, name="PauliPrepXm")
     prep_xm.append(HGate(), [0])
     prep_xm.append(ZGate(), [0])
     # |+i> Yp rotation
     prep_yp = QuantumCircuit(1, name="PauliPrepYp")
     prep_yp.append(HGate(), [0])
     prep_yp.append(SGate(), [0])
     # |-i> Ym rotation
     prep_ym = QuantumCircuit(1, name="PauliPrepYm")
     prep_ym.append(HGate(), [0])
     prep_ym.append(SdgGate(), [0])
     super().__init__(
         [
             prep_zp,
             prep_zm,
             prep_xp,
             prep_xm,
             prep_yp,
             prep_ym,
         ]
     )
    def test_caching_negative_results(self):
        """Check that hashing negative results in commutativity checker works as expected."""

        comm_checker = CommutationChecker()
        res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], [])
        self.assertFalse(res)
        self.assertGreater(len(comm_checker.cache), 0)
Beispiel #21
0
    def test_initial_state_as_circuit_object(self):
        """Test setting `initial_state` to `QuantumCircuit` object"""
        #           ┌───┐          ┌───┐
        # q_0: ──■──┤ X ├───────■──┤ X ├
        #      ┌─┴─┐├───┤┌───┐┌─┴─┐├───┤
        # q_1: ┤ X ├┤ H ├┤ X ├┤ X ├┤ X ├
        #      └───┘└───┘└───┘└───┘└───┘
        ref = QuantumCircuit(2)
        ref.cx(0, 1)
        ref.x(0)
        ref.h(1)
        ref.x(1)
        ref.cx(0, 1)
        ref.x(0)
        ref.x(1)

        qc = QuantumCircuit(2)
        qc.cx(0, 1)
        qc.h(1)

        expected = NLocal(
            num_qubits=2,
            rotation_blocks=XGate(),
            entanglement_blocks=CXGate(),
            initial_state=qc,
            reps=1,
        )

        self.assertCircuitEqual(ref, expected)
    def test_relative_phase_toffoli_gates(self, num_ctrl_qubits):
        """Test the relative phase Toffoli gates.

        This test compares the matrix representation of the relative phase gate classes
        (i.e. RCCXGate().to_matrix()), the matrix obtained from the unitary simulator,
        and the exact version of the gate as obtained through `_compute_control_matrix`.
        """
        # get target matrix (w/o relative phase)
        base_mat = XGate().to_matrix()
        target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits)

        # build the matrix for the relative phase toffoli using the unitary simulator
        circuit = QuantumCircuit(num_ctrl_qubits + 1)
        if num_ctrl_qubits == 2:
            circuit.rccx(0, 1, 2)
        else:  # num_ctrl_qubits == 3:
            circuit.rcccx(0, 1, 2, 3)
        simulator = BasicAer.get_backend('unitary_simulator')
        simulated_mat = execute(circuit, simulator).result().get_unitary()

        # get the matrix representation from the class itself
        if num_ctrl_qubits == 2:
            repr_mat = RCCXGate().to_matrix()
        else:  # num_ctrl_qubits == 3:
            repr_mat = RC3XGate().to_matrix()

        # test up to phase
        # note, that all entries may have an individual phase! (as opposed to a global phase)
        self.assertTrue(matrix_equal(np.abs(simulated_mat), target_mat))

        # compare simulated matrix with the matrix representation provided by the class
        self.assertTrue(matrix_equal(simulated_mat, repr_mat))
Beispiel #23
0
    def test_entanglement_by_str(self, entanglement):
        """Test setting the entanglement of the layers by str."""
        reps = 3
        nlocal = NLocal(5, rotation_blocks=XGate(), entanglement_blocks=CCXGate(),
                        entanglement=entanglement, reps=reps)

        def get_expected_entangler_map(rep_num, mode):
            if mode == 'linear':
                return [(0, 1, 2), (1, 2, 3), (2, 3, 4)]
            elif mode == 'full':
                return [(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4),
                        (1, 2, 3), (1, 2, 4), (1, 3, 4),
                        (2, 3, 4)]
            else:
                circular = [(3, 4, 0), (0, 1, 2), (1, 2, 3), (2, 3, 4)]
                if mode == 'circular':
                    return circular
                sca = circular[-rep_num:] + circular[:-rep_num]
                if rep_num % 2 == 1:
                    sca = [tuple(reversed(indices)) for indices in sca]
                return sca

        for rep_num in range(reps):
            entangler_map = nlocal.get_entangler_map(rep_num, 0, 3)
            if isinstance(entanglement, list):
                mode = entanglement[rep_num % len(entanglement)]
            else:
                mode = entanglement
            expected = get_expected_entangler_map(rep_num, mode)

            with self.subTest(rep_num=rep_num):
                # using a set here since the order does not matter
                self.assertEqual(set(entangler_map), set(expected))
Beispiel #24
0
 def test_get_instructions_for_qargs(self):
     with self.assertRaises(KeyError):
         self.empty_target.operations_for_qargs((0, ))
     expected = [RZGate(self.theta), IGate(), SXGate(), XGate(), Measure()]
     res = self.ibm_target.operations_for_qargs((0, ))
     for gate in expected:
         self.assertIn(gate, res)
     expected = [ECRGate()]
     res = self.fake_backend_target.operations_for_qargs((1, 0))
     for gate in expected:
         self.assertIn(gate, res)
     expected = [CXGate()]
     res = self.fake_backend_target.operations_for_qargs((0, 1))
     self.assertEqual(expected, res)
     ideal_sim_expected = [
         UGate(self.theta, self.phi, self.lam),
         RXGate(self.theta),
         RYGate(self.theta),
         RZGate(self.theta),
         CXGate(),
         ECRGate(),
         CCXGate(),
         Measure(),
     ]
     for gate in ideal_sim_expected:
         self.assertIn(gate,
                       self.ideal_sim_target.operations_for_qargs(None))
Beispiel #25
0
    def test_skip_unentangled_qubits(self):
        """Test skipping the unentangled qubits."""
        num_qubits = 6
        entanglement_1 = [[0, 1, 3], [1, 3, 5], [0, 1, 5]]
        skipped_1 = [2, 4]

        entanglement_2 = [entanglement_1, [[0, 1, 2], [2, 3, 5]]]
        skipped_2 = [4]

        for entanglement, skipped in zip([entanglement_1, entanglement_2],
                                         [skipped_1, skipped_2]):
            with self.subTest(entanglement=entanglement, skipped=skipped):
                nlocal = NLocal(
                    num_qubits,
                    rotation_blocks=XGate(),
                    entanglement_blocks=CCXGate(),
                    entanglement=entanglement,
                    reps=3,
                    skip_unentangled_qubits=True,
                )

                skipped_set = set(nlocal.qubits[i] for i in skipped)
                dag = circuit_to_dag(nlocal)
                idle = set(dag.idle_wires())
                self.assertEqual(skipped_set, idle)
Beispiel #26
0
def Agate(numLis, inverse=False, plot_gate=False):
    if len(numLis) != 6:
        raise Exception("Parameter Lis error!")
    qr = QuantumRegister(2)
    qc = QuantumCircuit(qr)
    qc.cz(qr[0], qr[1])
    qc.rx(numLis[0], qr[1])
    sqrtXdg = XGate().power(0.5).inverse()
    qc.append(sqrtXdg, qargs=[qr[1]])

    qc.append(myRzz(numLis[1]).control(), qargs=qr[:])
    if plot_gate:
        qc.barrier()
    qc.rx(numLis[2], qr[0])
    qc.append(myRzz(numLis[3]).control(), qargs=[qr[1]] + [qr[0]])
    qc.cx(qr[0], qr[1])
    qc.rx(numLis[4], qr[0])
    qc.cx(qr[0], qr[1])
    qc.cz(qr[0], qr[1])
    #print(qc)
    if plot_gate:
        print(qc)
        return
    ret = qc.to_gate()
    if inverse:
        ret.inverse()
    ret.name = f'gate_1/{numLis[5]}'
    return ret
    def test_multi_control_toffoli_matrix_clean_ancillas(self, num_controls):
        """Test the multi-control Toffoli gate with clean ancillas.

        Based on the test moved here from Aqua:
        https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py
        """
        # set up circuit
        q_controls = QuantumRegister(num_controls)
        q_target = QuantumRegister(1)
        qc = QuantumCircuit(q_controls, q_target)

        if num_controls > 2:
            num_ancillas = num_controls - 2
            q_ancillas = QuantumRegister(num_controls)
            qc.add_register(q_ancillas)
        else:
            num_ancillas = 0
            q_ancillas = None

        # apply hadamard on control qubits and toffoli gate
        qc.mct(q_controls, q_target[0], q_ancillas, mode='basic')

        # execute the circuit and obtain statevector result
        backend = BasicAer.get_backend('unitary_simulator')
        simulated = execute(qc, backend).result().get_unitary(qc)

        # compare to expectation
        if num_ancillas > 0:
            simulated = simulated[:2**(num_controls + 1), :2**(num_controls +
                                                               1)]

        base = XGate().to_matrix()
        expected = _compute_control_matrix(base, num_controls)
        self.assertTrue(matrix_equal(simulated, expected))
Beispiel #28
0
    def test_can_append_to_quantum_circuit(self):
        """Test that we can add various objects with Operation interface to a Quantum Circuit."""
        qc = QuantumCircuit(6, 1)
        qc.append(XGate(), [2])
        qc.append(Barrier(3), [1, 2, 4])
        qc.append(CXGate(), [0, 1])
        qc.append(Measure(), [1], [0])
        qc.append(Reset(), [0])
        qc.cx(3, 4)
        qc.append(Gate("some_gate", 3, []), [1, 2, 3])
        qc.append(Initialize([0.5, 0.5, 0.5, 0.5]), [4, 5])
        qc.append(Isometry(np.eye(4, 4), 0, 0), [3, 4])
        qc.append(Pauli("II"), [0, 1])

        # Appending Clifford
        circ1 = QuantumCircuit(2)
        circ1.h(1)
        circ1.cx(0, 1)
        qc.append(Clifford(circ1), [0, 1])

        # Appending CNOTDihedral
        circ2 = QuantumCircuit(2)
        circ2.t(0)
        circ2.x(0)
        circ2.t(1)
        qc.append(CNOTDihedral(circ2), [2, 3])

        # If we got to here, we have successfully appended everything to qc
        self.assertIsInstance(qc, QuantumCircuit)
Beispiel #29
0
    def test_pairwise_entanglement_raises(self):
        """Test choosing pairwise entanglement raises an error for too large blocks."""
        nlocal = NLocal(3, XGate(), CCXGate(), entanglement='pairwise', reps=1)

        # pairwise entanglement is only defined if the entangling gate has 2 qubits
        with self.assertRaises(ValueError):
            print(nlocal.draw())
Beispiel #30
0
    def to_circuit(self) -> QuantumCircuit:

        pauli = self.primitive.to_label()[-self.num_qubits:]
        phase = self.primitive.phase

        qc = QuantumCircuit(self.num_qubits)
        if pauli == "I" * self.num_qubits:
            qc.global_phase = -phase * pi / 2
            return qc

        if self.num_qubits == 1:
            gate = {
                "I": IGate(),
                "X": XGate(),
                "Y": YGate(),
                "Z": ZGate()
            }[pauli]
        else:
            gate = PauliGate(pauli)
        qc.append(gate, range(self.num_qubits))

        if not phase:
            return qc

        qc.global_phase = -phase * pi / 2
        return qc