def postoptimize(prog):
    dev = Rget_devices(as_dict=True)['8Q-Agave']
    comp = CompilerConnection(device=dev)
    pp1 = comp.compile(prog)

    for i in range(0):

        change = False

        ne_inst = []
        for inst in pp1.instructions:
            if type(inst) is Gate:
                if inst.name == 'RZ':
                    angle = inst.params[0] % 2 * pi
                    print('RZ angle: ', angle, angle % 2 * pi)
                    if min(angle, 2 * pi - angle) < 1e-3:
                        change = True
                        print('Removing.')
                        continue

            ne_inst.append(inst)

        if not change:
            break

        #print('Recompiling...')

        pp1 = comp.compile(pq.Program(ne_inst))

    return pp1
Example #2
0
def compile_INIT_gate(prog):
    compiler = CompilerConnection(acorn)
    compiledProg = compiler.compile(prog)
    qpuProg = Program()
    qpuProg.inst(compiledProg)

    return qpuProg
Example #3
0
def compiler():
    try:
        compiler = CompilerConnection(isa_source=ISA.from_dict(isa_dict()))
        compiler.compile(Program(I(0)))
        return compiler
    except (RequestException, UnknownApiError) as e:
        return pytest.skip(
            "This test requires compiler connection: {}".format(e))
Example #4
0
def compiletoquil(myprogram):
    devices = get_devices(as_dict=True)
    agave = devices['8Q-Agave']
    compiler = CompilerConnection(agave)

    print('\n# Original pyQuil program,\n\n', myprogram)

    job_id = compiler.compile_async(myprogram)
    job = compiler.wait_for_job(job_id)

    print('\n# Compiled quil code,\n\n', 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())
    print('\n# End of compiling info\n')

    return  #myprogram, job.compiled_quil()
from pyquil.gates import *
from math import pi
from pyquil.paulis import *
from pyquil.api import QVMConnection, QPUConnection, CompilerConnection
import pickle
import json

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

from pyquil.api import get_devices

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

compiler = CompilerConnection(acorn)
devices = get_devices(as_dict=True)
acorn = devices['19Q-Acorn']
compiler = CompilerConnection(acorn)

comp_gates = {
    'RX(-pi/2) 0': 'RX(pi/2) 0',
    'RZ(-pi/2) 0': 'RZ(pi/2) 0',
    'RX(pi/2) 0': 'RX(-pi/2) 0',
    'RZ(pi/2) 0': 'RZ(-pi/2) 0'
}

paulis = {
    'RX(-pi) 0': 'RX(pi) 0',
    'RZ(-pi) 0': 'RZ(pi) 0',
    'RX(pi) 0': 'RX(-pi) 0',
Example #6
0
def test_compiler_without_isa():
    with pytest.raises(ValueError):
        CompilerConnection().compile(Program())
Example #7
0
    RZ(-pi / 2, 1),
    RX(pi / 2, 1),
    CZ(1, 0),
    RZ(-pi / 2, 0),
    RX(-pi / 2, 1),
    RZ(pi / 2, 1),
    Pragma("CURRENT_REWIRING", ('"#(0 1 2 3)"',)),
    Pragma("EXPECTED_REWIRING", ('"#(0 1 2 3)"',)),
    Pragma("CURRENT_REWIRING", ('"#(0 1 2 3)"',)),
])
DUMMY_ISA_DICT = {"1Q": {"0": {}, "1": {}}, "2Q": {"0-1": {}}}
DUMMY_ISA = ISA.from_dict(DUMMY_ISA_DICT)

mock_qvm = QVMConnection(api_key='api_key', user_id='user_id')
mock_async_qvm = QVMConnection(api_key='api_key', user_id='user_id', use_queue=True)
mock_compiler = CompilerConnection(isa_source=DUMMY_ISA, api_key='api_key', user_id='user_id')
mock_async_compiler = CompilerConnection(isa_source=DUMMY_ISA, api_key='api_key', user_id='user_id', use_queue=True)


def test_sync_run_mock():
    def mock_response(request, context):
        assert json.loads(request.text) == {
            "type": "multishot",
            "addresses": [0, 1],
            "trials": 2,
            "compiled-quil": "H 0\nCNOT 0 1\nMEASURE 0 [0]\nMEASURE 1 [1]\n"
        }
        return '[[0,0],[1,1]]'

    with requests_mock.Mocker() as m:
        m.post('https://api.rigetti.com/qvm', text=mock_response)
Example #8
0
from pyquil.api import CompilerConnection, get_devices
from pyquil.gates import X, H, CNOT, MEASURE
from pyquil.quil import Program

program = Program(
    # put your program here...
    X(0), )

