Esempio n. 1
0
    def test_probabilities_w(self):
        """Test probabilities method with W state"""

        state = (Statevector.from_label('001') + Statevector.from_label('010')
                 + Statevector.from_label('100')) / np.sqrt(3)

        # 3-qubit qargs
        target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0])
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities(qargs)
                self.assertTrue(np.allclose(probs, target))

        # 2-qubit qargs
        target = np.array([1 / 3, 1 / 3, 1 / 3, 0])
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities(qargs)
                self.assertTrue(np.allclose(probs, target))

        # 1-qubit qargs
        target = np.array([2 / 3, 1 / 3])
        for qargs in [[0], [1], [2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities(qargs)
                self.assertTrue(np.allclose(probs, target))
Esempio n. 2
0
    def test_sample_counts_w(self):
        """Test sample_counts method for W state"""
        shots = 3000
        threshold = 0.02 * shots
        state = (Statevector.from_label('001') + Statevector.from_label('010')
                 + Statevector.from_label('100')) / np.sqrt(3)
        state.seed(100)

        target = {'001': shots / 3, '010': shots / 3, '100': shots / 3}
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:

            with self.subTest(msg='P({})'.format(qargs)):
                counts = state.sample_counts(shots, qargs=qargs)
                self.assertDictAlmostEqual(counts, target, threshold)

        # 2-qubit qargs
        target = {'00': shots / 3, '01': shots / 3, '10': shots / 3}
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:

            with self.subTest(msg='P({})'.format(qargs)):
                counts = state.sample_counts(shots, qargs=qargs)
                self.assertDictAlmostEqual(counts, target, threshold)

        # 1-qubit qargs
        target = {'0': 2 * shots / 3, '1': shots / 3}
        for qargs in [[0], [1], [2]]:

            with self.subTest(msg='P({})'.format(qargs)):
                counts = state.sample_counts(shots, qargs=qargs)
                self.assertDictAlmostEqual(counts, target, threshold)
Esempio n. 3
0
    def test_sample_memory_w(self):
        """Test sample_memory method for W state"""
        shots = 3000
        state = (Statevector.from_label('001') + Statevector.from_label('010')
                 + Statevector.from_label('100')) / np.sqrt(3)
        state.seed(100)

        target = {'001': shots / 3, '010': shots / 3, '100': shots / 3}
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_memory(shots, qargs=qargs)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))

        # 2-qubit qargs
        target = {'00': shots / 3, '01': shots / 3, '10': shots / 3}
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_memory(shots, qargs=qargs)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))

        # 1-qubit qargs
        target = {'0': 2 * shots / 3, '1': shots / 3}
        for qargs in [[0], [1], [2]]:

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_memory(shots, qargs=qargs)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))
Esempio n. 4
0
    def test_probabilities_dict_w(self):
        """Test probabilities_dict method with W state"""

        state = (Statevector.from_label('001') + Statevector.from_label('010')
                 + Statevector.from_label('100')) / np.sqrt(3)

        # 3-qubit qargs
        target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0])
        target = {'001': 1 / 3, '010': 1 / 3, '100': 1 / 3}
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities_dict(qargs)
                self.assertDictAlmostEqual(probs, target)

        # 2-qubit qargs
        target = {'00': 1 / 3, '01': 1 / 3, '10': 1 / 3}
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities_dict(qargs)
                self.assertDictAlmostEqual(probs, target)

        # 1-qubit qargs
        target = {'0': 2 / 3, '1': 1 / 3}
        for qargs in [[0], [1], [2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities_dict(qargs)
                self.assertDictAlmostEqual(probs, target)
Esempio n. 5
0
    def test_probabilities_dict_ghz(self):
        """Test probabilities_dict method for GHZ state"""

        state = (Statevector.from_label('000') +
                 Statevector.from_label('111')) / np.sqrt(2)

        # 3-qubit qargs
        target = {'000': 0.5, '111': 0.5}
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities_dict(qargs)
                self.assertDictAlmostEqual(probs, target)

        # 2-qubit qargs
        target = {'00': 0.5, '11': 0.5}
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities_dict(qargs)
                self.assertDictAlmostEqual(probs, target)

        # 1-qubit qargs
        target = {'0': 0.5, '1': 0.5}
        for qargs in [[0], [1], [2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities_dict(qargs)
                self.assertDictAlmostEqual(probs, target)
    def test_sample_memory_ghz(self):
        """Test sample_memory method for GHZ state"""

        shots = 2000
        state = DensityMatrix(
            (Statevector.from_label('000') + Statevector.from_label('111')) /
            np.sqrt(2))
        state.seed(100)

        # 3-qubit qargs
        target = {'000': shots / 2, '111': shots / 2}
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_memory(shots, qargs=qargs)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))

        # 2-qubit qargs
        target = {'00': shots / 2, '11': shots / 2}
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_memory(shots, qargs=qargs)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))

        # 1-qubit qargs
        target = {'0': shots / 2, '1': shots / 2}
        for qargs in [[0], [1], [2]]:

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_memory(shots, qargs=qargs)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))
    def test_sample_counts_ghz(self):
        """Test sample_counts method for GHZ state"""

        shots = 2000
        threshold = 0.02 * shots
        state = DensityMatrix(
            (Statevector.from_label('000') + Statevector.from_label('111')) /
            np.sqrt(2))
        state.seed(100)

        # 3-qubit qargs
        target = {'000': shots / 2, '111': shots / 2}
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:

            with self.subTest(msg='counts (qargs={})'.format(qargs)):
                counts = state.sample_counts(shots, qargs=qargs)
                self.assertDictAlmostEqual(counts, target, threshold)

        # 2-qubit qargs
        target = {'00': shots / 2, '11': shots / 2}
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:

            with self.subTest(msg='counts (qargs={})'.format(qargs)):
                counts = state.sample_counts(shots, qargs=qargs)
                self.assertDictAlmostEqual(counts, target, threshold)

        # 1-qubit qargs
        target = {'0': shots / 2, '1': shots / 2}
        for qargs in [[0], [1], [2]]:

            with self.subTest(msg='counts (qargs={})'.format(qargs)):
                counts = state.sample_counts(shots, qargs=qargs)
                self.assertDictAlmostEqual(counts, target, threshold)
    def test_probabilities_ghz(self):
        """Test probabilities method for GHZ state"""

        psi = (Statevector.from_label('000') +
               Statevector.from_label('111')) / np.sqrt(2)
        state = DensityMatrix(psi)

        # 3-qubit qargs
        target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities(qargs)
                self.assertTrue(np.allclose(probs, target))

        # 2-qubit qargs
        target = np.array([0.5, 0, 0, 0.5])
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities(qargs)
                self.assertTrue(np.allclose(probs, target))

        # 1-qubit qargs
        target = np.array([0.5, 0.5])
        for qargs in [[0], [1], [2]]:
            with self.subTest(msg='P({})'.format(qargs)):
                probs = state.probabilities(qargs)
                self.assertTrue(np.allclose(probs, target))
