def main(n, s):
    p = Program()

    #make all the gates
    g = make_gate(n)
    Uf = make_UF_gate(n, s)
    p.defgate("RACL", g)
    p.defgate("UF", Uf)

    apply_Hn(p)  #applying the first series of H gates to the first n qubits
    p.inst(X(n), H(n))  #get the |-> qubit into our system

    r = int((math.pi * (2**(n / 2)) / 4))  #r is the number of iteration
    for i in range(r):
        p.inst(("UF", *range(n)))  #apply Uf
        apply_Hn(
            p)  #applying the second series of H gates to the first n qubits

        p.inst(("RACL", *range(n)))  #applying the unitary 2(|0><0|)^n - I^n
        apply_Hn(
            p)  #applying the third series of H gates to the first n qubits

    #Make the Measurement
    classical_regs = [*range(n)]
    for i in range(n):
        p.measure(i, i)
    result = qvm.run(p, classical_regs)
    #print (result)

    #convert the result from binary to decimal
    t = 0
    for i in range(n):
        t += (2**i) * result[0][n - 1 - i]
    print("the answer is ", t)
示例#2
0
def generate_single_depth_experiment(rotation: Program,
                                     depth: int,
                                     exp_type: str,
                                     axis: Tuple = None) -> Program:
    """
    Generate an experiment for a single depth where the type specifies a final measurement of either
    X or Y. The rotation program is repeated depth number of times, and we assume the rotation is
    about the axis (theta, phi).

    :param rotation: the program specifying the gate whose angle of rotation we wish to estimate.
    :param depth: the number of times we apply the rotation in the experiment
    :param exp_type: X or Y, specifying which operator to measure at the end of the experiment
    :param axis: the axis of rotation. If none is specified, axis is assumed to be the Z axis. (rotation should be RZ)
    :return: a program specifying the entire experiment of a single iteration of the RPE protocol in [RPE]
    """
    experiment = Program()
    ro_bit = experiment.declare("ro", "BIT", 1)
    qubit = list(rotation.get_qubits())[0]
    prepare_state(experiment, qubit, axis)
    for _ in range(depth):
        experiment.inst(rotation)
    if axis:
        experiment.inst(RZ(-axis[1], qubit))
        experiment.inst(RY(-axis[0], qubit))
    local_pauli_eig_meas(experiment, exp_type, qubit)
    experiment.measure(qubit, ro_bit)
    return experiment
示例#3
0
def grover(n, s):
    p = Program()  # create program

    ##################
    ## Define Gates ##
    ##################
    uf = build_uf(n, s)  # build Uf
    p.defgate("Uf", uf)  # define Uf

    ug = build_ug(n)  # build Ug
    p.defgate("Ug", ug)  # define Ug

    gate_string = build_gate_string(n)  # useful for applying gates

    ####################
    ## Create Program ##
    ####################
    hadamard_n(n, p)  # apply Hadamard to first N registers
    p.inst(X(n), H(n))  # apply X and N to last register to get minus

    for i in range(int(
        (np.pi * (2**(n / 2))) / 4)):  # repeat (pi*2^(n/2))/4 times
        p.inst(("Uf" + gate_string))  # apply Uf to all registers
        hadamard_n(n, p)  # apply Hadamard to first N
        p.inst(("Ug" + gate_string[:-2]))  # apply Ug to first N
        hadamard_n(n, p)  # apply Hadamard to first N

    for i in range(n):
        p.measure(i, i)  # measure first N qubits, store in same registers

    return p
示例#4
0
def User_circuit(problem,depth,qubits):#function presents user with available gates and makes them create their circuit layer by layer.

    available_gates=[]
    for gate in problem.instructions[:-qubits]:
        available_gates.append(gate.name)
    
    shuffle(available_gates)

    solution=Program()

    for layer in range(depth):
        print ('layer',layer)
        print ('Available gates:')
        print(available_gates)
        gates = input("Please enter gates in layer" + str(layer) + "in format[GATE qubit,GATE qubit]:")
        print()

        gates.split(' ', 1)
        layer = gates.split(",")

        for gate in layer:
            if gate.split(' ', 1)[0] in available_gates: 
                available_gates.remove(gate.split(' ', 1)[0])  
                solution.inst(gate)  
            else:
                print("Gate choice," +  gate + "not available")

    for i in range(qubits):
        solution.measure(i,i)
        
    return solution
