コード例 #1
0
    def __init__(self,
                 endpoint: str,
                 device: AbstractDevice,
                 timeout: int = 10,
                 name: Optional[str] = None) -> None:
        """
        Client to communicate with the Compiler Server.

        :param endpoint: TCP or IPC endpoint of the Compiler Server
        :param device: PyQuil Device object to use as compilation target
        :param timeout: Number of seconds to wait for a response from the client.
        :param name: Name of the lattice being targeted
        """

        if not endpoint.startswith('tcp://'):
            raise ValueError(
                f"PyQuil versions >= 2.4 can only talk to quilc "
                f"versions >= 1.4 over network RPCQ.  You've supplied the "
                f"endpoint '{endpoint}', but this doesn't look like a network "
                f"ZeroMQ address, which has the form 'tcp://domain:port'. "
                f"You might try clearing (or correcting) your COMPILER_URL "
                f"environment variable and removing (or correcting) the "
                f"compiler_server_address line from your .forest_config file.")

        self.client = Client(endpoint, timeout=timeout)
        self.target_device = TargetDevice(isa=device.get_isa().to_dict(),
                                          specs=device.get_specs().to_dict())
        self.name = name
コード例 #2
0
    def __init__(self,
                 endpoint: str,
                 device: AbstractDevice,
                 timeout: float = 10) -> None:
        """
        Client to communicate with the Compiler Server.

        :param endpoint: TCP or IPC endpoint of the Compiler Server
        :param device: PyQuil Device object to use as compilation target
        """

        if not endpoint.startswith("tcp://"):
            raise ValueError(
                f"PyQuil versions >= 2.4 can only talk to quilc "
                f"versions >= 1.4 over network RPCQ.  You've supplied the "
                f"endpoint '{endpoint}', but this doesn't look like a network "
                f"ZeroMQ address, which has the form 'tcp://domain:port'. "
                f"You might try clearing (or correcting) your COMPILER_URL "
                f"environment variable and removing (or correcting) the "
                f"compiler_server_address line from your .forest_config file.")

        self.endpoint = endpoint
        self.client = Client(endpoint, timeout=timeout)
        td = TargetDevice(isa=device.get_isa().to_dict(),
                          specs=None)  # type: ignore
        self.target_device = td

        try:
            self.connect()
        except QuilcNotRunning as e:
            warnings.warn(
                f"{e}. Compilation using quilc will not be available.")
コード例 #3
0
    def __init__(
        self,
        quilc_endpoint: Optional[str],
        qpu_compiler_endpoint: Optional[str],
        device: AbstractDevice,
        timeout: int = 10,
        name: Optional[str] = None,
        *,
        session: Optional[ForestSession] = None,
    ) -> None:
        """
        Client to communicate with the Compiler Server.

        :param quilc_endpoint: TCP or IPC endpoint of the Quil Compiler (quilc).
        :param qpu_compiler_endpoint: TCP or IPC endpoint of the QPU Compiler.
        :param device: PyQuil Device object to use as compilation target.
        :param timeout: Number of seconds to wait for a response from the client.
        :param name: Name of the lattice being targeted.
        :param session: ForestSession object, which manages engagement and configuration.
        """

        if not (session or (quilc_endpoint and qpu_compiler_endpoint)):
            raise ValueError(
                "QPUCompiler requires either `session` or both of `quilc_endpoint` and "
                "`qpu_compiler_endpoint`.")

        self.session = session
        self.timeout = timeout

        _quilc_endpoint = quilc_endpoint or self.session.config.quilc_url

        if not _quilc_endpoint.startswith("tcp://"):
            raise ValueError(
                f"PyQuil versions >= 2.4 can only talk to quilc "
                f"versions >= 1.4 over network RPCQ.  You've supplied the "
                f"endpoint '{quilc_endpoint}', but this doesn't look like a network "
                f"ZeroMQ address, which has the form 'tcp://domain:port'. "
                f"You might try clearing (or correcting) your COMPILER_URL "
                f"environment variable and removing (or correcting) the "
                f"compiler_server_address line from your .forest_config file.")

        self.quilc_client = Client(_quilc_endpoint, timeout=timeout)

        self.qpu_compiler_endpoint = qpu_compiler_endpoint
        self._qpu_compiler_client = None

        self._device = device
        self.target_device = TargetDevice(isa=device.get_isa().to_dict(),
                                          specs=None)
        self.name = name

        try:
            self.connect()
        except QuilcNotRunning as e:
            warnings.warn(
                f"{e}. Compilation using quilc will not be available.")
        except QPUCompilerNotRunning as e:
            warnings.warn(
                f"{e}. Compilation using the QPU compiler will not be available."
            )
コード例 #4
0
ファイル: _compiler.py プロジェクト: timasq/pyquil
    def __init__(self, endpoint: str, device: AbstractDevice) -> None:
        """
        Client to communicate with the Compiler Server.

        :param endpoint: TCP or IPC endpoint of the Compiler Server
        :param device: PyQuil Device object to use as compilation target
        """
        self.client = Client(endpoint)
        self.target_device = TargetDevice(isa=device.get_isa().to_dict(),
                                          specs=device.get_specs().to_dict())