Esempio n. 9
0
    def test_from_circuit(self):
        """Test initialization from a circuit."""
        # random unitaries
        u0 = random_unitary(2).data
        u1 = random_unitary(2).data
        # add to circuit
        qr = QuantumRegister(2)
        circ = QuantumCircuit(qr)
        circ.unitary(u0, [qr[0]])
        circ.unitary(u1, [qr[1]])
        target = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0]))
        vec = Statevector.from_instruction(circ)
        self.assertEqual(vec, target)

        # Test tensor product of 1-qubit gates
        circuit = QuantumCircuit(3)
        circuit.h(0)
        circuit.x(1)
        circuit.ry(np.pi / 2, 2)
        target = Statevector.from_label('000').evolve(Operator(circuit))
        psi = Statevector.from_instruction(circuit)
        self.assertEqual(psi, target)

        # Test decomposition of Controlled-Phase gate
        lam = np.pi / 4
        circuit = QuantumCircuit(2)
        circuit.h(0)
        circuit.h(1)
        circuit.cp(lam, 0, 1)
        target = Statevector.from_label('00').evolve(Operator(circuit))
        psi = Statevector.from_instruction(circuit)
        self.assertEqual(psi, target)

        # Test decomposition of controlled-H gate
        circuit = QuantumCircuit(2)
        circ.x(0)
        circuit.ch(0, 1)
        target = Statevector.from_label('00').evolve(Operator(circuit))
        psi = Statevector.from_instruction(circuit)
        self.assertEqual(psi, target)

        # Test initialize instruction
        target = Statevector([1, 0, 0, 1j]) / np.sqrt(2)
        circuit = QuantumCircuit(2)
        circuit.initialize(target.data, [0, 1])
        psi = Statevector.from_instruction(circuit)
        self.assertEqual(psi, target)

        # Test reset instruction
        target = Statevector([1, 0])
        circuit = QuantumCircuit(1)
        circuit.h(0)
        circuit.reset(0)
        psi = Statevector.from_instruction(circuit)
        self.assertEqual(psi, target)