def quantumcomp(charlist, bytelist, explicitprinting=0, samples=1):
    # empty list for results for each letter
    res = []
    # 8 bits in 1 byte
    bit = [None] * 8
    for j in range(0, len(bytelist)):
        # Do quantum stuff now we have our bit string
        qvm = QVMConnection()
        prog = Program()
        # make 8 individual bits for the 8 qubits
        bit = get_binary_from_byte(bytelist[j])
        print('\n#--------------------------------------------------------#')
        print('# Character= %s Bitstring = %s' % (charlist[j], bit))
        print('#--------------------------------------------------------#')
        # don't what this is for...
        cr = []
        for i in range(0, len(bit)):
            # do x rotation to get 1
            if bit[i] == 1:
                prog.inst(X(i))
            # measure the i-th qubit
            prog.measure(i, i)

        # store measurement outcomes, can change number of shots
        results = (qvm.run(prog, cr, samples))
        # use list for results for each char
        res.append(results[0])
        if explicitprinting == 1:
            print(compiletoquil(prog))
        print('\n#--------------------------------------------------------#')
        print('# Result =', results[0])
        print('#--------------------------------------------------------#')
    return res
def create_quill_length(c, invc, l):

    p = Program().inst(
        c[0:2 * l]
    )  #remember this l and 4l for full circuit with inverses and interleaving
    p.inst(invc[0:2 * l][::-1])
    p.measure(0, 0)
    return p
示例#7
0
def genQUIL(
    layers, qubits
):  #takes a list of gates in format [[H(1),I(2)],[H(2),I(1)],[CNOT(1,2),Y(3)]] converts to QUIL

    program = Program()

    for layer in layers:
        program.inst(layer)

    for i in qubits:
        program.measure(i, i)

    return program
def grover(marked_element):
    # Determine number of qubits needed
    n = len(marked_element)
    N = 2**n
    no_marked = int(marked_element, 2)

    # Determine number of times to iterate
    T = int(round(np.pi * np.sqrt(N) / 4 - 0.5))
    print('Number of iterations T =', T)

    # Invoking and renaming Program and Connection
    qvm = QVMConnection()
    p = Program()

    # Step 1: Start with qubits in equal superposition
    for i in range(n):
        p.inst(H(i))

    # Defining Oracle matrices: U_0 and U_f
    U_0 = np.eye(N)
    U_0[0][0] = -1
    U_f = np.eye(N)
    U_f[no_marked][no_marked] = -1

    # Defining Oracle gates
    p.defgate("U0", U_0)
    p.defgate("Uf", U_f)

    # Step 2: Repeat applications of U_f and D
    for i in range(T):
        # Apply U_f
        p.inst(("Uf", ) + tuple(range(n)))

        # Apply D
        for j in range(n):
            p.inst(H(j))

        p.inst(("U0", ) + tuple(range(n)))

        for j in range(n):
            p.inst(H(j))

    # Step 3: Measure all the qubits and output result
    for i in range(n):
        p.measure(i)

    # Run the program
    results = qvm.run(p, list(range(n)), 1)

    print('Element found =', results[0])
    return results[0]
