qcs-sdk-python 0.21.22

Python bindings to qcs-sdk-rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
"""
The `qcs_sdk` package provides a Python interface to the Rigetti Quantum Cloud Services (QCS) platform.

For more information about QCS, see [the QCS documentation](https://docs.rigetti.com/qcs/).

⚠️ This package is still in early development and breaking changes should be expected between minor versions.
"""
from __future__ import annotations
import datetime
from enum import Enum
from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union, final

import numpy as np
from numpy.typing import NDArray

from qcs_sdk.client import QCSClient as QCSClient
from qcs_sdk.compiler.quilc import CompilerOpts, QuilcClient
from qcs_sdk.qpu import QPUResultData, RawQPUReadoutData
from qcs_sdk.qpu.api import ExecutionOptions
from qcs_sdk.qpu.translation import TranslationOptions
from qcs_sdk.qvm import QVMClient, QVMResultData, RawQVMReadoutData
from qcs_sdk.diagnostics import _gather_diagnostics

from qcs_sdk import _tracing_subscriber as _tracing_subscriber
from qcs_sdk import client as client
from qcs_sdk import compiler as compiler
from qcs_sdk import qpu as qpu
from qcs_sdk import qvm as qvm
from qcs_sdk import diagnostics as diagnostics


__all__ = [
    'ExeParameter',
    'Executable',
    'ExecutionData',
    'ExecutionError',
    'JobHandle',
    'QCSClient',
    'RegisterData',
    'RegisterMap',
    'RegisterMatrix',
    'RegisterMatrixConversionError',
    'ResultData',
    'Service',
    '_tracing_subscriber',
    'client',
    'compiler',
    'qpu',
    'qvm',
    'reset_logging',
    '__version__',
    '_gather_diagnostics',
    'diagnostics',
]


__version__: str = ...


class ExecutionError(RuntimeError):
    """Error encountered when executing a program."""

    ...

@final
class Executable:
    """
    The builder interface for executing Quil programs on QVMs and QPUs.
    """

    def __new__(
        cls,
        quil: str,
        /,
        registers: Optional[Sequence[str]] = None,
        parameters: Optional[Sequence[ExeParameter]] = None,
        shots: Optional[int] = None,
        quilc_client: Optional[QuilcClient] = None,
        compiler_options: Optional[CompilerOpts] = None,
    ) -> "Executable": ...
    def execute_on_qvm(self, client: QVMClient) -> ExecutionData:
        """
        Execute on a QVM which is accessible via the provided client.

        :raises `ExecutionError`: If the job fails to execute.
        """
        ...
    async def execute_on_qvm_async(self, client: QVMClient) -> ExecutionData:
        """
        Execute on a QVM which is accessible via the provided client.
        (async analog of ``Executable.execute_on_qvm``.)

        :raises `ExecutionError`: If the job fails to execute.
        """
        ...
    def execute_on_qpu(
        self,
        quantum_processor_id: str,
        endpoint_id: Optional[str] = None,
        translation_options: Optional[TranslationOptions] = None,
        execution_options: Optional[ExecutionOptions] = None,
    ) -> ExecutionData:
        """
        Compile the program and execute it on a QPU, waiting for results.

        :param endpoint_id: execute the compiled program against an explicitly provided endpoint. If `None`,
        the default endpoint for the given quantum_processor_id is used.

        :raises `ExecutionError`: If the job fails to execute.
        """
        ...
    async def execute_on_qpu_async(
        self,
        quantum_processor_id: str,
        endpoint_id: Optional[str] = None,
        translation_options: Optional[TranslationOptions] = None,
        execution_options: Optional[ExecutionOptions] = None,
    ) -> ExecutionData:
        """
        Compile the program and execute it on a QPU, waiting for results.
        (async analog of `Executable.execute_on_qpu`)

        :param endpoint_id: execute the compiled program against an explicitly provided endpoint. If `None`,
        the default endpoint for the given quantum_processor_id is used.

        :raises `ExecutionError`: If the job fails to execute.
        """
        ...
    def submit_to_qpu(
        self,
        quantum_processor_id: str,
        endpoint_id: Optional[str] = None,
        translation_options: Optional[TranslationOptions] = None,
        execution_options: Optional[ExecutionOptions] = None,
    ) -> JobHandle:
        """
        Compile the program and execute it on a QPU, without waiting for results.

        :param endpoint_id: execute the compiled program against an explicitly provided endpoint. If `None`,
        the default endpoint for the given quantum_processor_id is used.

        :raises `ExecutionError`: If the job fails to execute.
        """
        ...
    async def submit_to_qpu_async(
        self,
        quantum_processor_id: str,
        endpoint_id: Optional[str] = None,
        translation_options: Optional[TranslationOptions] = None,
        execution_options: Optional[ExecutionOptions] = None,
    ) -> JobHandle:
        """
        Compile the program and execute it on a QPU, without waiting for results.
        (async analog of `Executable.execute_on_qpu`)

        :param endpoint_id: execute the compiled program against an explicitly provided endpoint. If `None`,
        the default endpoint for the given quantum_processor_id is used.

        :raises `ExecutionError`: If the job fails to execute.
        """
        ...
    def retrieve_results(self, job_handle: JobHandle) -> ExecutionData:
        """
        Wait for the results of a job to complete.

        :raises `ExecutionError`: If the job fails to execute.
        """
        ...
    async def retrieve_results_async(self, job_handle: JobHandle) -> ExecutionData:
        """
        Wait for the results of a job to complete.
        (async analog of `Executable.retrieve_results`)

        :raises `ExecutionError`: If the job fails to execute.
        """
        ...

@final
class JobHandle:
    """
    The result of submitting a job to a QPU.

    Used to retrieve the results of a job.
    """

    @property
    def job_id(self) -> str:
        """
        Unique ID associated with a single job execution.
        """
        ...
    @property
    def readout_map(self) -> Dict[str, str]:
        """
        The readout map from source readout memory locations to the filter pipeline node
        which publishes the data.
        """
        ...

@final
class ExeParameter:
    """
    Program execution parameters.

    Note: The validity of parameters is not checked until execution.
    """

    def __new__(
        cls,
        name: str,
        index: int,
        value: float,
    ) -> "ExeParameter": ...
    @property
    def name(self) -> str: ...
    @name.setter
    def name(self, value: str): ...
    @property
    def index(self) -> int: ...
    @index.setter
    def index(self, value: int): ...
    @property
    def value(self) -> float: ...
    @value.setter
    def value(self, value: float): ...

@final
class Service(Enum):
    Quilc = "Quilc"
    QVM = "QVM"
    QCS = "QCS"
    QPU = "QPU"

class RegisterMatrixConversionError(ValueError):
    """Error that may occur when building a `RegisterMatrix` from execution data."""

    ...

@final
class RegisterMatrix:
    """
    Values in a 2-dimensional ``ndarray`` representing the final shot value in each memory reference across all shots.
    Each variant corresponds to the possible data types a register can contain.

    ## Variants:
    - ``integer``: Corresponds to the Quil ``BIT``, ``OCTET``, or ``INTEGER`` types.
    - ``real``: Corresponds to the Quil ``REAL`` type.
    - ``complex``: Registers containing complex numbers.

    ### Methods (each per variant):
    - ``is_*``: if the underlying values are that type.
    - ``as_*``: if the underlying values are that type, then those values, otherwise ``None``.
    - ``to_*``: the underlying values as that type, raises ``ValueError`` if they are not.
    - ``from_*``: wrap underlying values as this enum type.

    """

    def is_integer(self) -> bool: ...
    def is_real(self) -> bool: ...
    def is_complex(self) -> bool: ...
    def as_integer(self) -> Optional[NDArray[np.int64]]: ...
    def as_real(self) -> Optional[NDArray[np.float64]]: ...
    # In numpy `complex128` is a complex number made up of two `f64`s.
    def as_complex(self) -> Optional[NDArray[np.complex128]]: ...
    def to_integer(self) -> NDArray[np.int64]: ...
    def to_real(self) -> NDArray[np.float64]: ...
    def to_complex(self) -> NDArray[np.complex128]: ...
    @staticmethod
    def from_integer(inner: NDArray[np.int64]) -> "RegisterMatrix": ...
    @staticmethod
    def from_real(inner: NDArray[np.float64]) -> "RegisterMatrix": ...
    @staticmethod
    def from_complex(inner: NDArray[np.complex128]) -> "RegisterMatrix": ...
    def to_ndarray(self) -> Union[NDArray[np.complex128], NDArray[np.int64], NDArray[np.float64]]:
        """
        Get the RegisterMatrix as numpy ``ndarray``.
        """
        ...

@final
class RegisterMap:
    """A map of register names (ie. "ro") to a `RegisterMatrix` containing the values of the register."""

    def get_register_matrix(self, register_name: str) -> Optional[RegisterMatrix]:
        """Get the ``RegisterMatrix`` for the given register. Returns `None` if the register doesn't exist."""
        ...
    def get(self, key: str, default: Optional[RegisterMatrix] = None) -> Optional[RegisterMatrix]: ...
    def items(self) -> Iterable[Tuple[str, RegisterMatrix]]: ...
    def keys(self) -> Iterable[str]: ...
    def values(self) -> Iterable[RegisterMatrix]: ...
    def __iter__(self) -> Iterable[str]: ...
    def __getitem__(self, item: str) -> RegisterMatrix: ...
    def __contains__(self, key: str) -> bool: ...
    def __len__(self) -> int: ...

@final
class ResultData:
    """
    Represents the two possible types of data returned from either the QVM or a real QPU.
    Each variant contains the original data returned from its respective executor.

    ## Usage

    Your usage of `ResultData` will depend on the types of programs you are running and where.
    The `ResultData.to_register_map()` method will attempt to build `RegisterMap` out of the data, where each
    register name is mapped to a 2-dimensional rectangular `RegisterMatrix` where each row
    represents the final values in each register index for a particular shot. This is often the
    desired form of the data and it is <em>probably</em> what you want. This transformation isn't always
    possible, in which case `to_register_map()` will return an error.

    To understand why this transformation can fail, we need to understand a bit about how readout data is
    returned from the QVM and from a real QPU:

    The QVM treats each `DECLARE` statement as initialzing some amount of memory. This memory works
    as one might expect it to. It is zero-initalized, and subsequent writes to the same region
    overwrite the previous value. The QVM returns memory at the end of every shot. This means
    we get the last value in every memory reference for each shot, which is exactly the
    representation we want for a `RegisterMatrix`. For this reason, `to_register_map()` should
    always succeed for `ResultData::Qvm`.

    The QPU on the other hand doesn't use the same memory model as the QVM. Each memory reference
    (ie. "ro[0]") is more like a stream than a value in memory. Every `MEASURE` to a memory
    reference emits a new value to said stream. This means that the number of values per memory
    reference can vary per shot. For this reason, it's not always clear what the final value in
    each shot was for a particular reference. When this is the case, `to_register_map()` will return
    an error as it's impossible to build a correct ``RegisterMatrix``  from the data without
    knowing the intent of the program that was run. Instead, it's recommended to build the
    ``RegisterMatrix`` you need from the inner ``QPUResultData`` data using the knowledge of your
    program to choose the correct readout values for each shot.

    For more information on QPU readout data, refer to the
    [QCS Documentation](https://docs.rigetti.com/qcs/guides/qpus-vs-qvms#qpu-readout-data).

    ### Variants:
    - ``qvm``: Data returned from the QVM, stored as ``QVMResultData``
    - ``qpu``: Data returned from the QPU, stored as ``QPUResultData``

    ### Methods (each per variant):
    - ``is_*``: if the underlying values are that type.
    - ``as_*``: if the underlying values are that type, then those values, otherwise ``None``.
    - ``to_*``: the underlying values as that type, raises ``ValueError`` if they are not.
    - ``from_*``: wrap underlying values as this enum type.
    """

    def __new__(cls, inner: Union[QPUResultData, QVMResultData]) -> "ResultData":
        """
        Create a new ResultData from either QVM or QPU result data.
        """
        ...
    def to_register_map(self) -> RegisterMap:
        """
        Convert `ResultData` from its inner representation as `QVMResultData` or
        `QPUResultData` into a `RegisterMap`. The `RegisterMatrix` for each register will be
        constructed such that each row contains all the final values in the register for a single shot.

        ## Errors

        Raises a `RegisterMatrixConversionError` if the inner execution data for any of the
        registers would result in a jagged matrix. `QPUResultData` data is captured per measure,
        meaning a value is returned for every measure to a memory reference, not just once per shot.
        This is often the case in programs that use mid-circuit measurement or dynamic control flow,
        where measurements to the same memory reference might occur multiple times in a shot, or be
        skipped conditionally. In these cases, building a rectangular `RegisterMatrix` would
        necessitate making assumptions about the data that could skew the data in undesirable ways.
        Instead, it's recommended to manually build a matrix from `QPUResultData` that accurately
        selects the last value per-shot based on the program that was run.
        """
        ...
    def to_raw_readout_data(self) -> Union[RawQPUReadoutData, RawQVMReadoutData]:
        """
        Get the raw data returned from the QVM or QPU. See `RawQPUReadoutData` and
        `RawQVMReadoutData` for more information.
        """
    def inner(
        self,
    ) -> Union[QVMResultData, QPUResultData]:
        """Returns the inner result data"""
        ...
    def is_qvm(self) -> bool: ...
    def is_qpu(self) -> bool: ...
    def as_qvm(self) -> Optional[QVMResultData]: ...
    def as_qpu(self) -> Optional[QPUResultData]: ...
    def to_qvm(self) -> QVMResultData: ...
    def to_qpu(self) -> QPUResultData: ...
    @staticmethod
    def from_qvm(inner: QVMResultData) -> "ResultData": ...
    @staticmethod
    def from_qpu(inner: QPUResultData) -> "ResultData": ...

@final
class ExecutionData:
    """
    Contains the `ResultData` and the duration of the execution.
    """

    def __new__(cls, result_data: ResultData, duration: Optional[datetime.timedelta] = None): ...
    @property
    def result_data(self) -> ResultData: ...
    @result_data.setter
    def result_data(self, result_data: ResultData): ...
    @property
    def duration(self) -> Optional[datetime.timedelta]: ...
    @duration.setter
    def duration(self, duration: Optional[datetime.timedelta]): ...

@final
class RegisterData:
    """
    Values present in a register that are one of a set of variants.

    Variants:
    - ``i8``: Corresponds to the Quil ``BIT`` or ``OCTET`` types.
    - ``i16``: Corresponds to the Quil ``INTEGER`` type.
    - ``f64``: Corresponds to the Quil ``REAL`` type.
    - ``complex32``: Results containing complex numbers.

    Methods (each per variant):
    - ``is_*``: if the underlying values are that type.
    - ``as_*``: if the underlying values are that type, then those values, otherwise ``None``.
    - ``to_*``: the underlying values as that type, raises ``ValueError`` if they are not.
    - ``from_*``: wrap underlying values as this enum type.
    """

    def __new__(cls, inner: Union[List[List[int]], List[List[float]], List[List[complex]]]) -> "RegisterData": ...
    def inner(
        self,
    ) -> Union[List[List[int]], List[List[float]], List[List[complex]]]:
        """Returns the inner value."""
        ...
    def as_ndarray(self) -> Union[NDArray[np.int64], NDArray[np.float64], NDArray[np.complex128]]:
        """Returns the values as an ``ndarray``."""
        ...
    def is_i8(self) -> bool: ...
    def is_i16(self) -> bool: ...
    def is_f64(self) -> bool: ...
    def is_complex32(self) -> bool: ...
    def as_i8(self) -> Optional[List[List[int]]]: ...
    def as_i16(self) -> Optional[List[List[int]]]: ...
    def as_f64(self) -> Optional[List[List[float]]]: ...
    def as_complex32(self) -> Optional[List[List[complex]]]: ...
    def to_i8(self) -> List[List[int]]: ...
    def to_i16(self) -> List[List[int]]: ...
    def to_f64(self) -> List[List[float]]: ...
    def to_complex32(self) -> List[List[complex]]: ...
    @staticmethod
    def from_i8(inner: Sequence[Sequence[int]]) -> "RegisterData": ...
    @staticmethod
    def from_i16(inner: Sequence[Sequence[int]]) -> "RegisterData": ...
    @staticmethod
    def from_f64(inner: Sequence[Sequence[float]]) -> "RegisterData": ...
    @staticmethod
    def from_complex32(inner: Sequence[Sequence[complex]]) -> "RegisterData": ...

def reset_logging():
    """
    Reset all caches for logging configuration within this library, allowing the most recent Python-side
    changes to be applied.

    See <https://docs.rs/pyo3-log/latest/pyo3_log/> for more information.
    """