Esempio n. 10
0
    def test_sample_measure_ghz(self):
        """Test sample measure method for GHZ state"""

        shots = 2000
        threshold = 0.02 * shots
        state = (Statevector.from_label('000') +
                 Statevector.from_label('111')) / np.sqrt(2)
        state.seed(100)

        # 3-qubit qargs
        target = {'000': shots / 2, '111': shots / 2}
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:

            with self.subTest(msg='counts (qargs={})'.format(qargs)):
                counts = state.sample_measure(qargs=qargs, shots=shots)
                self.assertDictAlmostEqual(counts, target, threshold)

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_measure(qargs=qargs,
                                              shots=shots,
                                              memory=True)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))

        # 2-qubit qargs
        target = {'00': shots / 2, '11': shots / 2}
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:

            with self.subTest(msg='counts (qargs={})'.format(qargs)):
                counts = state.sample_measure(qargs=qargs, shots=shots)
                self.assertDictAlmostEqual(counts, target, threshold)

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_measure(qargs=qargs,
                                              shots=shots,
                                              memory=True)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))

        # 1-qubit qargs
        target = {'0': shots / 2, '1': shots / 2}
        for qargs in [[0], [1], [2]]:

            with self.subTest(msg='counts (qargs={})'.format(qargs)):
                counts = state.sample_measure(qargs=qargs, shots=shots)
                self.assertDictAlmostEqual(counts, target, threshold)

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_measure(qargs=qargs,
                                              shots=shots,
                                              memory=True)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))
