How to use the pyquil.api.QVMConnection function in pyquil

To help you get started, we’ve selected a few pyquil examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rigetti / pyquil / examples / 1.3_vqe_demo.py View on Github external
result = result[0][
            0
        ].real  # first output is expected value, second is variance, third is shots
    elif isinstance(hamiltonian, np.ndarray) and isinstance(quantum_resource, QVMConnection):
        wf = quantum_resource.wavefunction(ucc_circuit(theta))
        wf = wf.amplitudes.reshape((-1, 1))
        result = np.conj(wf).T.dot(hamiltonian).dot(wf)[0, 0].real
        print(result)
    else:
        raise TypeError("type of hamiltonian or qvm is unrecognized")

    return result


if __name__ == "__main__":
    qvm = QVMConnection(endpoint="http://localhost:5000")
    bond_length = np.linspace(0.25, 3, 30)
    ucc_energy = []
    fci_energy = []
    hf_energy = []
    for rr in bond_length:
        molecule = get_h2_dimer(rr)
        hamiltonian = molecule.get_molecular_hamiltonian()
        bk_hamiltonian = symmetry_conserving_bravyi_kitaev(get_fermion_operator(hamiltonian), 4, 2)

        # generate the spin-adapted classical coupled-cluster amplitude to use as the input for the
        # circuit
        packed_amps = uccsd_singlet_get_packed_amplitudes(
            molecule.ccsd_single_amps,
            molecule.ccsd_double_amps,
            molecule.n_qubits,
            molecule.n_electrons,
github msohaibalam / Link_to_Quantum_game / meyer_classical_quantum_game.py View on Github external
text_size_ = font.render("Prob(not flip): " + str(1 - picard_prob), True, (0, 0, 0))
        screen.blit(text_size_, [150, size_y - 100])
        # display Q's 2nd choice
        text_rect_Q_x = font.render("|b|^2: " + str(np.square(b2)), True, (0, 0, 0))
        screen.blit(text_rect_Q_x, [size_x - 400, 50])
        text_size_ = font.render("|a|^2: " + str(np.square(a2)), True, (0, 0, 0))
        screen.blit(text_size_, [size_x - 400, 20])
        # program is now ready to be run
        run_quantum_program = True

    if run_quantum_program:
        # draw DESTRUCTION! log
        pygame.draw.rect(screen, (0, 0, 0), (0, dest_y, size_x, dest_width))
        ### Carry out program
        # initialize program
        qvm = api.QVMConnection()
        p = Program()

        ##### Q's 1st move
        p.defgate("Q1", U_(a1, b1))
        p.inst(("Q1", 0))

        ##### Picard's random move
        # set the parameters for the random move
        prob = picard_prob
        # create a dummy gate
        a = np.random.rand()
        b = np.sqrt(1 - np.square(a))
        Uf_ = U_(a, b)
        # perform the random move
        p.defgate("Uf", Uf_)
        p.inst(("Uf", 0))
github rigetti / pyquil / examples / 1.3_vqe_demo.py View on Github external
from openfermionpsi4 import run_psi4
from openfermion.hamiltonians import MolecularData
from openfermion.transforms import symmetry_conserving_bravyi_kitaev, get_fermion_operator
from openfermion.utils import uccsd_singlet_get_packed_amplitudes

from forestopenfermion import qubitop_to_pyquilpauli

from pyquil.quil import Program
from pyquil.paulis import sX, sY, exponentiate, PauliSum
from pyquil.gates import X
from pyquil.api import QVMConnection
from pyquil.unitary_tools import tensor_up

from grove.measurements.estimation import estimate_locally_commuting_operator

QVM_CONNECTION = QVMConnection(endpoint="http://localhost:5000")


def get_h2_dimer(bond_length):
    # Set molecule parameters.
    basis = "sto-3g"
    multiplicity = 1
    charge = 0
    geometry = [("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, bond_length])]
    molecule = MolecularData(geometry, basis, multiplicity, charge)
    molecule.filename = "./" + molecule.filename.split("/")[-1]
    # Run Psi4.
    molecule = run_psi4(
        molecule, run_scf=True, run_mp2=False, run_cisd=False, run_ccsd=True, run_fci=True
    )
    return molecule
github msohaibalam / Link_to_Quantum_game / overworld.py View on Github external
def calculate_probs () :
    
    results = {}
    for basis in ["XX","ZZ","XZ","ZX"]:
        
        if sim:
            engine = api.QVMConnection(use_queue=True)
        else:
            engine = api.QPUConnection(device)   

        script = Program()
        
        # bell state
        script.inst( H(0) )
        script.inst( H(5) )
        script.inst( CZ(0,5) )
        script.inst( RY( numpy.pi/4, 0 ) )
        script.inst( H(0) )
        script.inst( H(5) )
        
        # set up bases
        
        if basis[0]=="X":
github msohaibalam / Link_to_Quantum_game / quantum_darts.py View on Github external
import pygame
import numpy as np
import pyquil.api as api
from pyquil.gates import *
from pyquil.quil import Program

## open a QVM/QPU connection
cxn = api.QVMConnection()
# cxn = api.QPUConnection('19Q-Acorn')

# define colors
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
red_blue = (255, 0, 255)
red_green = (255, 255, 0)
blue_green = (0, 255, 255)
black = (0, 0, 0)
color_code = 0
dartboard_A_color = (127.5, 127.5, 127.5)
# boolean controling when game stops
game_over = False
color_rect = True
# frames per second
github rigetti / pyquil / examples / meyer_penny_game.py View on Github external
# Q puts the coin into a superposition
    prog.inst(H(0))
    # Picard makes a decision and acts accordingly
    prog.measure(1, picard_register)
    prog.if_then(picard_register, then_branch, else_branch)
    # Q undoes his superposition operation
    prog.inst(H(0))
    # The outcome is recorded into the answer register
    prog.measure(0, answer_register)

    return prog


if __name__ == "__main__":
    n_trials = 10
    qvm = api.QVMConnection()
    outcomes = np.asarray(qvm.run(meyer_penny_program(), [0, 1], trials=n_trials))

    print("Number of games: {}".format(n_trials))
    print("Q's winning average: {}".format(outcomes[:, 0].mean()))
    print("Picard's flip-decision average: {}".format(outcomes[:, 1].mean()))
github JackHidary / quantumcomputingbook / chapter10 / pyquil / vqe.py View on Github external
# Plot the sampled expectation
plt.plot(angle_range, sampled, "-o")

# Plotting options
plt.title("VQE on a Noisy Measurement Simulator")
plt.xlabel("Angle [radians]")
plt.ylabel("Expectation value")
plt.grid()
plt.show()

# Study the effect of increasing measurement noise in VQE
data = []
noises = np.linspace(0.0, 0.5, 20)
for noise in noises:
    measure_noise = [noise] * 3
    noisy_qvm = api.QVMConnection(measurement_noise=measure_noise)
    result = vqe_inst.vqe_run(small_ansatz, hamiltonian, initial_angle, samples=10000, qvm=noisy_qvm)
    data.append(result['fun'])

# Plot the ground state energy vs noise level
plt.plot(noises, data)
plt.xlabel('Noise level %')
plt.ylabel('Eigenvalue')
plt.show()

# ==========================
# More sophisticated ansatze
# ==========================
print()
print(" More sophisticated ansatze ".center(80, "="))
print()
github JackHidary / quantumcomputingbook / chapter10 / pyquil / vqe.py View on Github external
from pyquil.quil import Program
import pyquil.api as api
from pyquil.paulis import sZ
from pyquil.gates import RX, RZ, X, MEASURE

from grove.pyvqe.vqe import VQE

# ============================
# VQE on a noiseless simulator
# ============================
print()
print(" VQE on a noiseless simulator ".center(80, "="))
print()

# Get a QVM Connection. NOTE: This requires the qvm to be running
qvm = api.QVMConnection()

# Function to create the ansatz
def small_ansatz(params):
    """Returns an ansatz Program with one parameter."""
    return Program(RX(params[0], 0))

# Show the ansatz with an example value for the parameter
print("Ansatz with example value for parameter:")
print(small_ansatz([1.0]))

# Create a Hamltion H = Z_0
hamiltonian = sZ(0)

# Make an instance of VQE with a Nelder-Mead minimizer
vqe_inst = VQE(minimizer=minimize,
               minimizer_kwargs={'method': 'nelder-mead'})