def test_adjoint(self):
     """ adjoint test """
     gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + \
         PrimitiveOp(Operator.from_label('+r0IX').data)
     np.testing.assert_array_almost_equal(
         np.conj(np.transpose(gnarly_op.to_matrix())),
         gnarly_op.adjoint().to_matrix())
Esempio n. 2
0
    def test_reuse(self):
        """Test re-using a VQE algorithm instance."""
        vqe = VQE()
        with self.subTest(msg='assert running empty raises AlgorithmError'):
            with self.assertRaises(AlgorithmError):
                _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op)

        var_form = TwoLocal(rotation_blocks=['ry', 'rz'],
                            entanglement_blocks='cz')
        vqe.var_form = var_form
        with self.subTest(msg='assert missing operator raises AlgorithmError'):
            with self.assertRaises(AlgorithmError):
                _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op)

        vqe.quantum_instance = self.statevector_simulator
        with self.subTest(msg='assert VQE works once all info is available'):
            result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
            self.assertAlmostEqual(result.eigenvalue.real,
                                   self.h2_energy,
                                   places=5)

        operator = PrimitiveOp(
            np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0,
                                                                  3]]))

        with self.subTest(msg='assert minimum eigensolver interface works'):
            result = vqe.compute_minimum_eigenvalue(operator=operator)
            self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