Esempio n. 11
0
    def test_sample_measure_w(self):
        """Test sample measure method for W state"""
        shots = 3000
        threshold = 0.02 * shots
        state = DensityMatrix(
            (Statevector.from_label('001') + Statevector.from_label('010') +
             Statevector.from_label('100')) / np.sqrt(3))
        state.seed(100)

        target = {'001': shots / 3, '010': shots / 3, '100': shots / 3}
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:

            with self.subTest(msg='P({})'.format(qargs)):
                counts = state.sample_measure(qargs=qargs, shots=shots)
                self.assertDictAlmostEqual(counts, target, threshold)

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_measure(qargs=qargs,
                                              shots=shots,
                                              memory=True)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))

        # 2-qubit qargs
        target = {'00': shots / 3, '01': shots / 3, '10': shots / 3}
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:

            with self.subTest(msg='P({})'.format(qargs)):
                counts = state.sample_measure(qargs=qargs, shots=shots)
                self.assertDictAlmostEqual(counts, target, threshold)

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_measure(qargs=qargs,
                                              shots=shots,
                                              memory=True)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))

        # 1-qubit qargs
        target = {'0': 2 * shots / 3, '1': shots / 3}
        for qargs in [[0], [1], [2]]:

            with self.subTest(msg='P({})'.format(qargs)):
                counts = state.sample_measure(qargs=qargs, shots=shots)
                self.assertDictAlmostEqual(counts, target, threshold)

            with self.subTest(msg='memory (qargs={})'.format(qargs)):
                memory = state.sample_measure(qargs=qargs,
                                              shots=shots,
                                              memory=True)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))
    def test_probabilities_dict_product(self):
        """Test probabilities_dict method for product state"""

        state = Statevector.from_label("+0")

        # 2-qubit qargs
        with self.subTest(msg="P(None)"):
            probs = state.probabilities_dict()
            target = {"00": 0.5, "10": 0.5}
            self.assertDictAlmostEqual(probs, target)

        with self.subTest(msg="P([0, 1])"):
            probs = state.probabilities_dict([0, 1])
            target = {"00": 0.5, "10": 0.5}
            self.assertDictAlmostEqual(probs, target)

        with self.subTest(msg="P([1, 0]"):
            probs = state.probabilities_dict([1, 0])
            target = {"00": 0.5, "01": 0.5}
            self.assertDictAlmostEqual(probs, target)

        # 1-qubit qargs
        with self.subTest(msg="P([0])"):
            probs = state.probabilities_dict([0])
            target = {"0": 1}
            self.assertDictAlmostEqual(probs, target)

        with self.subTest(msg="P([1])"):
            probs = state.probabilities_dict([1])
            target = {"0": 0.5, "1": 0.5}
            self.assertDictAlmostEqual(probs, target)
    def test_probabilities_product(self):
        """Test probabilities method for product state"""

        state = Statevector.from_label("+0")

        # 2-qubit qargs
        with self.subTest(msg="P(None)"):
            probs = state.probabilities()
            target = np.array([0.5, 0, 0.5, 0])
            self.assertTrue(np.allclose(probs, target))

        with self.subTest(msg="P([0, 1])"):
            probs = state.probabilities([0, 1])
            target = np.array([0.5, 0, 0.5, 0])
            self.assertTrue(np.allclose(probs, target))

        with self.subTest(msg="P([1, 0]"):
            probs = state.probabilities([1, 0])
            target = np.array([0.5, 0.5, 0, 0])
            self.assertTrue(np.allclose(probs, target))

        # 1-qubit qargs
        with self.subTest(msg="P([0])"):
            probs = state.probabilities([0])
            target = np.array([1, 0])
            self.assertTrue(np.allclose(probs, target))

        with self.subTest(msg="P([1])"):
            probs = state.probabilities([1])
            target = np.array([0.5, 0.5])
            self.assertTrue(np.allclose(probs, target))
Esempio n. 14
0
    def test_probabilities_dict_product(self):
        """Test probabilities_dict method for product state"""

        state = Statevector.from_label('+0')

        # 2-qubit qargs
        with self.subTest(msg='P(None)'):
            probs = state.probabilities_dict()
            target = {'00': 0.5, '10': 0.5}
            self.assertDictAlmostEqual(probs, target)

        with self.subTest(msg='P([0, 1])'):
            probs = state.probabilities_dict([0, 1])
            target = {'00': 0.5, '10': 0.5}
            self.assertDictAlmostEqual(probs, target)

        with self.subTest(msg='P([1, 0]'):
            probs = state.probabilities_dict([1, 0])
            target = {'00': 0.5, '01': 0.5}
            self.assertDictAlmostEqual(probs, target)

        # 1-qubit qargs
        with self.subTest(msg='P([0])'):
            probs = state.probabilities_dict([0])
            target = {'0': 1}
            self.assertDictAlmostEqual(probs, target)

        with self.subTest(msg='P([1])'):
            probs = state.probabilities_dict([1])
            target = {'0': 0.5, '1': 0.5}
            self.assertDictAlmostEqual(probs, target)
def save_expval_final_statevecs():
    """SaveExpectationValue test circuits pre meas statevecs"""
    # Get pre-measurement statevectors
    statevecs = []
    # State |+1>
    statevec = Statevector.from_label('+1')
    statevecs.append(statevec)
    # State |00> + |11>
    statevec = (Statevector.from_label('00') +
                Statevector.from_label('11')) / np.sqrt(2)
    statevecs.append(statevec)
    # State |10> -i|01>
    statevec = (Statevector.from_label('10') -
                1j * Statevector.from_label('01')) / np.sqrt(2)
    statevecs.append(statevec)
    return statevecs
    def test_from_label(self):
        """Test initialization from a label"""
        x_p = Statevector(np.array([1, 1]) / np.sqrt(2))
        x_m = Statevector(np.array([1, -1]) / np.sqrt(2))
        y_p = Statevector(np.array([1, 1j]) / np.sqrt(2))
        y_m = Statevector(np.array([1, -1j]) / np.sqrt(2))
        z_p = Statevector(np.array([1, 0]))
        z_m = Statevector(np.array([0, 1]))

        label = "01"
        target = z_p.tensor(z_m)
        self.assertEqual(target, Statevector.from_label(label))

        label = "+-"
        target = x_p.tensor(x_m)
        self.assertEqual(target, Statevector.from_label(label))

        label = "rl"
        target = y_p.tensor(y_m)
        self.assertEqual(target, Statevector.from_label(label))
