Example #1
0
def test_initialization():
    r1 = [0, 1, 2]
    r2 = [3, 4, 5]
    circuit = shor.initialization(r1, r2)
    
    qvm = QVMConnection()
    
    #confirm hadamard transform does expected
    qvm.wavefunction(circuit)[0].real == 1/np.sqrt(2**len(r1))
Example #2
0
def getRandomNum(num):
    q = QVMConnection()
    s = "".join(["H " + str(i) + "\n" for i in range(num)])
    s += "".join(
        ["MEASURE " + str(i) + " [" + str(i) + "]\n" for i in range(num)])
    #print(s)
    p = parse_program(s)
    res = None
    try:
        res = str(
            q.wavefunction(p).amplitudes)[1:-1].split(" ").index("1.+0.j")
    except:
        print(q.wavefunction(p).amplitudes)
        return -1
    return res
Example #3
0
 def displayState(self):
     qvm = QVMConnection()
     wf = qvm.wavefunction(self.theGame)
     probs = wf.probabilities()
     if self.numOfBits <= 4 or not self.longLineSuppress: #Avoids printing long wavefunctions.
         print('Wavefunction:',wf)
         print('State Probabilities:',[round(i,2) for i in probs])
     print('Win Probabilities:', self.winProbabilities(probs))
 def test_create_singlet_state(self):
     p = create_singlet_state()
     qvm = QVMConnection()
     wavefunction = qvm.wavefunction(p)
     # Make sure the wave function is what we expect
     # 1/sqrt(2) * (01|> - 10|>)
     self.assertEqual(wavefunction.amplitudes[0], 0)
     self.assertAlmostEqual(wavefunction.amplitudes[1],
                            0.7071067811865475 + 0j)
     self.assertAlmostEqual(wavefunction.amplitudes[2],
                            -0.7071067811865475 + 0j)
     self.assertEqual(wavefunction.amplitudes[3], 0)
Example #5
0
def main():
    qvm = QVMConnection()

    # Rotation
    for angle in [0, pi/4, pi/2, 3*pi/4, pi]:
        p = create_singlet_state()
        add_switch_to_singlet_triplet_basis_gate_to_program(p)

        # Rotate phase to specified angle. In a real system, both spins/qubits are rotating,
        # But the difference between angles is all that matters
        p.inst(PHASE(angle, 0))
        # Using custom gate defined in add_switch_to_singlet_triplet_basis_gate_to_program function
        p.inst(("SWITCH_TO_SINGLET_TRIPLET_BASIS", 0, 1))
        # p.inst(PHASE(pi/4, 1))
        wavefunction = qvm.wavefunction(p)
        probs = wavefunction.get_outcome_probs()

        print("Rotation angle: %s", angle/pi*180)
        print("Probabilities ('11' - Singlet, '00' - Triplet): %s" % probs)
Example #6
0
            molecule.ccsd_double_amps,
            molecule.n_qubits,
            molecule.n_electrons,
        )
        theta = packed_amps[-1]  # always take the doubles amplitude

        # now that we're done setting up the Hamiltonian and grabbing initial opt parameters
        # we can switch over to how to run things
        ucc_program = ucc_circuit(theta)

        paulis_bk_hamiltonian = qubitop_to_pyquilpauli(bk_hamiltonian)
        bk_mat = tensor_up(paulis_bk_hamiltonian, [0, 1])

        w, v = np.linalg.eigh(bk_mat)

        wf = qvm.wavefunction(ucc_program)
        wf = wf.amplitudes.reshape((-1, 1))

        tenergy = np.conj(wf).T.dot(bk_mat).dot(wf)[0, 0].real

        # observable = objective_fun(theta, hamiltonian=paulis_bk_hamiltonian, quantum_resource=qvm)
        observable = objective_fun(theta, hamiltonian=bk_mat, quantum_resource=qvm)

        result = minimize(
            objective_fun, x0=theta, args=(bk_mat, qvm), method="CG", options={"disp": True}
        )
        ucc_energy.append(result.fun)
        fci_energy.append(molecule.fci_energy)
        hf_energy.append(molecule.hf_energy)
        print(w[0], molecule.fci_energy, tenergy, result.fun)
Example #7
0
if number_of_cards == 1:
    print("Queen is at position 1\n")
    quit()

qvm = QVMConnection()
grover_circuit = Program()
qubits = list(reversed(range(N)))
print("No of qubits required: ", len(qubits))