Esempio n. 3
0
    def test_reuse(self):
        """Test re-using a VQE algorithm instance."""
        vqe = VQE()
        with self.subTest(msg="assert running empty raises AlgorithmError"):
            with self.assertRaises(AlgorithmError):
                _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op)

        ansatz = TwoLocal(rotation_blocks=["ry", "rz"],
                          entanglement_blocks="cz")
        vqe.ansatz = ansatz
        with self.subTest(msg="assert missing operator raises AlgorithmError"):
            with self.assertRaises(AlgorithmError):
                _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op)

        vqe.expectation = MatrixExpectation()
        vqe.quantum_instance = self.statevector_simulator
        with self.subTest(msg="assert VQE works once all info is available"):
            result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
            self.assertAlmostEqual(result.eigenvalue.real,
                                   self.h2_energy,
                                   places=5)

        operator = PrimitiveOp(
            np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0,
                                                                  3]]))

        with self.subTest(msg="assert minimum eigensolver interface works"):
            result = vqe.compute_minimum_eigenvalue(operator=operator)
            self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
    def test_primitive_strings(self):
        """ get primitives test """
        self.assertEqual(X.primitive_strings(), {'Pauli'})

        gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + \
            PrimitiveOp(Operator.from_label('+r0IX').data)
        self.assertEqual(gnarly_op.primitive_strings(), {'QuantumCircuit', 'Matrix'})
    def test_primitive_strings(self):
        """get primitives test"""
        self.assertEqual(X.primitive_strings(), {"Pauli"})

        gnarly_op = 3 * (H ^ I
                         ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + PrimitiveOp(
                             Operator.from_label("+r0IX").data)
        self.assertEqual(gnarly_op.primitive_strings(),
                         {"QuantumCircuit", "Matrix"})
    def test_circuit_construction(self):
        """circuit construction test"""
        hadq2 = H ^ I
        cz = hadq2.compose(CX).compose(hadq2)
        qc = QuantumCircuit(2)
        qc.append(cz.primitive, qargs=range(2))

        ref_cz_mat = PrimitiveOp(CZGate()).to_matrix()
        np.testing.assert_array_almost_equal(cz.to_matrix(), ref_cz_mat)
 def test_to_pauli_op(self):
     """ Test to_pauli_op method """
     gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + \
         PrimitiveOp(Operator.from_label('+r0IX').data)
     mat_op = gnarly_op.to_matrix_op()
     pauli_op = gnarly_op.to_pauli_op()
     self.assertIsInstance(pauli_op, SummedOp)
     for p in pauli_op:
         self.assertIsInstance(p, PauliOp)
     np.testing.assert_array_almost_equal(mat_op.to_matrix(), pauli_op.to_matrix())
    def test_io_consistency(self):
        """consistency test"""
        new_op = X ^ Y ^ I
        label = "XYI"
        # label = new_op.primitive.to_label()
        self.assertEqual(str(new_op.primitive), label)
        np.testing.assert_array_almost_equal(new_op.primitive.to_matrix(),
                                             Operator.from_label(label).data)
        self.assertEqual(new_op.primitive, Pauli(label))

        x_mat = X.primitive.to_matrix()
        y_mat = Y.primitive.to_matrix()
        i_mat = np.eye(2, 2)
        np.testing.assert_array_almost_equal(
            new_op.primitive.to_matrix(), np.kron(np.kron(x_mat, y_mat),
                                                  i_mat))

        hi = np.kron(H.to_matrix(), I.to_matrix())
        hi2 = Operator.from_label("HI").data
        hi3 = (H ^ I).to_matrix()
        np.testing.assert_array_almost_equal(hi, hi2)
        np.testing.assert_array_almost_equal(hi2, hi3)

        xy = np.kron(X.to_matrix(), Y.to_matrix())
        xy2 = Operator.from_label("XY").data
        xy3 = (X ^ Y).to_matrix()
        np.testing.assert_array_almost_equal(xy, xy2)
        np.testing.assert_array_almost_equal(xy2, xy3)

        # Check if numpy array instantiation is the same as from Operator
        matrix_op = Operator.from_label("+r")
        np.testing.assert_array_almost_equal(
            PrimitiveOp(matrix_op).to_matrix(),
            PrimitiveOp(matrix_op.data).to_matrix())
        # Ditto list of lists
        np.testing.assert_array_almost_equal(
            PrimitiveOp(matrix_op.data.tolist()).to_matrix(),
            PrimitiveOp(matrix_op.data).to_matrix(),
        )
    def test_to_matrix(self):
        """to matrix text"""
        np.testing.assert_array_equal(X.to_matrix(),
                                      Operator.from_label("X").data)
        np.testing.assert_array_equal(Y.to_matrix(),
                                      Operator.from_label("Y").data)
        np.testing.assert_array_equal(Z.to_matrix(),
                                      Operator.from_label("Z").data)

        op1 = Y + H
        np.testing.assert_array_almost_equal(op1.to_matrix(),
                                             Y.to_matrix() + H.to_matrix())

        op2 = op1 * 0.5
        np.testing.assert_array_almost_equal(op2.to_matrix(),
                                             op1.to_matrix() * 0.5)

        op3 = (4 - 0.6j) * op2
        np.testing.assert_array_almost_equal(op3.to_matrix(),
                                             op2.to_matrix() * (4 - 0.6j))

        op4 = op3.tensor(X)
        np.testing.assert_array_almost_equal(
            op4.to_matrix(), np.kron(op3.to_matrix(), X.to_matrix()))

        op5 = op4.compose(H ^ I)
        np.testing.assert_array_almost_equal(
            op5.to_matrix(), np.dot(op4.to_matrix(), (H ^ I).to_matrix()))

        op6 = op5 + PrimitiveOp(Operator.from_label("+r").data)
        np.testing.assert_array_almost_equal(
            op6.to_matrix(),
            op5.to_matrix() + Operator.from_label("+r").data)

        param = Parameter("α")
        m = np.array([[0, -1j], [1j, 0]])
        op7 = MatrixOp(m, param)
        np.testing.assert_array_equal(op7.to_matrix(), m * param)

        param = Parameter("β")
        op8 = PauliOp(primitive=Pauli("Y"), coeff=param)
        np.testing.assert_array_equal(op8.to_matrix(), m * param)

        param = Parameter("γ")
        qc = QuantumCircuit(1)
        qc.h(0)
        op9 = CircuitOp(qc, coeff=param)
        m = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
        np.testing.assert_array_equal(op9.to_matrix(), m * param)
    def test_list_op_parameters(self):
        """Test that Parameters are stored correctly in a List Operator"""
        lam = Parameter("λ")
        phi = Parameter("φ")
        omega = Parameter("ω")

        mat_op = PrimitiveOp([[0, 1], [1, 0]], coeff=omega)

        qc = QuantumCircuit(1)
        qc.rx(phi, 0)
        qc_op = PrimitiveOp(qc)

        op1 = SummedOp([mat_op, qc_op])

        params = [phi, omega]
        self.assertEqual(op1.parameters, set(params))

        # check list nesting case
        op2 = PrimitiveOp([[1, 0], [0, -1]], coeff=lam)

        list_op = ListOp([op1, op2])

        params.append(lam)
        self.assertEqual(list_op.parameters, set(params))
Esempio n. 11
0
    def test_qiskit_result_instantiation(self):
        """ qiskit result instantiation test """
        qc = QuantumCircuit(3)
        # REMEMBER: This is Qubit 2 in Operator land.
        qc.h(0)
        sv_res = execute(qc, BasicAer.get_backend('statevector_simulator')).result()
        sv_vector = sv_res.get_statevector()
        qc_op = PrimitiveOp(qc) @ Zero

        qasm_res = execute(qc_op.to_circuit(meas=True),
                           BasicAer.get_backend('qasm_simulator')).result()

        np.testing.assert_array_almost_equal(StateFn(sv_res).to_matrix(),
                                             [.5 ** .5, .5 ** .5, 0, 0, 0, 0, 0, 0])
        np.testing.assert_array_almost_equal(StateFn(sv_vector).to_matrix(),
                                             [.5 ** .5, .5 ** .5, 0, 0, 0, 0, 0, 0])
        np.testing.assert_array_almost_equal(StateFn(qasm_res).to_matrix(),
                                             [.5 ** .5, .5 ** .5, 0, 0, 0, 0, 0, 0],
                                             decimal=1)

        np.testing.assert_array_almost_equal(((I ^ I ^ H) @ Zero).to_matrix(),
                                             [.5 ** .5, .5 ** .5, 0, 0, 0, 0, 0, 0])
        np.testing.assert_array_almost_equal(qc_op.to_matrix(),
                                             [.5 ** .5, .5 ** .5, 0, 0, 0, 0, 0, 0])
    def test_op_parameters(self):
        """Test that Parameters are stored correctly"""
        phi = Parameter("φ")
        theta = ParameterVector(name="θ", length=2)

        qc = QuantumCircuit(2)
        qc.rz(phi, 0)
        qc.rz(phi, 1)
        for i in range(2):
            qc.rx(theta[i], i)
        qc.h(0)
        qc.x(1)

        l = Parameter("λ")
        op = PrimitiveOp(qc, coeff=l)

        params = {phi, l, *theta.params}

        self.assertEqual(params, op.parameters)
        self.assertEqual(params, StateFn(op).parameters)
        self.assertEqual(params, StateFn(qc, coeff=l).parameters)
    def test_evals(self):
        """evals test"""
        # TODO: Think about eval names
        self.assertEqual(Z.eval("0").eval("0"), 1)
        self.assertEqual(Z.eval("1").eval("0"), 0)
        self.assertEqual(Z.eval("0").eval("1"), 0)
        self.assertEqual(Z.eval("1").eval("1"), -1)
        self.assertEqual(X.eval("0").eval("0"), 0)
        self.assertEqual(X.eval("1").eval("0"), 1)
        self.assertEqual(X.eval("0").eval("1"), 1)
        self.assertEqual(X.eval("1").eval("1"), 0)
        self.assertEqual(Y.eval("0").eval("0"), 0)
        self.assertEqual(Y.eval("1").eval("0"), -1j)
        self.assertEqual(Y.eval("0").eval("1"), 1j)
        self.assertEqual(Y.eval("1").eval("1"), 0)

        with self.assertRaises(ValueError):
            Y.eval("11")

        with self.assertRaises(ValueError):
            (X ^ Y).eval("1111")

        with self.assertRaises(ValueError):
            Y.eval((X ^ X).to_matrix_op())

        # Check that Pauli logic eval returns same as matrix logic
        self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("0").eval("0"), 1)
        self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("1").eval("0"), 0)
        self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("0").eval("1"), 0)
        self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("1").eval("1"), -1)
        self.assertEqual(PrimitiveOp(X.to_matrix()).eval("0").eval("0"), 0)
        self.assertEqual(PrimitiveOp(X.to_matrix()).eval("1").eval("0"), 1)
        self.assertEqual(PrimitiveOp(X.to_matrix()).eval("0").eval("1"), 1)
        self.assertEqual(PrimitiveOp(X.to_matrix()).eval("1").eval("1"), 0)
        self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("0").eval("0"), 0)
        self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("1").eval("0"), -1j)
        self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("0").eval("1"), 1j)
        self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("1").eval("1"), 0)

        pauli_op = Z ^ I ^ X ^ Y
        mat_op = PrimitiveOp(pauli_op.to_matrix())
        full_basis = list(
            map("".join, itertools.product("01", repeat=pauli_op.num_qubits)))
        for bstr1, bstr2 in itertools.product(full_basis, full_basis):
            # print('{} {} {} {}'.format(bstr1, bstr2, pauli_op.eval(bstr1, bstr2),
            # mat_op.eval(bstr1, bstr2)))
            np.testing.assert_array_almost_equal(
                pauli_op.eval(bstr1).eval(bstr2),
                mat_op.eval(bstr1).eval(bstr2))

        gnarly_op = SummedOp(
            [
                (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(Z),
                PrimitiveOp(Operator.from_label("+r0I")),
                3 * (X ^ CX ^ T),
            ],
            coeff=3 + 0.2j,
        )
        gnarly_mat_op = PrimitiveOp(gnarly_op.to_matrix())
        full_basis = list(
            map("".join, itertools.product("01", repeat=gnarly_op.num_qubits)))
        for bstr1, bstr2 in itertools.product(full_basis, full_basis):
            np.testing.assert_array_almost_equal(
                gnarly_op.eval(bstr1).eval(bstr2),
                gnarly_mat_op.eval(bstr1).eval(bstr2))