Esempio n. 17
0
    def test_sample_memory_w(self):
        """Test sample_memory method for W state"""
        shots = 3000
        state = DensityMatrix(
            (
                Statevector.from_label("001")
                + Statevector.from_label("010")
                + Statevector.from_label("100")
            )
            / np.sqrt(3)
        )
        state.seed(100)

        target = {"001": shots / 3, "010": shots / 3, "100": shots / 3}
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:

            with self.subTest(msg=f"memory (qargs={qargs})"):
                memory = state.sample_memory(shots, qargs=qargs)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))

        # 2-qubit qargs
        target = {"00": shots / 3, "01": shots / 3, "10": shots / 3}
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:

            with self.subTest(msg=f"memory (qargs={qargs})"):
                memory = state.sample_memory(shots, qargs=qargs)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))

        # 1-qubit qargs
        target = {"0": 2 * shots / 3, "1": shots / 3}
        for qargs in [[0], [1], [2]]:

            with self.subTest(msg=f"memory (qargs={qargs})"):
                memory = state.sample_memory(shots, qargs=qargs)
                self.assertEqual(len(memory), shots)
                self.assertEqual(set(memory), set(target))
    def test_open_controlled_unitary_matrix(self, num_ctrl_qubits):
        """test open controlled unitary matrix"""
        # verify truth table
        num_target_qubits = 2
        num_qubits = num_ctrl_qubits + num_target_qubits
        target_op = Operator(XGate())
        for i in range(num_target_qubits - 1):
            target_op = target_op.tensor(XGate())

        for i in range(2**num_qubits):
            input_bitstring = bin(i)[2:].zfill(num_qubits)
            input_target = input_bitstring[0:num_target_qubits]
            input_ctrl = input_bitstring[-num_ctrl_qubits:]
            phi = Statevector.from_label(input_bitstring)
            cop = Operator(
                _compute_control_matrix(target_op.data,
                                        num_ctrl_qubits,
                                        ctrl_state=input_ctrl))
            for j in range(2**num_qubits):
                output_bitstring = bin(j)[2:].zfill(num_qubits)
                output_target = output_bitstring[0:num_target_qubits]
                output_ctrl = output_bitstring[-num_ctrl_qubits:]
                psi = Statevector.from_label(output_bitstring)
                cxout = np.dot(phi.data, psi.evolve(cop).data)
                if input_ctrl == output_ctrl:
                    # flip the target bits
                    cond_output = ''.join(
                        [str(int(not int(a))) for a in input_target])
                else:
                    cond_output = input_target
                if cxout == 1:
                    self.assertTrue((output_ctrl == input_ctrl)
                                    and (output_target == cond_output))
                else:
                    self.assertTrue(((output_ctrl == input_ctrl) and
                                     (output_target != cond_output))
                                    or output_ctrl != input_ctrl)
Esempio n. 19
0
    def test_sample_counts_w(self):
        """Test sample_counts method for W state"""
        shots = 3000
        threshold = 0.02 * shots
        state = DensityMatrix(
            (
                Statevector.from_label("001")
                + Statevector.from_label("010")
                + Statevector.from_label("100")
            )
            / np.sqrt(3)
        )
        state.seed(100)

        target = {"001": shots / 3, "010": shots / 3, "100": shots / 3}
        for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:

            with self.subTest(msg=f"P({qargs})"):
                counts = state.sample_counts(shots, qargs=qargs)
                self.assertDictAlmostEqual(counts, target, threshold)

        # 2-qubit qargs
        target = {"00": shots / 3, "01": shots / 3, "10": shots / 3}
        for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:

            with self.subTest(msg=f"P({qargs})"):
                counts = state.sample_counts(shots, qargs=qargs)
                self.assertDictAlmostEqual(counts, target, threshold)

        # 1-qubit qargs
        target = {"0": 2 * shots / 3, "1": shots / 3}
        for qargs in [[0], [1], [2]]:

            with self.subTest(msg=f"P({qargs})"):
                counts = state.sample_counts(shots, qargs=qargs)
                self.assertDictAlmostEqual(counts, target, threshold)