printline1 = "--" * 50

#Step 1 of Grover's Algorithm - Initialization
print("\nStep 1 : Initialization")
print(printline1)
grover_circuit.inst([I(q) for q in qubits])  #(1)|00>
print(qvm.wavefunction(grover_circuit))

print("\nApplying the H gate")
grover_circuit.inst([H(q) for q in qubits
                     ])  #(1/2)|00> + (1/2)|01> + (1/2)|10> + (1/2)|11>
print(qvm.wavefunction(grover_circuit))

# Step 2 of Grover's Algorithm - Define quantum oracle
print("\nStep 2 : Define quantum oracle")
print(printline1)
oracle = np.zeros(shape=(2**N, 2**N))
for b in range(2**N):
    if np.binary_repr(b, N) == queen_position_binary:
        oracle[b, b] = -1
    else:
        oracle[b, b] = 1
prog += Program(H(tmp[0]))
for i in range(0, len(qregs)):
    prog += Program(H(qregs[i]))

# this is the oracle, think of it as a blackbo
for i in range(0, len(qregs)):
    if s & (1 << i):
        prog += Program(CNOT(qregs[i], tmp[0]))

prog += Program(H(tmp[0]))
for i in range(0, len(qregs)):
    prog += Program(H(qregs[i]))

for i in range(0, len(qregs)):
    prog += Program(MEASURE(qregs[i], i))

prog = address_qubits(prog)

print(prog)

qvm = QVMConnection()

wf = qvm.wavefunction(prog)
print(wf)
print(wf.amplitudes)

results = qvm.run(prog, classical_addresses=class_readouts, trials=10)

for r in results:
    print r
Example #9
0
# Imports for pyQuil (ignore for now)
import numpy as np
from pyquil.quil import Program
from pyquil.api import QVMConnection
quantum_simulator = QVMConnection()

# pyQuil is based around operations (or gates) so we will start with the most
# basic one: the identity operation, called I. I takes one argument, the index
# of the qubit that it should be applied to.
from pyquil.gates import *

# Make a quantum program that allocates one qubit (qubit #0) and does nothing to it
p = Program(I(0))

print(p.inst(X(0)))

# Quantum states are called wavefunctions for historical reasons.
# We can run this basic program on our connection to the simulator.
# This call will return the state of our qubits after we run program p.
# This api call returns a tuple, but we'll ignore the second value for now.
wavefunction = quantum_simulator.wavefunction(p)

# wavefunction is a Wavefunction object that stores a quantum state as a list of amplitudes
alpha, beta = wavefunction

print("Our qubit is in the state alpha={} and beta={}".format(alpha, beta))
print("The probability of measuring the qubit in outcome 0 is {}".format(
    abs(alpha)**2))
print("The probability of measuring the qubit in outcome 1 is {}".format(
    abs(beta)**2))
