Example #1
0
def estimate_gradient(f_h, precision, n_measurements=50, cxn=False):
    """ Estimate the gradient from point of evaluation
        to point of perturbation, h

    :param float f_h: Oracle output at perturbation h.
    :param int precision: Bit precision of gradient.
    :param Connection cxn: connection to the QPU or QVM
    :param int n_measurements: Number of times to measure system.
    """

    # enumerate input and ancilla qubits
    input_qubits = list(range(precision))
    ancilla_qubit = precision

    # generate gradient program
    perturbation_sign = np.sign(f_h)
    p_gradient = gradient_estimator(abs(f_h), ancilla_qubit)

    # run gradient program
    if not cxn:
        from pyquil.api import SyncConnection
        cxn = SyncConnection()
    measurements = cxn.run(p_gradient, input_qubits, n_measurements)

    # summarize measurements
    bf_estimate = perturbation_sign * measurements_to_bf(measurements)
    bf_explicit = '{0:.16f}'.format(bf_estimate)
    deci_estimate = binary_to_real(bf_explicit)

    return deci_estimate
Example #2
0
def run(n, mappings):
    deutsch_program = pq.Program()
    qubits = [deutsch_program.alloc() for _ in range(n)]
    ancilla = deutsch_program.alloc()
    unitary_funct = unitary_function(mappings)
    oracle = oracle_function(unitary_funct, qubits, ancilla)
    deutsch_program += deutsch_jozsa(oracle, qubits, ancilla)
    deutsch_program.out()
    qvm = SyncConnection()
    results = qvm.run_and_measure(deutsch_program, [q.index() for q in qubits])
    return "balanced" if 1 in results[0] else "constant"
Example #3
0
        # of the currently built up reversed_prog because
        # of the reversal of the steps in the final reversed program.
        reversed_prog = reversed_step_prog + reversed_prog

    # Add Hadamard gates to remove superposition
    reversed_prog = pq.Program().inst(list(map(H, qubits))) + reversed_prog

    # Correct the overall phase
    reversed_prog = pq.Program().inst(RZ(-2 * phases[0], qubits[0])) \
                      .inst(PHASE(2 * phases[0], qubits[0])) + reversed_prog

    # Apply all gates in reverse
    return reversed_prog


if __name__ == "__main__":
    print("Example list: -3.2+1j, -7, -0.293j, 1, 0, 0")
    v = input("Input a comma separated list of complex numbers:\n")
    if isinstance(v, int):
        v = [v]
    else:
        v = list(v)
    p = create_arbitrary_state(v)
    qvm = SyncConnection()
    wf, _ = qvm.wavefunction(p)
    print("Normalized Vector: ", list(v / np.linalg.norm(v)))
    print("Generated Wavefunction: ", wf)
    if input("Show Program? (y/n): ") == 'y':
        print("----------Quil Code Used----------")
        print(p.out())
Example #4
0
    for i, qubit in enumerate(qubits):
        if bitstring[i] == '0':
            prog.inst(X(qubit))

    prog += amp.n_qubit_control(qubits[:-1], qubits[-1],
                                np.array([[1, 0], [0, -1]]), 'Z')

    for i, qubit in enumerate(qubits):
        if bitstring[i] == '0':
            prog.inst(X(qubit))
    return prog


if __name__ == "__main__":
    from pyquil.api import SyncConnection
    import sys

    try:
        target = sys.argv[1]
    except IndexError:
        raise ValueError("Enter a target bitstring for Grover's Algorithm.")

    grover_program = pq.Program()
    qubits = range(len(target))
    oracle = basis_selector_oracle(target, qubits)
    grover_program += grover(oracle, qubits)

    cxn = SyncConnection()
    mem = cxn.run_and_measure(grover_program, qubits)
    print(mem)
Example #5
0
    return np.allclose(np.eye(rows), mat.dot(mat.T.conj()))