Esempio n. 20
0
 def test_statevector_partial_trace(self):
     """Test partial_trace function on statevectors"""
     psi = Statevector.from_label("10+")
     self.assertEqual(partial_trace(psi, [0, 1]),
                      DensityMatrix.from_label("1"))
     self.assertEqual(partial_trace(psi, [0, 2]),
                      DensityMatrix.from_label("0"))
     self.assertEqual(partial_trace(psi, [1, 2]),
                      DensityMatrix.from_label("+"))
     self.assertEqual(partial_trace(psi, [0]),
                      DensityMatrix.from_label("10"))
     self.assertEqual(partial_trace(psi, [1]),
                      DensityMatrix.from_label("1+"))
     self.assertEqual(partial_trace(psi, [2]),
                      DensityMatrix.from_label("0+"))
Esempio n. 21
0
 def test_statevector_partial_trace(self):
     """Test partial_trace function on statevectors"""
     psi = Statevector.from_label('10+')
     self.assertEqual(partial_trace(psi, [0, 1]),
                      DensityMatrix.from_label('1'))
     self.assertEqual(partial_trace(psi, [0, 2]),
                      DensityMatrix.from_label('0'))
     self.assertEqual(partial_trace(psi, [1, 2]),
                      DensityMatrix.from_label('+'))
     self.assertEqual(partial_trace(psi, [0]),
                      DensityMatrix.from_label('10'))
     self.assertEqual(partial_trace(psi, [1]),
                      DensityMatrix.from_label('1+'))
     self.assertEqual(partial_trace(psi, [2]),
                      DensityMatrix.from_label('0+'))
def save_expval_post_meas_values():
    """SaveExpectationValue test circuits reference final statevector"""
    targets = []
    for statevec in save_expval_final_statevecs():
        values = {}
        for label, (mat, qubits) in save_expval_params().items():
            inner_dict = {}
            for j in ['00', '01', '10', '11']:
                # Check if non-zero measurement probability for given
                # measurement outcome for final statevector
                vec = Statevector.from_label(j)
                if not np.isclose(vec.data.dot(statevec.data), 0):
                    # If outcome is non-zero compute expectation value
                    # with post-selected outcome state
                    inner_dict[hex(int(j, 2))] = vec.data.conj().dot(
                        vec.evolve(mat, qubits).data)
            values[label] = inner_dict
        targets.append(values)
    return targets
    def test_measure_2qubit(self):
        """Test measure method for 2-qubit state"""

        state = Statevector.from_label("+0")
        seed = 200
        shots = 100

        with self.subTest(msg="measure"):
            for i in range(shots):
                psi = state.copy()
                psi.seed(seed + i)
                outcome, value = psi.measure()
                self.assertIn(outcome, ["00", "10"])
                if outcome == "00":
                    target = Statevector.from_label("00")
                    self.assertEqual(value, target)
                else:
                    target = Statevector.from_label("10")
                    self.assertEqual(value, target)

        with self.subTest(msg="measure [0, 1]"):
            for i in range(shots):
                psi = state.copy()
                outcome, value = psi.measure([0, 1])
                self.assertIn(outcome, ["00", "10"])
                if outcome == "00":
                    target = Statevector.from_label("00")
                    self.assertEqual(value, target)
                else:
                    target = Statevector.from_label("10")
                    self.assertEqual(value, target)

        with self.subTest(msg="measure [1, 0]"):
            for i in range(shots):
                psi = state.copy()
                outcome, value = psi.measure([1, 0])
                self.assertIn(outcome, ["00", "01"])
                if outcome == "00":
                    target = Statevector.from_label("00")
                    self.assertEqual(value, target)
                else:
                    target = Statevector.from_label("10")
                    self.assertEqual(value, target)

        with self.subTest(msg="measure [0]"):
            for i in range(shots):
                psi = state.copy()
                outcome, value = psi.measure([0])
                self.assertEqual(outcome, "0")
                target = Statevector(np.array([1, 0, 1, 0]) / np.sqrt(2))
                self.assertEqual(value, target)

        with self.subTest(msg="measure [1]"):
            for i in range(shots):
                psi = state.copy()
                outcome, value = psi.measure([1])
                self.assertIn(outcome, ["0", "1"])
                if outcome == "0":
                    target = Statevector.from_label("00")
                    self.assertEqual(value, target)
                else:
                    target = Statevector.from_label("10")
                    self.assertEqual(value, target)