def main():
    agave = get_devices(as_dict=True)['8Q-Agave']
    compiler = CompilerConnection(agave)
    qvm = QVMConnection()  # Perfect QVM
    qvm_noisy = QVMConnection(agave)  # Simulate Noise
    qpu = QPUConnection(agave)  # Physical QPU
    print("Timestamp,"
          "Singlet (Wavefunction), Triplet (Wavefunction), "
          "Singlet (QVM), Triplet (QVM),"
          "Singlet Mean (QVM Noise), Singlet Std (QVM Noise), "
          "Triplet Mean (QVM Noise), Triplet Std (QVM Noise),"
          "00 Mean (QVM Noise), 00 Std (QVM Noise),"
          "11 Mean (QVM Noise), 11 Std (QVM Noise),"
          "Singlet Mean (QPU), Singlet Std (QPU),"
          "Triplet Mean (QPU), Triplet Std (QPU),"
          "00 Mean (QPU), 00 Std (QPU),"
          "11 Mean (QPU), 1 Std (QPU)")
    # Rotation
    fp_raw = open("output.txt", "w")
    for t in range(0, 30):  # ns
        # for t in np.arange(0.0, 30.0, 0.1):  # ns
        p = create_singlet_state()
        add_switch_to_singlet_triplet_basis_gate_to_program(p)
        w_larmor = 0.46  # 4.6e8 1/s as determined in the experiment
        p.inst(PHASE(w_larmor * t, 0))
        p.inst(("SWITCH_TO_SINGLET_TRIPLET_BASIS", 0, 1))
        wavefunction = qvm.wavefunction(p)
        probs = wavefunction.get_outcome_probs()

        p.measure(0, 0)
        p.measure(1, 1)

        # Run the code on a perfect QVM (no noise)
        data = qvm.run(p, trials=1024)

        # simulate physical noise on QVM
        singlet_noisy = []
        triplet_noisy = []
        state11_noisy = []
        state00_noisy = []
        for i in range(0, 3):
            data_noisy = qvm_noisy.run(p, trials=1000)
            noisy_data_distr = distribution(data_noisy)
            singlet_noisy.append(noisy_data_distr[(1, 0)])
            triplet_noisy.append(noisy_data_distr[(0, 1)])
            state11_noisy.append(noisy_data_distr[(1, 1)])
            state00_noisy.append(noisy_data_distr[(0, 0)])

        # Run the code on QPU
        singlet_qpu = []
        triplet_qpu = []
        state11_qpu = []
        state00_qpu = []

        # Suppress print statements
        _old_stdout = sys.stdout
        for i in range(0, 9):
            with open(os.devnull, 'w') as fp:
                sys.stdout = fp
                data_qpu = qpu.run(p, trials=1024)
            qpu_data_distr = distribution(data_qpu)
            singlet_qpu.append(qpu_data_distr[(1, 0)])
            triplet_qpu.append(qpu_data_distr[(0, 1)])
            state11_qpu.append(qpu_data_distr[(1, 1)])
            state00_qpu.append(qpu_data_distr[(0, 0)])

        sys.stdout = _old_stdout
        # print('compiled quil', job.compiled_quil())
        # print('gate volume', job.gate_volume())
        # print('gate depth', job.gate_depth())
        # print('topological swaps', job.topological_swaps())
        # print('program fidelity', job.program_fidelity())
        # print('multiqubit gate depth', job.multiqubit_gate_depth())

        # Note the order of qubit in Rigetti
        # http://pyquil.readthedocs.io/en/latest/qvm.html#multi-qubit-basis-enumeration
        # (1, 0) is singlet, but in string notation it is reversed ('01'), because
        #
        #  "The Rigetti QVM enumerates bitstrings such that qubit 0 is the least significant bit (LSB)
        #   and therefore on the right end of a bitstring"
        #
        print("%s, Noise, Singlet, %s" % (t, singlet_noisy), file=fp_raw)
        print("%s, Noise, Triplet, %s" % (t, triplet_noisy), file=fp_raw)
        print("%s, Noise, 00, %s" % (t, state00_noisy), file=fp_raw)
        print("%s, Noise, 11, %s" % (t, state11_noisy), file=fp_raw)
        print("%s, QPU, Singlet, %s" % (t, singlet_qpu), file=fp_raw)
        print("%s, QPU, Triplet, %s" % (t, triplet_qpu), file=fp_raw)
        print("%s, QPU, 00, %s" % (t, state00_qpu), file=fp_raw)
        print("%s, QPU, 11, %s" % (t, state11_qpu), file=fp_raw)
        print(
            "%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s"
            % (
                t,
                probs['01'],
                probs['10'],
                distribution(data).get((1, 0), 0),
                distribution(data).get((0, 1), 0),
                np.mean(singlet_noisy),
                np.std(singlet_noisy),
                np.mean(triplet_noisy),
                np.std(triplet_noisy),
                np.mean(state00_noisy),
                np.std(state00_noisy),
                np.mean(state11_noisy),
                np.std(state11_noisy),
                np.mean(singlet_qpu),
                np.std(singlet_qpu),
                np.mean(triplet_qpu),
                np.std(triplet_qpu),
                np.mean(state00_qpu),
                np.std(state00_qpu),
                np.mean(state11_qpu),
                np.std(state11_qpu),
            ))
Example #11
0
from pyquil.quil import Program
#from pyquil.api import QPUConnection
from pyquil.api import QVMConnection
from pyquil.gates import *

qvm = QVMConnection()

ins = Program()

ins.inst(H(1), CNOT(1, 2))  # Creating B00
ins.inst(CNOT(0, 1), H(0))
ins.measure(0, 0).measure(1, 1).if_then(1, X(2)).if_then(0, Z(2))
wvf = qvm.wavefunction(ins, [0, 1])
#print( wvf)