示例#9
0
def _naive_program_generator(qc: QuantumComputer, qubits: Sequence[int],
                             permutations: np.ndarray,
                             gates: np.ndarray) -> Program:
    """
    Naively generates a native quil program to implement the circuit which is comprised of the given
    permutations and gates.

    :param qc: the quantum resource that will implement the PyQuil program for each model circuit
    :param qubits: the qubits available for the implementation of the circuit. This naive
        implementation simply takes the first depth-many available qubits.
    :param permutations: array of depth-many arrays of size n_qubits indicating a qubit permutation
    :param gates: a depth by depth//2 array of matrices representing the 2q gates at each layer.
        The first row of matrices is the earliest-time layer of 2q gates applied.
    :return: a PyQuil program in native_quil instructions that implements the circuit represented by
        the input permutations and gates. Note that the qubits are measured in the proper order
        such that the results may be directly compared to the simulated heavy hitters from
        collect_heavy_outputs.
    """
    num_measure_qubits = len(permutations[0])
    # at present, naively select the minimum number of qubits to run on
    qubits = qubits[:num_measure_qubits]

    # create a simple program that uses the compiler to directly generate 2q gates from the matrices
    prog = Program()
    for layer_idx, (perm, layer) in enumerate(zip(permutations, gates)):
        for gate_idx, gate in enumerate(layer):
            # get the Quil definition for the new gate
            g_definition = DefGate(
                "LYR" + str(layer_idx) + "_RAND" + str(gate_idx), gate)
            # get the gate constructor
            G = g_definition.get_constructor()
            # add definition to program
            prog += g_definition
            # add gate to program, acting on properly permuted qubits
            prog += G(int(qubits[perm[gate_idx]]),
                      int(qubits[perm[gate_idx + 1]]))

    ro = prog.declare("ro", "BIT", len(qubits))
    for idx, qubit in enumerate(qubits):
        prog.measure(qubit, ro[idx])

    native_quil = qc.compiler.quil_to_native_quil(prog)

    if not set(native_quil.get_qubits()).issubset(set(qubits)):
        raise ValueError(
            "naive_program_generator could not generate program using only the "
            "qubits supplied. Please provide your own program_generator if you wish "
            "to use only the qubits specified.")

    return native_quil
示例#10
0
def test_if_then_inherits_defined_gates():
    p1 = Program()
    p1.inst(H(0))
    p1.measure(0, 0)

    p2 = Program()
    p2.defgate("A", np.array([[1., 0.], [0., 1.]]))
    p2.inst(("A", 0))

    p3 = Program()
    p3.defgate("B", np.array([[0., 1.], [1., 0.]]))
    p3.inst(("B", 0))

    p1.if_then(0, p2, p3)
    assert p2.defined_gates[0] in p1.defined_gates
    assert p3.defined_gates[0] in p1.defined_gates
示例#11
0
def test_unitary_errors(qvm_unitary):
    # do we properly throw errors when non-gates are thrown into a unitary?

    # try measuring
    prog = Program()
    prog.inst([H(0), H(1)])
    prog.measure(0, [0])
    with pytest.raises(TypeError):
        qvm_unitary.unitary(prog)

    # try an undefined DefGate
    prog = Program()
    prog.defgate("hello", np.array([[0, 1], [1, 0]]))
    prog.inst(("hello2", 0))
    with pytest.raises(TypeError):
        qvm_unitary.unitary(prog)
示例#12
0
def test_if_then_inherits_defined_gates():
    p1 = Program()
    p1.inst(H(0))
    p1.measure(0, MemoryReference("ro", 0))

    p2 = Program()
    p2.defgate("A", np.array([[1.0, 0.0], [0.0, 1.0]]))
    p2.inst(("A", 0))

    p3 = Program()
    p3.defgate("B", np.array([[0.0, 1.0], [1.0, 0.0]]))
    p3.inst(("B", 0))

    p1.if_then(MemoryReference("ro", 0), p2, p3)
    assert p2.defined_gates[0] in p1.defined_gates
    assert p3.defined_gates[0] in p1.defined_gates
示例#13
0
def run_swap_test(programA, programB, num_measurement, quantum_resources,
                  classical_memory, ancilla):
    registerA = list(programA)
    registerB = list(programB)

    swap_test_program = Program()
    swap_test_program += programA + programB
    swap_test_program += swap_test_program(ancilla, registerA, registerB)
    ro = swap_test_program.declare('ro', 'BIT', 1)
    swap_test_program.measure(ancilla, [classical_memory])

    results = quantum_resources.run(swap_test_program,
                                    classical_memory,
                                    trials=num_measurement)
    probabiliy_of_one = np.mean(results)

    return 1 - 2 * probabiliy_of_one