if __name__ == "__main__":
    from pyquil.api import SyncConnection

    # Read function mappings from user
    n = int(input("How many bits? "))
    assert n > 0, "The number of bits must be positive."
    print("Enter f(x) for the following n-bit inputs:")
    mappings = []
    for i in range(2**n):
        val = int(input(integer_to_bitstring(i, n) + ': '))
        assert val in [0, 1], "f(x) must return only 0 and 1"
        mappings.append(val)

    deutsch_program = pq.Program()
    qubits = [deutsch_program.alloc() for _ in range(n)]
    ancilla = deutsch_program.alloc()

    unitary_funct = unitary_function(mappings)
    oracle = oracle_function(unitary_funct, qubits, ancilla)
    deutsch_program += deutsch_jozsa(oracle, qubits, ancilla)
    deutsch_program.out()

    print(deutsch_program)
    qvm = SyncConnection()
    results = qvm.run_and_measure(deutsch_program, [q.index() for q in qubits])
    print("Results:", results)
    print("f(x) is", "balanced" if 1 in results[0] else "constant")
Example #6
0
# Hello, World!

from pyquil.quil import Program
from pyquil.gates import H, CNOT
from pyquil.api import SyncConnection
# construct a Bell State program
p = Program()
p.inst(H(0))
p.inst(CNOT(0, 1))
# run the program on a QVM
qvm = SyncConnection()
result = qvm.wavefunction(p)

# pyquil init needed
Example #7
0
def cxn():
    c = SyncConnection()
    c.post_json = MockPostJson()
    c.post_json.return_value.text = json.dumps('Success')
    c.measurement_noise = 1
    return c
Example #8
0
from pyquil.quil import Program
from pyquil.gates import H, X, CNOT, MEASURE
from pyquil.api import SyncConnection

# Reference: https://arxiv.org/pdf/1302.4310.pdf

p = Program()
p.inst("""DEFGATE CH(%theta):
    1, 0, 0, 0
    0, 1, 0, 0
    0, 0, cos(2*%theta), sin(2*%theta)
    0, 0, sin(2*%theta), cos(-2*%theta)""")
p.inst(H(3))
p.inst(CNOT(3, 2))
p.inst(CNOT(2, 1))
p.inst("CH(pi/8) 1 0")
p.inst("CH(pi/16) 2 0")
p.inst(H(1))
p.inst(H(2))
p.inst(X(0))
p.inst(MEASURE(0))
p.inst(MEASURE(1))
p.inst(MEASURE(2))

# run the program on a QVM
qvm = SyncConnection()

wvf, _ = qvm.wavefunction(p)
print(wvf)
Example #9
0
from pyquil.quil import Program
from pyquil.gates import H, CNOT
from pyquil.api import SyncConnection
from pyquil.api import QVMConnection
from pyquil.gates import *

p = Program()
p.inst(H(0))
p.inst(CNOT(0, 1))
qvm = SyncConnection()
result = qvm.wavefunction(p)
print('result', result)

qvm = QVMConnection()
p = Program()
p.inst(H(0), CNOT(0, 1), MEASURE(0, 0), MEASURE(1, 1))
print(p)
x = qvm.run(p, [0, 1], 10)
print(x)

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.
Example #10
0
    prog += n_qubit_control(qubits, query_qubit, np.array([[0, 1], [1, 0]]),
                            'NOT')

    for i, qubit in enumerate(qubits):
        if bitstring[i] == '0':
            prog.inst(X(qubit))
    return prog


if __name__ == "__main__":
    from pyquil.api import SyncConnection
    import sys
    try:
        target = sys.argv[1]
    except IndexError:
        raise ValueError("Enter a target bitstring for Grover's Algorithm.")

    grover_program = pq.Program()
    qubits = [grover_program.alloc() for _ in target]
    query_qubit = grover_program.alloc()
    oracle = basis_selector_oracle(target, qubits, query_qubit)
    grover_program += grover(oracle, qubits, query_qubit)

    # To instantiate the qubits in the program. This is just a temporary hack.
    grover_program.out()
    print grover_program
    cxn = SyncConnection()
    mem = cxn.run_and_measure(grover_program, [q.index() for q in qubits])
    print mem