ins = Program(
    H(0),
    H(1),
    CNOT(1, 2),
    CNOT(0, 1),
    H(0),
)

ins.measure(0, 0).measure(1, 1).if_then(1, X(2)).if_then(1, Z(2))
wvf = qvm.wavefunction(ins)

print(ins)
result = qvm.run_and_measure(ins, [2])
print(result)

print(wvf)
Example #12
0
from pyquil.quil import Program
#from pyquil.api import QPUConnection
from pyquil.api import QVMConnection
from pyquil.gates import *


#qpu = QPUConnection(device_name='19Q-Acorn')
qvm = QVMConnection()


# f0
zero_one = Program(
    # Put qubit 0 and qubit 1 into superposition
    H(0),
    CNOT(0, 1),
    X(0),
    Z(0),
    CNOT(0, 1),
    H(0),

)
wvf = qvm.wavefunction(zero_one)

print(wvf)
print("0 1")
result = qvm.run_and_measure(zero_one, [0, 1], 100)
print(result)
Example #13
0
#!/usr/bin/env python

"""
A script appropriate for featuring on rigetti.com to show how easy it is to get started!

This version exists on the website as of September, 2018. It should continue working
even if PyQuil changes.
"""

from pyquil.quil import Program
from pyquil.gates import H, CNOT
from pyquil.api import QVMConnection

# construct a Bell State program
p = Program(H(0), CNOT(0, 1))
# run the program on a QVM
qvm = QVMConnection()
result = qvm.wavefunction(p)
print(result)
Example #14
0
def test():
    qvm = QVMConnection()
    p = Program(X(1), H(0), CNOT(0, 1))
    wf = qvm.wavefunction(p)
    wfo = str(wf)
    output.writetooutput()
Example #15
0
import numpy as np
from pyquil.quil import Program
from pyquil.api import QVMConnection
quantum_simulator = QVMConnection()
# pyQuil is based around operations (or gates) so we will start with the most
# basic one: the identity operation, called I. I takes one argument, the index
# of the qubit that it should be applied to.
from pyquil.gates import I
p = Program(I(0))

# Quantum states are called wavefunctions for historical reasons.
# We can run this basic program on our connection to the simulator.
# This call will return the state of our qubits after we run program p.
# This api call returns a tuple, but we'll ignore the second value for now.
wavefunction = quantum_simulator.wavefunction(p)

# wavefunction is a Wavefunction object that stores a quantum state as a list of amplitudes
alpha, beta = wavefunction

print("Our qubit is in the state alpha = {} and beta = {}".format(alpha, beta))
print("The probability of measuring the qubit in outcome 0 is {}".format(
    abs(alpha)**2))
print("The probabbility of measuring the qubit in outcome 1 is {}".format(
    abs(beta)**2))

# Applying an operation to our qubit affects the probability of each outcome.
# We can import the qubit "flip" operation, called X, and see what it does.
# We will learn more about this operation in the next section.
from pyquil.gates import X
p = Program(X(0))
Example #16
0
        prog += H(2)  # number=19
        prog += H(3)  # number=20

    # circuit end

    return prog


def summrise_results(bitstrings) -> dict:
    d = {}
    for l in bitstrings:
        if d.get(l) is None:
            d[l] = 1
        else:
            d[l] = d[l] + 1

    return d


if __name__ == '__main__':

    x_bits = "1011"
    f = lambda rep: str(int(rep == x_bits))

    prog = make_circuit(4, f)
    state = conn.wavefunction(prog)

    #writefile = open("../data/startPyquil_Class9.csv","w")
    print(state.get_outcome_probs())  #,file=writefile)
    #writefile.close()
Example #17
0
print(y)

x = np.fft.ifft(y, norm='ortho')
print(x)

#==============================================================================
# QFT
#==============================================================================
import math
from pyquil.quil import Program
from pyquil.api import QVMConnection
from pyquil.gates import SWAP, H, CPHASE

# Create connection with QVM and initilize program
qvm = QVMConnection()
prog = Program()

# Prepare state
prog = prog.inst(H(0), H(1))
print('Amplitudes a of input state psi: {}'.format(
    qvm.wavefunction(prog).amplitudes))

# Perfrom QFT
prog += SWAP(0, 1)
prog += H(1)
prog += CPHASE(math.pi / 2, 0, 1)
prog += H(0)

print('Amplitudes b of output state phi: {}'.format(
    qvm.wavefunction(prog).amplitudes))