Esempio n. 24
0
    def test_measure_2qubit(self):
        """Test measure method for 2-qubit state"""

        state = Statevector.from_label('+0')
        seed = 200
        shots = 100

        with self.subTest(msg='measure'):
            for i in range(shots):
                psi = state.copy()
                psi.seed(seed + i)
                outcome, value = psi.measure()
                self.assertIn(outcome, ['00', '10'])
                if outcome == '00':
                    target = Statevector.from_label('00')
                    self.assertEqual(value, target)
                else:
                    target = Statevector.from_label('10')
                    self.assertEqual(value, target)

        with self.subTest(msg='measure [0, 1]'):
            for i in range(shots):
                psi = state.copy()
                outcome, value = psi.measure([0, 1])
                self.assertIn(outcome, ['00', '10'])
                if outcome == '00':
                    target = Statevector.from_label('00')
                    self.assertEqual(value, target)
                else:
                    target = Statevector.from_label('10')
                    self.assertEqual(value, target)

        with self.subTest(msg='measure [1, 0]'):
            for i in range(shots):
                psi = state.copy()
                outcome, value = psi.measure([1, 0])
                self.assertIn(outcome, ['00', '01'])
                if outcome == '00':
                    target = Statevector.from_label('00')
                    self.assertEqual(value, target)
                else:
                    target = Statevector.from_label('10')
                    self.assertEqual(value, target)

        with self.subTest(msg='measure [0]'):
            for i in range(shots):
                psi = state.copy()
                outcome, value = psi.measure([0])
                self.assertEqual(outcome, '0')
                target = Statevector(np.array([1, 0, 1, 0]) / np.sqrt(2))
                self.assertEqual(value, target)

        with self.subTest(msg='measure [1]'):
            for i in range(shots):
                psi = state.copy()
                outcome, value = psi.measure([1])
                self.assertIn(outcome, ['0', '1'])
                if outcome == '0':
                    target = Statevector.from_label('00')
                    self.assertEqual(value, target)
                else:
                    target = Statevector.from_label('10')
                    self.assertEqual(value, target)
Esempio n. 25
0
if __name__ == '__main__':
    import numpy as np
    from qiskit import Aer
    from qiskit.aqua.algorithms.minimum_eigen_solvers import VQSD
    from qiskit.quantum_info.states import Statevector
    from qiskit.aqua.components.initial_states import Custom
    from qiskit.aqua.components.optimizers import COBYLA
    from qiskit.aqua.operators import MatrixOperator
    from qiskit.aqua.algorithms.eigen_solvers import NumPyEigensolver
    from qiskit.aqua.components.variational_forms import RY
    from qiskit.quantum_info import partial_trace

    num_ancillae = 1
    state_vector = np.sqrt(6/10) * Statevector.from_label('+1+') \
        + np.sqrt(4/10) * Statevector.from_label('-0-')
    initial_state = Custom(state_vector.num_qubits,
                           state_vector=state_vector.data)
    vqsd_obj = VQSD(initial_state,
                    q=.25,
                    num_ancillae=num_ancillae,
                    quantum_instance=Aer.get_backend("qasm_simulator"),
                    optimizer=COBYLA(),
                    var_form=RY(initial_state._num_qubits - num_ancillae,
                                depth=2))
    result = vqsd_obj.run(shots=1000)

    print("=== VQSD ===")
    print(result.eigenvalue)
    print(result.eigenstate)

    print("== Exact ===")