示例#14
0
def User_circuit(problem,depth,qubits):#function presents user with available gates and makes them create their circuit layer by layer.

    available_gates=[]
    for gate in problem.instructions[:-len(qubits)]:
        available_gates.append(gate.name)
    
    shuffle(available_gates)

    solution=Program()

    for layer in range(depth):
        solution = layer_input(layer,available_gates,solution,qubits)

    for i in qubits:
        solution.measure(i,i)
        
    return solution
示例#15
0
def generate_2q_single_depth_experiment(rotation: Program,
                                        depth: int,
                                        exp_type: str,
                                        measurement_qubit: int,
                                        init_one: bool = False,
                                        axis: Tuple = None) -> Program:
    """
    A special variant of the 1q method that is specifically designed to calibrate a CPHASE gate. The
    ideal CPHASE is of the following form
        CPHASE(\phi) = diag(1,1,1,Exp[-i \phi]
    The imperfect CPHASE has two local Z rotations and a possible over (or under) rotation on the
    phase phi. Thus we have
        CPHASE(\Phi, \Theta_1, \Theta_2) = diag( exp(-a -b), exp(-a + b), exp(a-b), exp(a+b+c) )
        a = i \Theta_1 / 2,     b = i \Theta_2 / 2,     c = i \Phi

    The following experiments isolate the three angles using the state preparations |0>|+>, |+>|0>,
    |1>|+>, |+>|1> where the incurred phase is measured on the qubit initialized to the plus state.
    The four measurements are specified by setting the measurement qubit to either q1 or q2, and
    setting init_one to True indicating that the non-measurement qubit be prepared in the one state
    |1>.

    :param rotation: the program specifying the gate whose angle of rotation we wish to estimate.
    :param depth: the number of times we apply the rotation in the experiment
    :param exp_type: X or Y, specifying which operator to measure at the end of the experiment
    :param measurement_qubit: the qubit to be measured in this variant of the experiment
    :param axis: the axis of rotation. If none is specified, axis is assumed to be the Z axis. (rotation should be RZ)
    :param init_one: True iff the non-measurement qubit should be prepared in the 1 state.
    :param axis: the axis of rotation. If none is specified, axis is assumed to be the Z axis. (rotation should be RZ)
    :return: An estimate of some aspect of the CPHASE gate which depends on the measurement variant.
    """
    prog = Program()
    ro_bit = prog.declare("ro", "BIT", 1)
    qubits = rotation.get_qubits()
    non_measurement_qubit = list(qubits - {measurement_qubit})[0]
    prepare_state(prog, measurement_qubit)
    if init_one:
        prog.inst(X(non_measurement_qubit))
    for _ in range(depth):
        prog.inst(rotation)
    if axis:
        prog.inst(RZ(-axis[1], measurement_qubit))
        prog.inst(RY(-axis[0], measurement_qubit))
    local_pauli_eig_meas(prog, exp_type, measurement_qubit)
    prog.measure(measurement_qubit, ro_bit)
    return prog
示例#16
0
def deutsch_jozsa(f):
    # Determine number of qubits needed
    N = len(f)
    n = int(np.log2(N))

    # Invoking and renaming
    qvm = QVMConnection()
    p = Program()

    # Applying first round of n Hadamards
    for i in range(n):
        p.inst(H(i))

    # Defining the Oracle matrix
    U_f = np.eye(N)
    for i in range(N):
        if f[i] == '1':
            U_f[i][i] = -1
    # Adding the Oracle matrix as a gate
    p.defgate("Uf", U_f)
    # Applying Oracle gate
    p.inst(("Uf", ) + tuple(range(n)))

    # Applying second run of n Hadamards
    for i in range(n):
        p.inst(H(i))

    # Measure all the qubits and output result
    for i in range(n):
        p.measure(i, i)

    # Run the program
    classical_reg = list(range(n))
    results = qvm.run(p, classical_reg, 1)

    y = 0
    for i in range(n):
        y = y + 2**i * int(results[0][i])

    if y == 0:
        print('Function is constant.')
    else:
        print('Function is balanced.')