agave = get_devices(as_dict=True)['8Q-Agave']
compiler = CompilerConnection(device=agave)
compiled = compiler.compile(program)

print(compiled)
Example #9
0
def distribution(data):
    """ Distribution of measurement of quantum system """
    combinations = {}
    for result in data:
        result_as_tuple = tuple(result)
        if result_as_tuple not in combinations:
            combinations[result_as_tuple] = 0
        combinations[result_as_tuple] += 1
    return combinations


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)
Example #10
0
def toy_piano_counterpoint():
    pitch_index = int(request.args['pitch_index'])
    pitch_index %= (DIATONIC_SCALE_OCTAVE_PITCHES - 1)
    if pitch_index >= NUM_PITCHES:
        pitch_index = 0

    species = int(request.args['species'])
    #print("species: ", species)

    melodic_degrees = request.args['melodic_degrees'].split(",")
    #print("melodic_degrees: ", melodic_degrees)

    harmonic_degrees = request.args['harmonic_degrees'].split(",")
    #print("harmonic_degrees: ", harmonic_degrees)

    use_simulator = request.args['use_simulator'].lower() == "true"
    print("use_simulator: ", use_simulator)

    compiler = None
    quantum_device = None
    q_con = None

    if use_simulator:
        q_con = api.QVMConnection()
    else:
        quantum_device = available_quantum_device()
        if quantum_device is not None:
            print('quantum_device: ', quantum_device)
            compiler = CompilerConnection(quantum_device)
            q_con = api.QPUConnection(quantum_device)

            # q_con = api.QVMConnection()
        else:
            # TODO: Test this condition
            print('No quantum devices available, using simulator')
            use_simulator = True
            q_con = api.QVMConnection()

    if (len(melodic_degrees) == DEGREES_OF_FREEDOM
            and len(harmonic_degrees) == DEGREES_OF_FREEDOM
            and 1 <= species <= 3 and 0 <= pitch_index < NUM_PITCHES):

        #TODO: Move/change this
        rot_melodic_circuit = compute_circuit(melodic_degrees)

        if not use_simulator:
            # TODO: Put back in
            # rot_melodic_circuit = compiler.compile(rot_melodic_circuit)

            # TODO: Remove these lines
            tmp_rot_melodic_circuit = compiler.compile(rot_melodic_circuit)
            # print("tmp_rot_melodic_circuit:")
            # print(tmp_rot_melodic_circuit)
            rot_melodic_circuit = Program()
            for instruction in tmp_rot_melodic_circuit.instructions:
                if not isinstance(instruction, Pragma):
                    rot_melodic_circuit.inst(instruction)

        print("rot_melodic_circuit:")
        print(rot_melodic_circuit)

        rot_harmonic_circuit = compute_circuit(harmonic_degrees)

        if not use_simulator:
            # TODO: Put back in
            # rot_harmonic_circuit = compiler.compile(rot_harmonic_circuit)

            # TODO: Remove these lines
            tmp_rot_harmonic_circuit = compiler.compile(rot_harmonic_circuit)
            # print("tmp_rot_harmonic_circuit:")
            # print(tmp_rot_harmonic_circuit)
            rot_harmonic_circuit = Program()
            for instruction in tmp_rot_harmonic_circuit.instructions:
                if not isinstance(instruction, Pragma):
                    rot_harmonic_circuit.inst(instruction)

        print("rot_harmonic_circuit:")
        print(rot_harmonic_circuit)

        harmony_notes_factor = 2**(
            species - 1)  # Number of harmony notes for each melody note
        num_composition_bits = TOTAL_MELODY_NOTES * (harmony_notes_factor +
                                                     1) * NUM_CIRCUIT_WIRES

        composition_bits = [0] * num_composition_bits

        # Convert the pitch index to a binary string, and place into the
        # composition_bits array, least significant bits in lowest elements of array
        qubit_string = format(pitch_index, '03b')
        for idx, qubit_char in enumerate(qubit_string):
            if qubit_char == '0':
                composition_bits[idx] = 0
            else:
                composition_bits[idx] = 1

        num_runs = 1

        # Compute notes for the main melody
        for melody_note_idx in range(0, TOTAL_MELODY_NOTES):
            #
            if (melody_note_idx < TOTAL_MELODY_NOTES - 1):
                p = Program()

                for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                    if (composition_bits[melody_note_idx * NUM_CIRCUIT_WIRES +
                                         bit_idx] == 0):
                        p.inst(I(NUM_CIRCUIT_WIRES - 1 - bit_idx))
                    else:
                        p.inst(X(NUM_CIRCUIT_WIRES - 1 - bit_idx))

                p.inst(copy.deepcopy(rot_melodic_circuit))
                p.inst().measure(0, 0).measure(1, 1) \
                    .measure(2, 2)
                # print("rot_melodic_circuit:")
                # print(p)

                result = q_con.run(p, [2, 1, 0], num_runs)
                bits = result[0]
                for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                    composition_bits[(melody_note_idx + 1) * NUM_CIRCUIT_WIRES
                                     + bit_idx] = bits[bit_idx]

                #print(composition_bits)

                measured_pitch = bits[0] * 4 + bits[1] * 2 + bits[2]
                #print("melody melody_note_idx measured_pitch")
                #print(melody_note_idx)
                #print(measured_pitch)

            # Now compute a harmony note for the melody note
            #print("Now compute a harmony note for the melody notev")
            p = Program()

            for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                if composition_bits[melody_note_idx * NUM_CIRCUIT_WIRES +
                                    bit_idx] == 0:
                    p.inst(I(NUM_CIRCUIT_WIRES - 1 - bit_idx))
                else:
                    p.inst(X(NUM_CIRCUIT_WIRES - 1 - bit_idx))

            p.inst(copy.deepcopy(rot_harmonic_circuit))
            p.inst().measure(0, 0).measure(1, 1) \
                .measure(2, 2)
            # print("rot_harmonic_circuit:")
            # print(p)

            result = q_con.run(p, [2, 1, 0], num_runs)
            bits = result[0]
            for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                composition_bits[(melody_note_idx * NUM_CIRCUIT_WIRES *
                                  harmony_notes_factor) +
                                 (TOTAL_MELODY_NOTES * NUM_CIRCUIT_WIRES) +
                                 bit_idx] = bits[bit_idx]

            #print(composition_bits)

            measured_pitch = bits[0] * 4 + bits[1] * 2 + bits[2]
            #print("harmony melody_note_idx measured_pitch")
            #print(melody_note_idx)
            #print(measured_pitch)

            # Now compute melody notes to follow the harmony note
            #print("Now compute melody notes to follow the harmony note")
            for harmony_note_idx in range(1, harmony_notes_factor):
                p = Program()

                for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                    if (composition_bits[
                        (melody_note_idx * NUM_CIRCUIT_WIRES *
                         harmony_notes_factor) +
                        ((harmony_note_idx - 1) * NUM_CIRCUIT_WIRES) +
                        (TOTAL_MELODY_NOTES * NUM_CIRCUIT_WIRES) +
                            bit_idx] == 0):
                        p.inst(I(NUM_CIRCUIT_WIRES - 1 - bit_idx))
                    else:
                        p.inst(X(NUM_CIRCUIT_WIRES - 1 - bit_idx))

                p.inst(copy.deepcopy(rot_melodic_circuit))
                p.inst().measure(0, 0).measure(1, 1) \
                    .measure(2, 2)
                #print("rot_melodic_circuit:")
                #print(p)

                result = q_con.run(p, [2, 1, 0], num_runs)
                bits = result[0]
                for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                    composition_bits[(melody_note_idx * NUM_CIRCUIT_WIRES *
                                      harmony_notes_factor) +
                                     ((harmony_note_idx) * NUM_CIRCUIT_WIRES) +
                                     (TOTAL_MELODY_NOTES * NUM_CIRCUIT_WIRES) +
                                     bit_idx] = bits[bit_idx]

                #print(composition_bits)

                measured_pitch = bits[0] * 4 + bits[1] * 2 + bits[2]
                #print("melody after harmony melody_note_idx measured_pitch")
                #print(melody_note_idx)
                #print(measured_pitch)

        all_note_nums = create_note_nums_array(composition_bits)
        melody_note_nums = all_note_nums[0:TOTAL_MELODY_NOTES]
        harmony_note_nums = all_note_nums[7:num_composition_bits]

    if use_simulator:
        composer = "Rigetti QVM"
    else:
        composer = "Rigetti " + "8Q-Agave"

    ret_dict = {
        "melody": melody_note_nums,
        "harmony": harmony_note_nums,
        "lilypond": create_lilypond(melody_note_nums, harmony_note_nums,
                                    composer),
        "toy_piano": create_toy_piano(melody_note_nums, harmony_note_nums)
    }

    return jsonify(ret_dict)
from pyquil.api import CompilerConnection, QVMConnection, get_devices
from pyquil.quil import Program
from pyquil.gates import H, X, CNOT

devices = get_devices(as_dict=True)
print(devices)

acorn = devices['19Q-Acorn']
compiler = CompilerConnection(acorn)

prog = Program()
prog.inst(H(0))
prog.inst(H(2))
prog.inst(CNOT(0, 1))
prog.inst(CNOT(1, 2))

job_id = compiler.compile_async(prog)
job = compiler.wait_for_job(job_id)

print('program fidelity', job.program_fidelity())
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),
        ))
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),
            ))