예제 #1
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()


def measurement_distribution(result):
    num_zeros = 0
    num_ones = 0
    for x in result:
        if x == [0]:
            num_zeros += 1
        else:
            num_ones += 1
    return [num_zeros, num_ones]


def get_Re(result):
    dist = measurement_distribution(result)
    return dist[0] - dist[1]


hadamard_test0 = Program(
    X(0),
    H(0),
    CNOT(0, 1),
    H(0),
예제 #2
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()


test_run_and_measure_empty = Program()

print(test_run_and_measure_empty)
result = qvm.run_and_measure(Program(), [0], 1)


test_run = Program(
    H(0),
    CNOT(0, 1)

)

print("test_run")
result = qvm.run(test_run, [0], 1)
print(result)


test_run_async = Program(
    H(0),
    CNOT(0, 1)
예제 #3
0
파일: ghz.py 프로젝트: vtomole/project-1
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()
ghz_state = Program(H(0), H(1), X(2), CNOT(1, 2), CNOT(0, 2), H(0), H(1), H(2))
ghz_state_efficient = Program(H(0), CNOT(0, 1), CNOT(1, 2))
print("3Q GHZ State QVM")
result = qvm.run_and_measure(ghz_state, [0, 1, 2], 100)
print(result)
예제 #4
0
def test_seeded_qvm(test_device):
    def mock_response(request, context):
        assert json.loads(request.text) == {
            "type": "multishot-measure",
            "qubits": [0, 1],
            "trials": 2,
            "compiled-quil": "H 0\nCNOT 0 1\n"
        }
        return '[[0,0],[1,1]]'

    with patch.object(CompilerConnection, "compile") as m_compile,\
            patch('pyquil.api.qvm.apply_noise_model') as m_anm,\
            requests_mock.Mocker() as m:
        m.post('https://api.rigetti.com/qvm', text=mock_response)
        m_compile.side_effect = [BELL_STATE]
        m_anm.side_effect = [BELL_STATE]

        qvm = QVMConnection(test_device)
        assert qvm.noise_model == test_device.noise_model
        qvm.run_and_measure(BELL_STATE, qubits=[0, 1], trials=2)
        assert m_compile.call_count == 1
        assert m_anm.call_count == 1

        test_device.noise_model = None
        qvm = QVMConnection(test_device)
        assert qvm.noise_model is None
        qvm.run_and_measure(BELL_STATE, qubits=[0, 1], trials=2)
        assert m_compile.call_count == 1
        assert m_anm.call_count == 1

        qvm = QVMConnection()
        assert qvm.noise_model is None
        qvm.run_and_measure(BELL_STATE, qubits=[0, 1], trials=2)
        assert m_compile.call_count == 1
        assert m_anm.call_count == 1
예제 #5
0
# qubit number=5
# total number=56
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np

conn = QVMConnection()

def make_circuit()-> Program:

    prog = Program() # circuit begin



    prog += H(0)  # number=3
    prog += H(1) # number=4
    prog += H(2) # number=5
    prog += H(3)  # number=6
    prog += H(0) # number=41
    prog += CZ(1,0) # number=42
    prog += H(0) # number=43
    prog += Z(1) # number=37
    prog += H(0) # number=51
    prog += CZ(1,0) # number=52
    prog += H(0) # number=53
    prog += H(4)  # number=21
    prog += X(2) # number=39

    prog += H(0)  # number=1
예제 #6
0
# unfinished: https://www.nature.com/articles/s41467-017-01904-7

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()
grover = Program(X(3), H(0), H(1), H(2), H(3), X(0) CNOT(0, 1), CCNOT(1, 2, 3), H(0), H(1), H(2), H(3), X(0), X(1), X(2))
print("3 Qubit Grover")
result = qvm.run_and_measure(grover, [0, 1, 2], 100)
print(result)
예제 #7
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)
예제 #8
0
def without_error(n, s, runs):
    """ runs grover on 2^n qubits without error simulation """
    qvm = QVMConnection(use_queue=False)  # put in queue in case too long
    p = grover(n, s)  # stores grover program
    result = qvm.run(p, list(range(n)), trials=runs)  # stores result
    print(accuracy(result, s))  # prints accuracy rate
예제 #9
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")
예제 #10
0
"""
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)
예제 #11
0
def test():
    qvm = QVMConnection()
    p = Program(X(1), H(0), CNOT(0, 1))
    wf = qvm.wavefunction(p)
    wfo = str(wf)
    output.writetooutput()
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),
            ))
예제 #13
0
from pyquil.quil import Program
from pyquil.api import QVMConnection
from pyquil.gates import H, CNOT, MEASURE

print("Making Connection")
qvm = QVMConnection()
print("Making Program")
p = Program(H(0), CNOT(0, 1), MEASURE(0, 0), MEASURE(1, 1))
results = qvm.run(p, classical_addresses=[0, 1], trials=10)
print(results)
예제 #14
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)
예제 #15
0
from pyquil.quil import Program
#from pyquil.api import QPUConnection
from pyquil.api import QVMConnection
from pyquil.gates import *
from numpy import pi

#qpu = QPUConnection(device_name='19Q-Acorn')
qvm = QVMConnection()
exp = Program(RX(pi/2, 0),
              I(0),
              RZ(-pi/2, 0),

              RX(-pi/2, 0),
              I(0),
              RZ(pi/2, 0))

print("EXPERIMENT 1")
result = qvm.run_and_measure(exp, [0], 10)
print(result)
예제 #16
0
def test_estimate_pauli_sum():
    """
    Full test of the estimation procedures
    """
    quantum_resource = QVMConnection()

    # type checks
    with pytest.raises(TypeError):
        estimate_pauli_sum('5', {
            0: 'X',
            1: 'Z'
        }, Program(), 1.0E-3, quantum_resource)

    with pytest.raises(CommutationError):
        estimate_pauli_sum([sX(0), sY(0)], {
            0: 'X',
            1: 'Z'
        }, Program(), 1.0E-3, quantum_resource)

    with pytest.raises(TypeError):
        estimate_pauli_sum(sX(0), {
            0: 'X',
            1: 'Z'
        }, Program(), 1.0E-3, quantum_resource)

    # mock out qvm
    np.random.seed(87655678)
    brv1 = bernoulli(p=0.25)
    brv2 = bernoulli(p=0.4)
    n = 500
    two_qubit_measurements = list(zip(brv1.rvs(size=n), brv2.rvs(size=n)))
    pauli_terms = [sZ(0), sZ(1), sZ(0) * sZ(1)]

    fakeQVM = Mock(spec=QVMConnection())
    fakeQVM.run = Mock(return_value=two_qubit_measurements)
    mean, means, cov, estimator_var, shots = estimate_pauli_sum(
        pauli_terms, {
            0: 'Z',
            1: 'Z'
        },
        Program(),
        1.0E-1,
        fakeQVM,
        symmetrize=False)
    parity_results = np.zeros((len(pauli_terms), n))
    parity_results[0, :] = [-2 * x[0] + 1 for x in two_qubit_measurements]
    parity_results[1, :] = [-2 * x[1] + 1 for x in two_qubit_measurements]
    parity_results[2, :] = [
        -2 * (sum(x) % 2) + 1 for x in two_qubit_measurements
    ]

    assert np.allclose(np.cov(parity_results, ddof=1), cov)
    assert np.isclose(np.sum(np.mean(parity_results, axis=1)), mean)
    assert np.allclose(np.mean(parity_results, axis=1), means)
    assert np.isclose(shots, n)
    variance_to_beat = np.sum(cov) / (n - 1)
    assert np.isclose(variance_to_beat, estimator_var)

    # Double the shots by ever so slightly decreasing variance bound
    double_two_q_measurements = two_qubit_measurements + two_qubit_measurements
    mean, means, cov, estimator_var, shots = estimate_pauli_sum(
        pauli_terms, {
            0: 'Z',
            1: 'Z'
        },
        Program(),
        variance_to_beat - 1.0E-8,
        fakeQVM,
        symmetrize=False)

    parity_results = np.zeros((len(pauli_terms), 2 * n))
    parity_results[0, :] = [-2 * x[0] + 1 for x in double_two_q_measurements]
    parity_results[1, :] = [-2 * x[1] + 1 for x in double_two_q_measurements]
    parity_results[2, :] = [
        -2 * (sum(x) % 2) + 1 for x in double_two_q_measurements
    ]

    assert np.allclose(np.cov(parity_results, ddof=1), cov)
    assert np.isclose(np.sum(np.mean(parity_results, axis=1)), mean)
    assert np.allclose(np.mean(parity_results, axis=1), means)
    assert np.isclose(shots, 2 * n)
    assert np.isclose(np.sum(cov) / (2 * n - 1), estimator_var)
예제 #17
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))
def reservoir_compute(sample, reservoir_circuit, qcircuit_callback):
    '''
    sample: numpy array of floating point data
    reservoir_circuit: Program to implement quantum reservoir computer
    qcircuit_callback: a callback to generate the input state
    initialization circuit
    '''

    p = qcircuit_callback(sample)
    psi = qvm.wavefunction(p + p_reservoir)
    probabilities = np.real(psi.amplitudes.conjugate() * psi.amplitudes)
    return probabilities


if __name__ == '__main__':
    qvm = QVMConnection()

    # circuit depth parameter
    depth = 8

    # initialize repeatable random reservoir
    np.random.seed(12939229)
    theta_init = get_init_theta(depth)
    p_reservoir = output_gates(theta_init, depth)

    # load data
    train, test = load_mnist_data()
    num_train_samples = train[0].shape[0]
    num_test_samples = test[0].shape[0]

    # for debugging, limit job sizes
예제 #19
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)
예제 #20
0
import matplotlib.pyplot as plt
from grove.tomography.process_tomography import do_process_tomography
from pyquil.api import CompilerConnection
from pyquil.api import QVMConnection
from pyquil.api import get_devices
from pyquil.gates import *
from pyquil.quil import Program

qvm = QVMConnection()
acorn = get_devices(as_dict=True)['19Q-Acorn']

# QVM with QPU
qpu = QVMConnection()

# noise acorn; qpu = QVMConnection()

#qpu = QPUConnection(acorn)

qubits = [8, 13]
gate = SWAP
gate_str = 'SWAP'
numberSamples = 500
numberSamplesQVM = 1000


def compile_INIT_gate(prog):
    compiler = CompilerConnection(acorn)
    compiledProg = compiler.compile(prog)
    qpuProg = Program()
    qpuProg.inst(compiledProg)
예제 #21
0
파일: inqnet.py 프로젝트: vtomole/project-1
# https://www.reddit.com/r/QuantumComputing/comments/7tfl74/what_does_this_circuit_do/?st=jcxukv2c&sh=f19ff94e
from pyquil.quil import Program
from pyquil.api import QVMConnection
from pyquil.gates import *

qvm = QVMConnection()

inqnet = Program(
    H(1),
    CNOT(0, 1),
    CNOT(1, 2),
    CNOT(0, 1),
    H(0),
    CNOT(1, 2),
    CZ(2, 0),
    H(0),
    H(0),

)
print("inqnet")
result = qvm.run_and_measure(inqnet, [0, 1, 2], 5)
print(result)
예제 #22
0
import pytest
from mock import patch

from pyquil.api import QVMConnection, QPUConnection, CompilerConnection
from pyquil.api._base_connection import validate_noise_probabilities, validate_run_items
from pyquil.api.qpu import append_measures_to_program
from pyquil.quil import Program
from pyquil.gates import CNOT, H, MEASURE
from pyquil.device import ISA

BELL_STATE = Program(H(0), CNOT(0, 1))
BELL_STATE_MEASURE = Program(H(0), CNOT(0, 1), MEASURE(0, 0), MEASURE(1, 1))
DUMMY_ISA_DICT = {"1Q": {"0": {}, "1": {}}, "2Q": {"0-1": {}}}
DUMMY_ISA = ISA.from_dict(DUMMY_ISA_DICT)

qvm = QVMConnection(api_key='api_key', user_id='user_id')
async_qvm = QVMConnection(api_key='api_key', user_id='user_id', use_queue=True)
compiler = CompilerConnection(isa_source=DUMMY_ISA,
                              api_key='api_key',
                              user_id='user_id')
async_compiler = CompilerConnection(isa_source=DUMMY_ISA,
                                    api_key='api_key',
                                    user_id='user_id',
                                    use_queue=True)


def test_sync_run():
    def mock_response(request, context):
        assert json.loads(request.text) == {
            "type": "multishot",
            "addresses": [0, 1],