def n_qubits (number) :
    ''' takes as argument the number of qubits to apply Hadamard Gates to
    and measure. Outputs a concatenated string of measurements.'''
    q = Program()
    [q.inst(H(entry)) for entry in range(number)]
    [q.measure(entry, entry) for entry in range(number)]
    wavefunction3 = qvm.wavefunction(q, classical_addresses=range(number))
    classical_mem3 = wavefunction3.classical_memory
    #print (classical_mem3)
    return("".join([str(x) for x in classical_mem3]))
示例#18
0
def _run_rpe_program(qc: QuantumComputer, program: Program,
                     measure_qubits: Sequence[Sequence[int]],
                     num_shots: int) -> np.ndarray:
    """
    Simple helper to run a program with appropriate number of shots and return result.

    Note that the program is first compiled with basic_compile.

    :param qc: quantum computer to run program on
    :param program: program to run
    :param measure_qubits: all of the qubits to be measured after the program is run
    :param num_shots: number of shots of results to collect for the program
    :return: the results for all of the measure_qubits after running the program
    """
    prog = Program() + program  # make a copy of program
    meas_qubits = [qubit for qubits in measure_qubits for qubit in qubits]
    ro_bit = prog.declare("ro", "BIT", len(meas_qubits))
    for idx, q in enumerate(meas_qubits):
        prog.measure(q, ro_bit[idx])
    prog.wrap_in_numshots_loop(num_shots)
    executable = qc.compiler.native_quil_to_executable(basic_compile(prog))
    return qc.run(executable)
示例#19
0
def run_swap_test(program_a, program_b, number_of_measurements, quantum_resource,
                  classical_memory=0, ancilla=None):
    """
    Run a swap test and return the calculated overlap

    :param Program program_a: state preparation for the 'A' register
    :param Program program_b: state preparation for the 'B' register
    :param Int number_of_measurements: number of times to measure
    :param quantum_resource: QAM connection object
    :param Int classical_memory: location of classical memory slot to use
    :param ancilla: Index of ancilla
    :return: overlap of states prepared by program_a and program_b
    :rtype: float
    """
    register_a = list(program_a.get_qubits())
    register_b = list(program_b.get_qubits())
    if ancilla is None:
        ancilla = max(register_a + register_b) + 1

    swap_test_program = Program()
    swap_test_program += program_a + program_b
    swap_test_program += swap_circuit_generator(register_a, register_b, ancilla)
    swap_test_program.measure(ancilla, [classical_memory])

    # TODO: instead of number of measurements have user set precision of overlap
    # estimate and calculate number of shots to be within this precision
    results = quantum_resource.run(swap_test_program,
                                   classical_memory,
                                   trials=number_of_measurements)

    probability_of_one = np.mean(results)
    if probability_of_one > 0.5:
        raise ValueError("measurements indicate overlap is negative")

    estimated_overlap = np.sqrt(1 - 2 * probability_of_one)
    return estimated_overlap
示例#20
0
# teleportation circuit
# =============================================================================

# Alice wants to send |1> to Bob
qprog += gates.X(0)

# main circuit
qprog += [
    gates.H(1),
    gates.CNOT(1, 2),
    gates.CNOT(0, 1),
    gates.H(0),
    gates.MEASURE(0, creg[0]),
    gates.MEASURE(1, creg[1])
]

# conditional operations
qprog.if_then(creg[0], gates.Z(2))
qprog.if_then(creg[1], gates.X(2))

# measure qubit three
qprog.measure(2, creg[2])

# =============================================================================
# run the circuit and print the results. Note Bob always measures 1
# =============================================================================

print(qvm.run(qprog))

