Ejemplo n.º 1
0
def test_generate_randomized_benchmarking_sequence__returns_benchmarking_sequence(
    mocker: MockerFixture, ):
    client_configuration = QCSClientConfiguration.load()
    compiler_client = CompilerClient(client_configuration=client_configuration)

    rpcq_client = patch_rpcq_client(
        mocker=mocker,
        return_value=rpcq.messages.RandomizedBenchmarkingResponse(
            sequence=[[3, 1, 4], [1, 6, 1]]))

    request = GenerateRandomizedBenchmarkingSequenceRequest(
        depth=42,
        num_qubits=3,
        gateset=["some", "gate", "set"],
        seed=314,
        interleaver="some-interleaver",
    )
    assert compiler_client.generate_randomized_benchmarking_sequence(
        request) == GenerateRandomizedBenchmarkingSequenceResponse(
            sequence=[[3, 1, 4], [1, 6, 1]])
    rpcq_client.call.assert_called_once_with(
        "generate_rb_sequence",
        rpcq.messages.RandomizedBenchmarkingRequest(
            depth=42,
            qubits=3,
            gateset=["some", "gate", "set"],
            seed=314,
            interleaver="some-interleaver",
        ))
Ejemplo n.º 2
0
def test_conjugate_pauli_by_clifford__returns_conjugation_result(
        mocker: MockerFixture):
    client_configuration = QCSClientConfiguration.load()
    compiler_client = CompilerClient(client_configuration=client_configuration)
    rpcq_client = patch_rpcq_client(
        mocker=mocker,
        return_value=rpcq.messages.ConjugateByCliffordResponse(phase=42,
                                                               pauli="pauli"))

    request = ConjugatePauliByCliffordRequest(
        pauli_indices=[0, 1, 2],
        pauli_symbols=["x", "y", "z"],
        clifford="cliff",
    )
    assert compiler_client.conjugate_pauli_by_clifford(
        request) == ConjugatePauliByCliffordResponse(
            phase_factor=42,
            pauli="pauli",
        )
    rpcq_client.call.assert_called_once_with(
        "conjugate_pauli_by_clifford",
        rpcq.messages.ConjugateByCliffordRequest(
            pauli=rpcq.messages.PauliTerm(indices=[0, 1, 2],
                                          symbols=["x", "y", "z"]),
            clifford="cliff",
        ))
Ejemplo n.º 3
0
def test_get_version__returns_version(mocker: MockerFixture):
    client_configuration = QCSClientConfiguration.load()
    compiler_client = CompilerClient(client_configuration=client_configuration)

    rpcq_client = patch_rpcq_client(mocker=mocker,
                                    return_value={"quilc": "1.2.3"})

    assert compiler_client.get_version() == "1.2.3"
    rpcq_client.call.assert_called_once_with("get_version_info")
Ejemplo n.º 4
0
def test_sets_timeout_on_requests(mocker: MockerFixture):
    client_configuration = QCSClientConfiguration.load()
    compiler_client = CompilerClient(client_configuration=client_configuration,
                                     request_timeout=0.1)

    patch_rpcq_client(mocker=mocker, return_value={})

    with compiler_client._rpcq_client() as client:
        assert client.timeout == compiler_client.timeout
Ejemplo n.º 5
0
    def __init__(
        self,
        noise_model: Optional[NoiseModel] = None,
        gate_noise: Optional[Tuple[float, float, float]] = None,
        measurement_noise: Optional[Tuple[float, float, float]] = None,
        random_seed: Optional[int] = None,
        timeout: float = 10.0,
        client_configuration: Optional[QCSClientConfiguration] = None,
    ) -> None:
        """
        A virtual machine that classically emulates the execution of Quil programs.

        :param noise_model: A noise model that describes noise to apply when emulating a program's
            execution.
        :param gate_noise: A tuple of three numbers [Px, Py, Pz] indicating the probability of an X,
           Y, or Z gate getting applied to each qubit after a gate application or reset. The
           default value of None indicates no noise.
        :param measurement_noise: A tuple of three numbers [Px, Py, Pz] indicating the probability
            of an X, Y, or Z gate getting applied before a measurement. The default value of
            None indicates no noise.
        :param random_seed: A seed for the QVM's random number generators. Either None (for an
            automatically generated seed) or a non-negative integer.
        :param timeout: Time limit for requests, in seconds.
        :param client_configuration: Optional client configuration. If none is provided, a default one will be loaded.
        """
        super().__init__()

        if (noise_model is not None) and (gate_noise is not None
                                          or measurement_noise is not None):
            raise ValueError("""
You have attempted to supply the QVM with both a Kraus noise model
(by supplying a `noise_model` argument), as well as either `gate_noise`
or `measurement_noise`. At this time, only one may be supplied.

To read more about supplying noise to the QVM, see
http://pyquil.readthedocs.io/en/latest/noise_models.html#support-for-noisy-gates-on-the-rigetti-qvm.
""")

        self.noise_model = noise_model

        validate_noise_probabilities(gate_noise)
        validate_noise_probabilities(measurement_noise)
        self.gate_noise = gate_noise
        self.measurement_noise = measurement_noise

        if random_seed is None:
            self.random_seed = None
        elif isinstance(random_seed, int) and random_seed >= 0:
            self.random_seed = random_seed
        else:
            raise TypeError("random_seed should be None or a non-negative int")

        client_configuration = client_configuration or QCSClientConfiguration.load(
        )
        self._qvm_client = QVMClient(client_configuration=client_configuration,
                                     request_timeout=timeout)
        self.connect()
Ejemplo n.º 6
0
def test_init__sets_base_url_and_timeout(monkeypatch: MonkeyPatch):
    host = "tcp://localhost:1234"
    monkeypatch.setenv("QCS_SETTINGS_APPLICATIONS_PYQUIL_QUILC_URL", host)
    client_configuration = QCSClientConfiguration.load()

    compiler_client = CompilerClient(client_configuration=client_configuration,
                                     request_timeout=3.14)

    assert compiler_client.base_url == host
    assert compiler_client.timeout == 3.14
Ejemplo n.º 7
0
def test_init__validates_compiler_url(monkeypatch: MonkeyPatch):
    monkeypatch.setenv("QCS_SETTINGS_APPLICATIONS_PYQUIL_QUILC_URL",
                       "not-http-or-tcp://example.com")
    client_configuration = QCSClientConfiguration.load()

    with raises(
            ValueError,
            match=
            "Expected compiler URL 'not-http-or-tcp://example.com' to start with 'tcp://'",
    ):
        CompilerClient(client_configuration=client_configuration)
Ejemplo n.º 8
0
    def __init__(self, *, timeout: float = 10.0, client_configuration: Optional[QCSClientConfiguration] = None):
        """
        Client to communicate with the benchmarking data endpoint.

        :param timeout: Time limit for requests, in seconds.
        :param client_configuration: Optional client configuration. If none is provided, a default one will be loaded.
        """

        self._compiler_client = CompilerClient(
            client_configuration=client_configuration or QCSClientConfiguration.load(),
            request_timeout=timeout,
        )
Ejemplo n.º 9
0
def test_compile_to_native_quil__returns_native_quil(
    aspen8_compiler_isa: CompilerISA,
    mocker: MockerFixture,
):
    client_configuration = QCSClientConfiguration.load()
    compiler_client = CompilerClient(client_configuration=client_configuration)

    rpcq_client = patch_rpcq_client(
        mocker=mocker,
        return_value=rpcq.messages.NativeQuilResponse(
            quil="native-program",
            metadata=rpcq.messages.NativeQuilMetadata(
                final_rewiring=[0, 1, 2],
                gate_depth=10,
                gate_volume=42,
                multiqubit_gate_depth=5,
                program_duration=3.14,
                program_fidelity=0.99,
                topological_swaps=3,
                qpu_runtime_estimation=0.1618,
            ),
        ))
    request = CompileToNativeQuilRequest(
        program="some-program",
        target_quantum_processor=compiler_isa_to_target_quantum_processor(
            aspen8_compiler_isa),
        protoquil=True,
    )

    assert compiler_client.compile_to_native_quil(
        request) == CompileToNativeQuilResponse(
            native_program="native-program",
            metadata=NativeQuilMetadataResponse(
                final_rewiring=[0, 1, 2],
                gate_depth=10,
                gate_volume=42,
                multiqubit_gate_depth=5,
                program_duration=3.14,
                program_fidelity=0.99,
                topological_swaps=3,
                qpu_runtime_estimation=0.1618,
            ),
        )
    rpcq_client.call.assert_called_once_with(
        "quil_to_native_quil",
        rpcq.messages.NativeQuilRequest(
            quil="some-program",
            target_device=compiler_isa_to_target_quantum_processor(
                aspen8_compiler_isa),
        ),
        protoquil=True,
    )
Ejemplo n.º 10
0
    def __init__(
        self,
        *,
        quantum_processor: AbstractQuantumProcessor,
        timeout: float,
        client_configuration: Optional[QCSClientConfiguration],
    ) -> None:
        self.quantum_processor = quantum_processor
        self._timeout = timeout

        self._client_configuration = client_configuration or QCSClientConfiguration.load(
        )
        self._compiler_client = CompilerClient(
            client_configuration=self._client_configuration,
            request_timeout=timeout)
Ejemplo n.º 11
0
    def __init__(
        self,
        *,
        gate_noise: Optional[Tuple[float, float, float]] = None,
        measurement_noise: Optional[Tuple[float, float, float]] = None,
        random_seed: Optional[int] = None,
        timeout: float = 10.0,
        client_configuration: Optional[QCSClientConfiguration] = None,
    ) -> None:
        """
        A simulator that propagates a wavefunction representation of a quantum state.

        :param gate_noise: A tuple of three numbers [Px, Py, Pz] indicating the probability of an X,
            Y, or Z gate getting applied to each qubit after a gate application or reset.
        :param measurement_noise: A tuple of three numbers [Px, Py, Pz] indicating the probability
            of an X, Y, or Z gate getting applied before a measurement.
        :param random_seed: A seed for the simulator's random number generators. Either None (for
            an automatically generated seed) or a non-negative integer.
        :param timeout: Time limit for requests, in seconds.
        :param client_configuration: Optional client configuration. If none is provided, a default one will be loaded.
        """

        validate_noise_probabilities(gate_noise)
        validate_noise_probabilities(measurement_noise)
        self.gate_noise = gate_noise
        self.measurement_noise = measurement_noise

        if random_seed is None:
            self.random_seed = None
        elif isinstance(random_seed, int) and random_seed >= 0:
            self.random_seed = random_seed
        else:
            raise TypeError("random_seed should be None or a non-negative int")

        client_configuration = client_configuration or QCSClientConfiguration.load(
        )
        self._qvm_client = QVMClient(client_configuration=client_configuration,
                                     request_timeout=timeout)
Ejemplo n.º 12
0
    def __init__(
        self,
        *,
        quantum_processor_id: str,
        priority: int = 1,
        timeout: float = 10.0,
        client_configuration: Optional[QCSClientConfiguration] = None,
        engagement_manager: Optional[EngagementManager] = None,
        endpoint_id: Optional[str] = None,
    ) -> None:
        """
        A connection to the QPU.

        :param quantum_processor_id: Processor to run against.
        :param priority: The priority with which to insert jobs into the QPU queue. Lower integers
            correspond to higher priority.
        :param timeout: Time limit for requests, in seconds.
        :param client_configuration: Optional client configuration. If none is provided, a default one will be loaded.
        :param endpoint_id: Optional endpoint ID to be used for engagement.
        :param engagement_manager: Optional engagement manager. If none is provided, a default one will be created.
        """
        super().__init__()

        self.priority = priority

        client_configuration = client_configuration or QCSClientConfiguration.load(
        )
        engagement_manager = engagement_manager or EngagementManager(
            client_configuration=client_configuration)
        self._qpu_client = QPUClient(
            quantum_processor_id=quantum_processor_id,
            endpoint_id=endpoint_id,
            engagement_manager=engagement_manager,
            request_timeout=timeout,
        )
        self._last_results: Dict[str, np.ndarray] = {}
        self._memory_results: Dict[str, Optional[np.ndarray]] = defaultdict(
            lambda: None)
Ejemplo n.º 13
0
def client_configuration() -> QCSClientConfiguration:
    return QCSClientConfiguration.load()