How to use the pyquil.quil.Program function in pyquil

To help you get started, we’ve selected a few pyquil examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rigetti / reference-qvm / tests / test_wavefunction.py View on Github external
def test_belltest(qvm):
    """
    Generate a bell state with fake qvm and qvm and compare
    """
    prog = Program().inst([Hgate(0), CNOTgate(0, 1)])
    bellout, _ = qvm.wavefunction(prog)
    bell = np.zeros((4, 1))
    bell[0, 0] = bell[-1, 0] = 1.0 / np.sqrt(2)
    assert np.allclose(bellout.amplitudes, bell)
github entropicalabs / entropica_qaoa / tests / test_optimizer2.py View on Github external
from pyquil.paulis import PauliSum, PauliTerm
from pyquil.api import WavefunctionSimulator, local_qvm, get_qc
from pyquil.quil import Program
from pyquil.gates import RX, CNOT

from forest_qaoa.vqe.optimizer import scipy_optimizer
from forest_qaoa.vqe.cost_function import (PrepareAndMeasureOnWFSim,
                                           PrepareAndMeasureOnQVM)
from forest_qaoa.qaoa.cost_function import QAOACostFunctionOnWFSim
from forest_qaoa.qaoa.parameters import FourierParams

#hamiltonian = PauliSum.from_compact_str("(-1.0)*Z0*Z1 + 0.8*Z0 + (-0.5)*Z1")

hamiltonian = PauliSum([PauliTerm("Z", 0, -1.0) * PauliTerm("Z", 1, 1.0),
                        PauliTerm("Z", 0, 0.8), PauliTerm("Z", 1, -0.5)])
prepare_ansatz = Program()
params = prepare_ansatz.declare("params", memory_type="REAL", memory_size=4)
prepare_ansatz.inst(RX(params[0], 0))
prepare_ansatz.inst(RX(params[1], 1))
prepare_ansatz.inst(CNOT(0, 1))
prepare_ansatz.inst(RX(params[2], 0))
prepare_ansatz.inst(RX(params[3], 1))

p0 = [0, 0, 0, 0]