# print the quil code
print(qprog)
示例#21
0
def shor(N):
    # Check if number is even
    if N % 2 == 0:
        print('Even number.')
        return 2

    # Step 1: Chose 1 < a < N uniformly at random
    a = np.random.randint(2, N - 1)
    a = 2
    # Step 2: Compute b = gcd(a,N). If b > 1, output b and stop
    b = gcd(a, N)
    if b > 1:
        print('Factor found by guessing:', b)
        return b

    # Step 3: Find the order r of a modulo N for f(x) = a^x mod N
    # Quantum Part: using approximate periodicity to find r

    m = int(np.ceil(np.log2(N**2)))  # Size of first register
    M = 2**m  # M is the smallest power of 2 greater than N^2
    n = int(np.ceil(
        np.log2(N -
                1)))  # Size of second register - need to represent 0 to N-1

    # Set up connection and program
    qvm = QVMConnection()
    p = Program()
    # Labels for register 1 and 2
    reg_1 = range(m)  # First m qubits
    reg_2 = range(m, m + n)  # Last n qubits
    reg_all = range(m + n)  # Label for both registers

    # Apply QFT to first register
    for i in reg_1:
        p.inst(H(i))

    # Apply the oracle to both registers - need superposition of |x>|f(x)>
    oracle_matrix = bit_oracle(a, N, m, n)
    p.defgate("oracle", oracle_matrix)
    p.inst(("oracle", ) + tuple(reg_all))

    # Measure the second register
    for i in reg_2:
        p.measure(i, i)

    # Apply the qft to the first register
    p.inst(qft(reg_1))

    # Measure the first register
    for i in reg_1:
        p.measure(i, i)

    # Run the approximate peridicity algorithm
    classical_addresses = list(reg_all)
    results = qvm.run(p, classical_addresses, trials=1)

    # Determine output y of algorithm
    y = 0
    for i in reg_1:
        y = y + 2**i * results[0][i]

    # Use continued fraction expansion of z = y/M to find r
    r = Fraction(y, M).limit_denominator(N).denominator

    # If r is odd the algorithm fails
    if r % 2 == 1:
        print('Order r found is odd: algorithm failed')
        return 0

    # Step 4: Find factor of N
    s = gcd(a**(r / 2) - 1, N)
    if s == 1 or s == N:
        print('Factor found is 1 or', N, ': algorithm failed')
        return N

    print('Factor found by Shor\'s algorithm is', s, 'using', m + n, 'qubits')
    return s
示例#22
0
ORACLE_GATE_NAME = "GROVER_ORACLE"
gr_prog.defgate(ORACLE_GATE_NAME, oracle)

# Define inversion around the mean
DIFFUSION_GATE_NAME = "DIFFUSION"
diffusion = 2.0 * np.full((2**N, 2**N), 1/(2**N)) - np.eye(2**N)
gr_prog.defgate(DIFFUSION_GATE_NAME, diffusion)

# Number of algorithm iterations
N_ITER = int(np.pi / 4 * np.sqrt(2**N))

# Loop
for i in range(N_ITER):
    
    # \psi_2^i:  Apply Quantum Oracle
    gr_prog.inst(tuple([ORACLE_GATE_NAME] + qubits))
    #print(qvm.wavefunction(gr_prog))
    
    # \psi_3^i:  Apply Inversion around the mean
    gr_prog.inst(tuple([DIFFUSION_GATE_NAME] + qubits))
    #print(qvm.wavefunction(gr_prog))

# \psi_5: Measure
for q in qubits:
    gr_prog.measure(qubit_index=q, classical_reg=q)