Example #18
0
matplotlib.use('Agg')
import matplotlib.pyplot as plt

if __name__ == '__main__':
    N_qubit = 10
    for noise_prob in [0., .01, .05, .1]:
        #1% chance of each gate at each timestep
        pauli_channel = [noise_prob] * 3

        noisy_qvm = QVMConnection(gate_noise=pauli_channel)

        p = Program(H(0))
        for i in range(N_qubit - 1):
            p += Program(CNOT(i, i + 1))

        print(noisy_qvm.wavefunction(p))

        print(p)

        classical_reg = [i for i in range(N_qubit)]
        for i in range(N_qubit):
            p.measure(i, i)

        num_trials = 1000
        result = noisy_qvm.run(p, classical_reg, trials=num_trials)

        for r in result:
            print(r)

        plt.hist([2 * (sum(trial) - 5) for trial in result],
                 label='noise = %s' % noise_prob,
Example #19
0
'''
import sys, math
import numpy as np
from numpy.fft import ifft
from math import pi

from pyquil.quil import Program
import pyquil.api as api
from pyquil.api import QVMConnection
from pyquil.gates import *


def exampleQft3(q0, q1, q2):
    p = Program()
    p.inst(H(q2), CPHASE(pi / 2.0, q1, q2), H(q1), CPHASE(pi / 4.0, q0, q2),
           CPHASE(pi / 2.0, q0, q1), H(q0),
           SWAP(q0, q2))  # SWAP is necessary because the QTF swaps the qubits
    return p


if __name__ == "__main__":
    print('hi there, we will qtf [0, 1, 0, 0, 0, 0, 0, 0] \n')
    qvm = QVMConnection()
    state_prep = Program().inst(X(0), I(1), I(2))
    # wavefunction = qvm.wavefunction(state_prep)
    # print(wavefunction)

    wavefunction = qvm.wavefunction(state_prep + exampleQft3(0, 1, 2))
    print(wavefunction.amplitudes)
    ifft([0, 1, 0, 0, 0, 0, 0, 0], norm="ortho")
Example #20
0
"""
test program
creates GHZ state with 10 qubits and sample 100 times
"""

from pyquil.quil import Program
from pyquil.api import QVMConnection, Job
from pyquil.gates import *
import pyquil.paulis as paulis

N_qubit = 10
N_sample = 100
qvm = QVMConnection()

p = Program(H(0))
for i in range(N_qubit - 1):
    p += Program(CNOT(i, i + 1))

print(qvm.wavefunction(p))

print(p)

classical_reg = [i for i in range(N_qubit)]
for i in range(N_qubit):
    p.measure(i, i)

result = qvm.run(p, classical_reg, trials=100)

for r in result:
    print(r)
Example #21
0
from pyquil.quil import Program
from pyquil.gates import I,H
from pyquil.api import QVMConnection

qvm = QVMConnection()
P = Program(H(0))
print(qvm.wavefunction(P))
from openfermion.utils import hermitian_conjugated
from forestopenfermion import qubitop_to_pyquilpauli, pyquilpauli_to_qubitop

from pyquil.quil import Program
from pyquil.gates import X
from pyquil.paulis import exponentiate
from pyquil.api import QVMConnection

hubbard_hamiltonian = FermionOperator()
spatial_orbitals = 4
for i in range(spatial_orbitals):
    electron_hop_alpha = FermionOperator(((2*i, 1), (2*((i+1) % spatial_orbitals), 0)))
    electron_hop_beta = FermionOperator(((2*i+1, 1), ((2 * ((i+1) % spatial_orbitals) + 1), 0)))
    hubbard_hamiltonian += -1 * (electron_hop_alpha + hermitian_conjugated(electron_hop_alpha))
    hubbard_hamiltonian += -1 * (electron_hop_beta + hermitian_conjugated(electron_hop_beta))
    hubbard_hamiltonian += FermionOperator(((2*i, 1), (2*i, 0), (2*i+1, 1), (2*i+1, 0)), 4.0)
hubbard_term_generator = jordan_wigner(hubbard_hamiltonian)
pyquil_hubbard_generator = qubitop_to_pyquilpauli(hubbard_term_generator)


localized_electrons_program = Program()
localized_electrons_program.inst([X(0), X(1)])
pyquil_program = Program()
for term in pyquil_hubbard_generator.terms:
    pyquil_program += exponentiate(0.1*term)
print (localized_electrons_program + pyquil_program)
qvm = QVMConnection()
print(qvm.run(pyquil_program, [0], 10))
wf = qvm.wavefunction(pyquil_program)
print(wf)
Example #23
0
#
# classical-quantum interaction
# Bell state: ( |00> + |11> )
#
from pyquil.gates import H, CNOT
from pyquil.quil import Program
from pyquil.api import QVMConnection

#define classical register
creg=0

# repeat simulate coin
pbell=Program(H(0),CNOT(0,1))
# define virtual quantum machine (remote)
qsim=QVMConnection()

#
wf=qsim.wavefunction(pbell)

# before measurement
print("Before measurement H|0>= ", qsim.wavefunction(pbell))

# after measurement
pbell.measure(0,creg)
for x in range(5):
    print("After measurement: ", qsim.wavefunction(pbell))
    print("Prob = ", wf.get_outcome_probs())
# QVM 
from pyquil.api import QVMConnection 
from pyquil.gates import Z, H, CNOT, MEASURE 
# Instantiating a new qvm instance 
qvm = QVMConnection() 
# Our program p requires 2 qubits, labeled 0 & 1
p = Program(H(0), CNOT(0, 1), MEASURE(0, 0), MEASURE(1, 1)) 
results = qvm.run(p, classical_addresses=[0, 1], trials=10)

# Seeing the results is nice! 
# There are ten trials so this should return an array such that len(results) === 10.
print(results)
# [[1,1], [1,1], [1,1], [0,0], [1,1], [1,1], [1,1], [1,1], [1,1], [1,1]]

# There's also a wavefunction representation of the program from the qvm.
wavefunction = qvm.wavefunction(p)
print(wavefunction)
# (1+0j)|11>

## Large qubit count test
p30 = Program(
  Z(0), 
  Z(1),
  Z(2),
  Z(3),
  Z(4),
  Z(5),
  Z(6),
  Z(7),
  Z(8),
  Z(9),
Example #25
0
from pyquil.api import QVMConnection

#==============================================================================
# Initilization
#==============================================================================
qvm = QVMConnection()
prog = Program()

#==============================================================================
# Qubit
#==============================================================================
from pyquil.gates import I
prog.inst(I(1), I(0))

# Print current quantum state of the system
state = qvm.wavefunction(prog)
print("The system is in state: {}".format(state))

# Probabilities
print("Probability that after measurement the system is in state 00 {}".format(
    abs(state.amplitudes[0])**2))
print("Probability that after measurement the system is in state 01 {}".format(
    abs(state.amplitudes[1])**2))
print("Probability that after measurement the system is in state 10 {}".format(
    abs(state.amplitudes[2])**2))
print("Probability that after measurement the system is in state 11 {}".format(
    abs(state.amplitudes[3])**2))

#==============================================================================
# Quantum gates
#==============================================================================
Example #26
0
from pyquil.quil import Program
#from pyquil.api import QPUConnection
from pyquil.api import QVMConnection
from pyquil.gates import *

qvm = QVMConnection()

ins = Program()

ins.inst(H(1), CNOT(1, 2))  # Creating B00
ins.inst(CNOT(0, 1), H(0))
ins.measure(0, 0).measure(1, 1).if_then(1, X(2)).if_then(0, Z(2))
wvf = qvm.wavefunction(ins, [0, 1])
#print( wvf)


ins = Program(
    H(0),
    H(1),
    CNOT(1, 2),
    CNOT(0, 1),
    H(0),
)


ins.measure(0, 0).measure(1, 1).if_then(1, X(2)).if_then(1, Z(2))
wvf = qvm.wavefunction(ins)

print(ins)
result = qvm.run_and_measure(ins, [2])
print(result)
def main():
    qvm = QVMConnection()
    agave = get_devices(as_dict=True)['8Q-Agave']
    qvm_noisy = QVMConnection(agave)
    print(
        "Timestamp, Singlet (Wavefunction), Triplet (Wavefunction), Singlet (QVM), Triplet (QVM),"
        "Singlet (Noise), Triplet (Noise), 00 (Noise), 11 (Noise),"
        "Singlet (Compiled on QVM), Triplet (Compiled on QVM), 00 (Compiled on QVM), 11 (Compiled on QVM),"
    )

    # Truncate file with compiled code
    open(FILENAME, "w").close()
    # Rotation
    for t in range(0, 50):  # ns
        p = create_singlet_state()
        add_switch_to_singlet_triplet_basis_gate_to_program(p)
        w_larmor = 0.46  # 4.6e8 1/s as determined in the experiment
        p.inst(PHASE(w_larmor * t, 0))
        p.inst(("SWITCH_TO_SINGLET_TRIPLET_BASIS", 0, 1))
        wavefunction = qvm.wavefunction(p)
        probs = wavefunction.get_outcome_probs()

        p.measure(0, 0)
        p.measure(1, 1)
        # Run on a perfect QVM (no noise)
        data = qvm.run(p, trials=1000)

        # simulate physical noise on QVM
        data_noisy = qvm_noisy.run(p, trials=1000)
        noisy_data_distr = distribution(data_noisy)

        agave = get_devices(as_dict=True)['8Q-Agave']
        compiler = CompilerConnection(agave)
        job_id = compiler.compile_async(p)
        # wait_for_job has print statement
        # using this workaround to suppress it
        import sys, os
        _old_stdout = sys.stdout
        with open(os.devnull, 'w') as fp:
            sys.stdout = fp
            job = compiler.wait_for_job(
                job_id)  # This is the only line that matters
        sys.stdout = _old_stdout

        # Run code compiled for 8Q-Agave on a noisy QVM
        # Per example on https://github.com/rigetticomputing/pyquil/blob/master/examples/run_quil.py
        p_compiled = Program(job.compiled_quil())
        with open(FILENAME, "a") as fp:
            fp.write("Timestep: %s\n" % t)
            fp.write("%s" % job.compiled_quil())
            fp.write("\n")
        data_compiled = qvm_noisy.run(p_compiled, trials=1000)
        compiled_data_distr = distribution(data_compiled)

        print("%s, %s, %s, %s, %s, %s, %s, %s ,%s, %s, %s, %s, %s" % (
            t,
            probs['01'],
            probs['10'],
            distribution(data).get((0, 1), 0),
            distribution(data).get((1, 0), 0),
            noisy_data_distr.get((0, 1), 0),
            noisy_data_distr.get((1, 0), 0),
            noisy_data_distr.get((0, 0), 0),
            noisy_data_distr.get((1, 1), 0),
            compiled_data_distr.get((0, 1), 0),
            compiled_data_distr.get((1, 0), 0),
            compiled_data_distr.get((0, 0), 0),
            compiled_data_distr.get((1, 1), 0),
        ))
Example #28
0
# http://pyquil.readthedocs.io/en/latest/intro.html

# Imports for pyQuil (ignore for now)
import numpy as np
from pyquil.quil import Program
from pyquil.api import QVMConnection
quantum_simulator = QVMConnection()

# pyQuil is based around operations (or gates) so we will start with the most
# basic one: the identity operation, called I. I takes one argument, the index
# of the qubit that it should be applied to.
from pyquil.gates import *

# Make a quantum program that allocates one qubit (qubit #0) and does nothing to it
p = Program(I(0))

print(p.inst(X(0)))

# Quantum states are called wavefunctions for historical reasons.
# We can run this basic program on our connection to the simulator.
# This call will return the state of our qubits after we run program p.
# This api call returns a tuple, but we'll ignore the second value for now.
wavefunction = quantum_simulator.wavefunction(p)

# wavefunction is a Wavefunction object that stores a quantum state as a list of amplitudes
alpha, beta = wavefunction

print("Our qubit is in the state alpha={} and beta={}".format(alpha, beta))
print("The probability of measuring the qubit in outcome 0 is {}".format(abs(alpha)**2))
print("The probability of measuring the qubit in outcome 1 is {}".format(abs(beta)**2))
Example #29
0
from pyquil.quil import Program
#from pyquil.api import QPUConnection
from pyquil.api import QVMConnection
from pyquil.gates import *

#qpu = QPUConnection(device_name='19Q-Acorn')
qvm = QVMConnection()

# f0
zero_one = Program(
    # Put qubit 0 and qubit 1 into superposition
    H(0),
    CNOT(0, 1),
    X(0),
    Z(0),
    CNOT(0, 1),
    H(0),
)
wvf = qvm.wavefunction(zero_one)

print(wvf)
print("0 1")
result = qvm.run_and_measure(zero_one, [0, 1], 100)
print(result)