コード例 #5
0
    def __init__(self, endpoint: str, device: AbstractDevice, timeout: int = 10) -> None:
        """
        Client to communicate with the Compiler Server.

        :param endpoint: TCP or IPC endpoint of the Compiler Server
        :param device: PyQuil Device object to use as compilation target
        :param timeout: Number of seconds to wait for a response from the client.
        """

        self.client = Client(endpoint, timeout=timeout)
        self.target_device = TargetDevice(isa=device.get_isa().to_dict(),
                                          specs=device.get_specs().to_dict())
コード例 #6
0
ファイル: _compiler.py プロジェクト: tim-yit-chen/pyquil
    def __init__(self,
                 quilc_endpoint: str,
                 qpu_compiler_endpoint: Optional[str],
                 device: AbstractDevice,
                 timeout: int = 10,
                 name: Optional[str] = None) -> None:
        """
        Client to communicate with the Compiler Server.

        :param quilc_endpoint: TCP or IPC endpoint of the Quil Compiler (quilc)
        :param qpu_compiler_endpoint: TCP or IPC endpoint of the QPU Compiler
        :param device: PyQuil Device object to use as compilation target
        :param timeout: Number of seconds to wait for a response from the client.
        :param name: Name of the lattice being targeted
        """

        if not quilc_endpoint.startswith('tcp://'):
            raise ValueError(
                f"PyQuil versions >= 2.4 can only talk to quilc "
                f"versions >= 1.4 over network RPCQ.  You've supplied the "
                f"endpoint '{quilc_endpoint}', but this doesn't look like a network "
                f"ZeroMQ address, which has the form 'tcp://domain:port'. "
                f"You might try clearing (or correcting) your COMPILER_URL "
                f"environment variable and removing (or correcting) the "
                f"compiler_server_address line from your .forest_config file.")

        self.quilc_client = Client(quilc_endpoint, timeout=timeout)
        if qpu_compiler_endpoint is not None:
            self.qpu_compiler_client = Client(qpu_compiler_endpoint,
                                              timeout=timeout)
        else:
            self.qpu_compiler_client = None
            warnings.warn(
                "It looks like you are initializing a QPUCompiler object without a "
                "qpu_compiler_address. If you didn't do this manually, then "
                "you probably don't have a qpu_compiler_address entry in your "
                "~/.forest_config file, meaning that you are not engaged to the QPU."
            )
        self.target_device = TargetDevice(isa=device.get_isa().to_dict(),
                                          specs=device.get_specs().to_dict())
        self.name = name

        try:
            self.connect()
        except QuilcNotRunning as e:
            warnings.warn(
                f'{e}. Compilation using quilc will not be available.')
        except QPUCompilerNotRunning as e:
            warnings.warn(
                f'{e}. Compilation using the QPU compiler will not be available.'
            )
コード例 #7
0
def _naive_program_generator(qc: QuantumComputer, qubits: Sequence[int],
                             permutations: Sequence[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.
    """
    # artificially restrict the entire computation to num_measure_qubits
    num_measure_qubits = len(permutations[0])
    # if these measure_qubits do not have a topology that supports the program, the compiler may
    # act on a different (potentially larger) subset of the input sequence of qubits.
    measure_qubits = qubits[:num_measure_qubits]

    # create a simple program that uses the compiler to directly generate 2q gates from the matrices
    prog = Program(Pragma('INITIAL_REWIRING', ['"PARTIAL"']))
    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(measure_qubits[perm[gate_idx]]),
                      int(measure_qubits[perm[gate_idx + 1]]))

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

    # restrict compilation to chosen qubits
    isa_dict = qc.device.get_isa().to_dict()
    single_qs = isa_dict['1Q']
    two_qs = isa_dict['2Q']

    new_1q = {}
    for key, val in single_qs.items():
        if int(key) in qubits:
            new_1q[key] = val
    new_2q = {}
    for key, val in two_qs.items():
        q1, q2 = key.split('-')
        if int(q1) in qubits and int(q2) in qubits:
            new_2q[key] = val

    new_isa = {'1Q': new_1q, '2Q': new_2q}

    new_compiler = copy(qc.compiler)
    new_compiler.target_device = TargetDevice(
        isa=new_isa, specs=qc.device.get_specs().to_dict())
    # try to compile with the restricted qubit topology
    try:
        native_quil = new_compiler.quil_to_native_quil(prog)
    except RPCErrorError as e:
        if "Multiqubit instruction requested between disconnected components of the QPU graph:" \
                in str(e):
            raise ValueError(
                "naive_program_generator could not generate a program using only the "
                "qubits supplied; expand the set of allowed qubits or supply "
                "a custom program_generator.")
        raise

    return native_quil