# Run
ret = qvm.run(gr_prog, classical_addresses=qubits)
ret_string = ''.join([str(q) for q in ret[0]])
print("The searched string is: {}".format(ret_string))
示例#23
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)
示例#24
0
        if score < 10:
            a = np.sqrt(1 / 2.)
        elif (score >= 10) and (score < 20):
            a = np.sqrt(3 / 4.)
        else:
            a = np.sqrt(1.)
        b = np.sqrt(1 - np.square(a))
        Uf_ = np.array([[a, b], [b, -a]])
        p.defgate("Uf", Uf_)
        # set dartboard_A center, and calculate results_B in either case
        if results_A == [[0]]:
            dartboard_A_center = [size_x // 2, size_y // 2 - dartboard_offset]
            # run the program for this case
            p.inst(I(0))
            p.inst(("Uf", 0))
            p.measure(0, [0])
            results_B = cxn.run(p, [0])
        elif results_A == [[1]]:
            dartboard_A_center = [size_x // 2, size_y // 2 + dartboard_offset]
            # run the program for this case
            p.inst(X(0))
            p.inst(("Uf", 0))
            p.measure(0, [0])
            results_B = cxn.run(p, [0])

    elif color_code % 3 == 1:
        screen.fill(red)
        if len(results_A) > 0:
            results_A.pop()
        # run the common parts of the program
        p = Program()
示例#25
0
p.inst(X(0))
p.inst(H(0))

# Apply H^(\otimes n)
for n_ in range(1, n + 1):
    p.inst(H(n_))

# Apply U_f
p.inst(("U_f", ) + tuple(range(n + 1)[::-1]))

# Apply final H^(\otimes n)
for n_ in range(1, n + 1):
    p.inst(H(n_))

# Final measurement
classical_regs = list(range(n))
for i, n_ in enumerate(list(range(1, n + 1))[::-1]):
    p.measure(n_, classical_regs[i])

qvm = api.QVMConnection()
measure_n_qubits = qvm.run(p, classical_regs)

# flatten out list
measure_n_qubits = [item for sublist in measure_n_qubits for item in sublist]

# Determine if function is balanced or not
if set(measure_n_qubits) == set([0, 1]):
    print("Function is balanced")
elif set(measure_n_qubits) == set([0]):
    print("Function is constant")
示例#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)
示例#27
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)
示例#28
0
#!/usr/bin/env python3
from pyquil.quil import Program
from pyquil.api import QVMConnection
from pyquil.gates import X, Z, H
from compile_for_pyquil import compiletoquil

# Q in binary
bitstring = '01010001'

# Do quantum stuff now we have our bit string
qvm = QVMConnection()
qprog = Program()

# do X on q1, q3, q7
# recall H Z H is X
qprog.inst(H(1), Z(1), H(1))
qprog.inst(X(3))
qprog.inst(X(7))

# do measurement over all 8 qubits
for i in range(0, 8):
    qprog.measure(i, i)

# store measurement outcomes
results = qvm.run(qprog)

# show info when compiled to 8 qubit AGAVE
compiletoquil(qprog)

print('# Result =', results[0])
示例#29
0
# 1. Calling Libraries
from pyquil.quil  import Program 
from pyquil.api   import QVMConnection 
from pyquil.gates import X, CCNOT

# 2. Initialising the program
qvm = QVMConnection()
p = Program()

# 3. Applying gates
p.inst(X(0),X(1),X(2)) # so here 111
p.inst(CCNOT(0,1,2)) 

# 4. Performing measurements
p.measure(0,0)
p.measure(1,1)
p.measure(2,2)

# 5. Executing the program
results = qvm.run(p, [], 4)
print(results)
示例#30
0
if __name__ == '__main__':
    agave = get_devices(as_dict=True)['8Q-Agave']
    qpu = QPUConnection(agave)  # Physical QPU
    compiler = CompilerConnection(agave)

    p = Program()

    p.inst(X(0))
    p.inst(X(0))
    p.inst(X(1))
    p.inst(X(2))
    p.inst(X(3))
    p.inst(X(4))
    p.inst(X(5))
    p.measure(0, 0)
    p.measure(1, 1)
    p.measure(2, 2)
    p.measure(3, 3)
    p.measure(4, 4)
    p.measure(5, 5)
    data_qpu = qpu.run(p, trials=100)
    print(distribution(data_qpu))
    # print(data_qpu.ge)

    # Should measure number of errors (bit flips). Can be different for different qubits, too
    p = Program("""#   prepare a Bell state
H 0
CNOT 0 1
#   wait a while
PRAGMA PRESERVE_BLOCK
示例#31
0
from pyquil.quil import Program
from pyquil.api import QVMConnection
from pyquil.gates import H, PHASE

from pyquilcompiler import compiletoquil

import numpy as np
# Invoking and renaming
qvm = QVMConnection()
p = Program()
# Gate implementation
p.inst(H(0))
theta = np.pi / 2
p.inst(PHASE(theta, 0))

# Measurement
p.measure(0, 0)
p.measure(1, 1)
# Running the program

compiletoquil(p)

cr = []
results = qvm.run(p, cr, 4)
print(results)