def test_vqe_on_WFSim():
    sim = WavefunctionSimulator()
    cost_fun = PrepareAndMeasureOnWFSim(prepare_ansatz=prepare_ansatz,
                                        make_memory_map=lambda p: {"params": p},
                                        hamiltonian=hamiltonian,
                                        sim=sim,
github rigetti / pyquil / pyquil / noise.py View on Github external
"""
    Generate the header for a pyquil Program that uses ``noise_model`` to overload noisy gates.
    The program header consists of 3 sections:

        - The ``DEFGATE`` statements that define the meaning of the newly introduced "noisy" gate
          names.
        - The ``PRAGMA ADD-KRAUS`` statements to overload these noisy gates on specific qubit
          targets with their noisy implementation.
        - THe ``PRAGMA READOUT-POVM`` statements that define the noisy readout per qubit.

    :param noise_model: The assumed noise model.
    :return: A quil Program with the noise pragmas.
    """
    from pyquil.quil import Program

    p = Program()
    defgates: Set[str] = set()
    for k in noise_model.gates:

        # obtain ideal gate matrix and new, noisy name by looking it up in the NOISY_GATES dict
        try:
            ideal_gate, new_name = get_noisy_gate(k.gate, tuple(k.params))

            # if ideal version of gate has not yet been DEFGATE'd, do this
            if new_name not in defgates:
                p.defgate(new_name, ideal_gate)
                defgates.add(new_name)
        except NoisyGateUndefined:
            print(
                "WARNING: Could not find ideal gate definition for gate {}".format(k.gate),
                file=sys.stderr,
            )
github rigetti / pyquil / pyquil / paulis.py View on Github external
the pauli_term object, i.e. exp[-1.0j * param * pauli_term]

    :param PauliTerm pauli_term: A PauliTerm to exponentiate
    :param float param: scalar, non-complex, value
    :returns: A Quil program object
    :rtype: Program
    """

    def reverse_hack(p: Program) -> Program:
        # A hack to produce a *temporary* program which reverses p.
        revp = Program()
        revp.inst(list(reversed(p.instructions)))
        return revp

    quil_prog = Program()
    change_to_z_basis = Program()
    change_to_original_basis = Program()
    cnot_seq = Program()
    prev_index = None
    highest_target_index = None

    for index, op in pauli_term:
        if "X" == op:
            change_to_z_basis.inst(H(index))
            change_to_original_basis.inst(H(index))

        elif "Y" == op:
            change_to_z_basis.inst(RX(np.pi / 2.0, index))
            change_to_original_basis.inst(RX(-np.pi / 2.0, index))

        elif "I" == op:
            continue
github rigetti / pyquil / pyquil / api / qpu.py View on Github external
def _run_and_measure_payload(self, quil_program, qubits, trials, needs_compilation, isa):
        # Developer note: Don't migrate this code to `ForestConnection`. The QPU run_and_measure
        # web endpoint is deprecated. If run_and_measure-type functionality is desired,
        # the client (ie PyQuil) should add measure instructions and hit the `run` endpoint. See
        # `QuantumComputer.run_and_measure` for an example.
        if not quil_program:
            raise ValueError("You have attempted to run an empty program."
                             " Please provide gates or measure instructions to your program.")

        if not isinstance(quil_program, Program):
            raise TypeError('quil_program must be a Quil program object')
        validate_run_items(qubits)
        if not isinstance(trials, integer_types):
            raise TypeError('trials must be an integer')

        payload = {'type': TYPE_MULTISHOT_MEASURE,
                   'qubits': list(qubits),
                   'trials': trials}

        if needs_compilation:
            payload['uncompiled-quil'] = quil_program.out()
            if isa:
                payload['target-device'] = {"isa": isa.to_dict()}
        else:
            payload['compiled-quil'] = quil_program.out()
github rigetti / pyquil / pyquil / api / _persistent_qvm.py View on Github external
def run_program(self, quil_program: Program) -> Dict[str, np.array]:
        """
        Run quil_program on this PersistentQVM instance, and return the values stored in all of the
        classical registers assigned to by the program.

        :param quil_program: the Quil program to run.

        :return: A Dict mapping classical memory names to values.
        """
        if not isinstance(quil_program, Program):
            raise TypeError(f"quil_program must be a Quil Program. Got {quil_program}.")

        classical_addresses = get_classical_addresses_from_program(quil_program)
        return self.connection._qvm_ng_run_program(quil_program=quil_program,
                                                   qvm_token=self.token,
                                                   simulation_method=None,
                                                   allocation_method=None,
                                                   classical_addresses=classical_addresses,
                                                   measurement_noise=None,
                                                   gate_noise=None,
                                                   random_seed=self.random_seed)
github JackHidary / quantumcomputingbook / chapter10 / pyquil / random-walk.py View on Github external
def k_4_ctqw(t):
    """Returns a program implementing a continuous time quantum walk."""
    prog = pq.Program()
    
    # Change to diagonal basis
    prog.inst(H(0))
    prog.inst(H(1))
    
    # Time evolve
    prog.inst(CPHASE00(-4*t, 0, 1))
    
    # Change back to computational basis
    prog.inst(H(0))
    prog.inst(H(1))
    
    return prog
github rigetti / pyquil / pyquil / paulis.py View on Github external
:param PauliTerm pauli_term: A PauliTerm to exponentiate
    :param float param: scalar, non-complex, value
    :returns: A Quil program object
    :rtype: Program
    """

    def reverse_hack(p: Program) -> Program:
        # A hack to produce a *temporary* program which reverses p.
        revp = Program()
        revp.inst(list(reversed(p.instructions)))
        return revp

    quil_prog = Program()
    change_to_z_basis = Program()
    change_to_original_basis = Program()
    cnot_seq = Program()
    prev_index = None
    highest_target_index = None

    for index, op in pauli_term:
        if "X" == op:
            change_to_z_basis.inst(H(index))
            change_to_original_basis.inst(H(index))

        elif "Y" == op:
            change_to_z_basis.inst(RX(np.pi / 2.0, index))
            change_to_original_basis.inst(RX(-np.pi / 2.0, index))

        elif "I" == op:
            continue

        if prev_index is not None: