Beispiel #1
0
    def get_angles(self):
        """
        Finds optimal angles with the quantum variational eigensolver method.

        Stored VQE result

        :returns: ([list], [list]) A tuple of the beta angles and the gamma
                  angles for the optimal solution.
        """
        stacked_params = np.hstack((self.betas, self.gammas))
        vqe = VQE(self.minimizer,
                  minimizer_args=self.minimizer_args,
                  minimizer_kwargs=self.minimizer_kwargs)
        cost_ham = reduce(lambda x, y: x + y, self.cost_ham)
        # maximizing the cost function!
        param_prog = self.get_parameterized_program()
        result = vqe.vqe_run(param_prog,
                             cost_ham,
                             stacked_params,
                             qvm=self.qvm,
                             **self.vqe_options)
        self.result = result
        betas = result.x[:self.steps]
        gammas = result.x[self.steps:]
        return betas, gammas
Beispiel #2
0
def test_vqe_run():
    """VQE initialized and then minimizer is called to return result. Checks
    correct sequence of execution"""
    def param_prog(alpha):
        return Program([H(0), RZ(alpha)(0)])

    hamiltonian = np.array([[1, 0], [0, -1]])
    initial_param = 0.0

    minimizer = Mock(spec=minimize, func_code=minimize.func_code)
    fake_result = Mock()
    fake_result.fun = 1.0
    fake_result.x = [0.0]
    fake_result.status = 0  # adding so we avoid writing to logger
    minimizer.return_value = fake_result

    # not actually called in VQE run since we are overriding minmizer to just
    # return a value. Still need this so I don't try to call the QVM server.
    fake_qvm = Mock(spec=['wavefunction'])

    inst = VQE(minimizer)

    t_result = inst.vqe_run(param_prog,
                            hamiltonian,
                            initial_param,
                            qvm=fake_qvm)
    assert np.isclose(t_result.fun, 1.0)
Beispiel #3
0
def test_vqe_run():
    """
    VQE initialized and then minimizer is called to return result.

    Checks correct sequence of execution.
    """
    def param_prog(alpha):
        return Program([H(0), RZ(alpha)(0)])

    hamiltonian = np.array([[1, 0], [0, -1]])
    initial_param = 0.0

    minimizer = MagicMock(spec=minimize, func_code=minimize.__code__)
    fake_result = Mock()
    fake_result.fun = 1.0
    fake_result.x = [0.0]
    fake_result.status = 0  # adding so we avoid writing to logger
    minimizer.return_value = fake_result

    # not actually called in VQE run since we are overriding minmizer to just
    # return a value. Still need this so I don't try to call the QVM server.
    fake_qvm = Mock(spec=['wavefunction'])

    with patch("funcsigs.signature") as patch_signature:
        func_sigs_fake = MagicMock(spec=funcsigs.Signature)
        func_sigs_fake.parameters.return_value = \
            OrderedDict({
                'fun': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'x0': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'args': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'method': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'jac': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'hess': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'hessp': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'bounds': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'constraints': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'tol': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'callback': funcsigs.Parameter.POSITIONAL_OR_KEYWORD,
                'options': funcsigs.Parameter.POSITIONAL_OR_KEYWORD
            })

        patch_signature.return_value = func_sigs_fake
        inst = VQE(minimizer)

        t_result = inst.vqe_run(param_prog,
                                hamiltonian,
                                initial_param,
                                qc=fake_qvm)
        assert np.isclose(t_result.fun, 1.0)
              PauliTerm.from_list([("I", 0),("I", 1)], coefficient=-3.8505),
              PauliTerm.from_list([("I", 0),("X", 1)], coefficient=-0.2288),
              PauliTerm.from_list([("I", 0),("Z", 1)], coefficient=-1.0466),
              PauliTerm.from_list([("X", 0),("I", 1)], coefficient=-0.2288),
              PauliTerm.from_list([("X", 0),("X", 1)], coefficient=0.2613),
              PauliTerm.from_list([("X", 0),("Z", 1)], coefficient=0.2288),
              PauliTerm.from_list([("Z", 0),("I", 1)], coefficient=-1.0466),
              PauliTerm.from_list([("Z", 0),("X", 1)], coefficient=0.2288),
              PauliTerm.from_list([("Z", 0),("Z", 1)], coefficient=0.2356)])
print(hamiltonian)

# Define ansatz
n_qubits = 2
depth = 3

def ansatz(params): 
    qp = Program()
    for i in range(depth):   
		qp.inst(CNOT(1,0))  
        for j in range(n_qubits):
            qp.inst(RY(params[j], j))  
    return qp

# Minimize and get approximate of the lowest eigenvalue
qvm = QVMConnection()
vqe = VQE(minimizer=minimize, minimizer_kwargs={'method': 'nelder-mead', 'options': {'xatol': 1.0e-2}})

# Initial Parameters
ip = np.random.uniform(0.0, 2*np.pi, size=n_qubits) 
result = vqe.vqe_run(ansatz, hamiltonian, ip, samples=None, qvm=qvm)
print(result)
Beispiel #5
0
# Variational-Quantum-Eigensolver in Grove
#==============================================================================
# Create connection with QVM
qc = get_qc('2q-qvm')

# Define matrix
from pyquil.paulis import sZ
H = sZ(0)

# Define ansatz
from pyquil.gates import RY


def ansatz(params):
    return Program(RY(params[0], 0))


# Minimize and get approximate of the lowest eigenvalue
from grove.pyvqe.vqe import VQE
vqe = VQE(minimizer=minimize,
          minimizer_kwargs={
              'method': 'nelder-mead',
              'options': {
                  'initial_simplex': np.array([[0.0], [0.05]]),
                  'xatol': 1.0e-2
              }
          })

initial_params = [0.0]
result = vqe.vqe_run(ansatz, H, initial_params, samples=10000, qc=qc)
print(result)
Beispiel #6
0
])

# Define ansatz
n_qubits, depth = 3, 3
from pyquil.gates import RY, CNOT


def ansatz(params):
    p = Program()
    for i in range(depth):
        p += CNOT(2, 0)
        for j in range(n_qubits):
            p += Program(RY(params[j], j))
    return p


# Minimize and get approximate of the lowest eigenvalue
from grove.pyvqe.vqe import VQE
qvm = QVMConnection()
vqe = VQE(minimizer=minimize,
          minimizer_kwargs={
              'method': 'nelder-mead',
              'options': {
                  'xatol': 1.0e-2
              }
          })

np.random.seed(999)
initial_params = np.random.uniform(0.0, 2 * np.pi, size=n_qubits)
result = vqe.vqe_run(ansatz, H, initial_params, samples=None, qvm=qvm)
print(result)
Beispiel #7
0
# 1. Calling Libraries
from pyquil.quil import Program
from pyquil.api import QVMConnection
from pyquil.gates import RX
from pyquil.paulis import sZ, PauliSum, PauliTerm

# Calling Grove Library and optimiser
from grove.pyvqe.vqe import VQE
import numpy as np
from scipy.optimize import minimize

# 2. Initialising the program
qvm = QVMConnection()
vqe = VQE(minimizer=minimize, minimizer_kwargs={'method': 'nelder-mead'})


# 3. Defining ansatz
def ansatz(theta):
    qp = Program()
    qp.inst(RX(theta[0], 0))
    return qp


# 4. Defining Hamiltonian
hamiltonian = sZ(0)

# 5. Running the VQE
initial_angle = [0.0]
result = vqe.vqe_run(ansatzv, hamiltonian, initial_angle, None, qvm=qvm)
print(result)