qcs 0.27.0

High level interface for running Quil on a QPU
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# This file is automatically generated by pyo3_stub_gen
# ruff: noqa: E501, F401, F403, F405
r"""
An interface to Rigetti [Quantum Cloud Services](https://docs.rigetti.com/qcs/) (QCS).

These APIs allow users to compile and run Quil programs on Rigetti quantum processors.
Internally, it is powered by the [QCS Rust SDK](https://github.com/rigetti/qcs-sdk-rust).

This package is still in development and breaking changes should be expected between minor versions.
"""

import builtins
import collections.abc
import datetime
import enum
import numpy
import numpy.typing
from qcs_sdk._qcs_sdk.compiler import quilc
from qcs_sdk._qcs_sdk.qpu import api
from qcs_sdk._qcs_sdk.qpu import translation
import typing
from qcs_sdk import _tracing_subscriber
from . import client
from . import compiler
from . import diagnostics
from . import qpu
from . import qvm

__all__ = [
    "ExeParameter",
    "Executable",
    "ExecutionData",
    "ExecutionError",
    "JobHandle",
    "QcsSdkError",
    "RegisterData",
    "RegisterMap",
    "RegisterMapItemsIter",
    "RegisterMapKeysIter",
    "RegisterMapValuesIter",
    "RegisterMatrix",
    "RegisterMatrixConversionError",
    "Service",
    "__version__",
    "_gather_diagnostics",
    "_tracing_subscriber",
    "client",
    "compiler",
    "diagnostics",
    "qpu",
    "qvm",
    "reset_logging",
]

__version__: typing.Final[builtins.str]

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

    Note: The validity of parameters is not checked until execution.
    """
    @property
    def index(self) -> builtins.int: ...
    @index.setter
    def index(self, value: builtins.int) -> None: ...
    @property
    def name(self) -> builtins.str: ...
    @name.setter
    def name(self, value: builtins.str) -> None: ...
    @property
    def value(self) -> builtins.float: ...
    @value.setter
    def value(self, value: builtins.float) -> None: ...
    def __new__(cls, name: builtins.str, index: builtins.int, value: builtins.float) -> ExeParameter: ...

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

    # Example

    This example executes a program on a QVM, specified by the `qvm_url` in the `QCSClient`:

    ```python
    from qcs_sdk import Executable
    from qcs_sdk.client import QCSClient
    from qcs_sdk.qvm import QVMClient

    PROGRAM = r'''
    DECLARE ro BIT[2]

    H 0
    CNOT 0 1

    MEASURE 0 ro[0]
    MEASURE 1 ro[1]
    '''

    async def run():
        client = QVMClient.new_http(QCSClient.load().qvm_url)
        result = await Executable(PROGRAM, shots=4).execute_on_qvm_async()
        let data = result.result_data
                            .to_register_map()
                            .expect("should convert to readout map")
                            .get_register_matrix("ro")
                            .expect("should have data in ro")
                            .as_integer()
                            .expect("should be integer matrix")
                            .to_owned();

        // In this case, we ran the program for 4 shots, so we know the number of rows is 4.
        assert_eq!(data.nrows(), 4);
        for shot in data.rows() {
            // Each shot will contain all the memory, in order, for the vector (or "register") we
            // requested the results of. In this case, "ro" (the default).
            assert_eq!(shot.len(), 2);
            // In the case of this particular program, we know ro[0] should equal ro[1]
            assert_eq!(shot[0], shot[1]);
        }

    def main():
        import asyncio
        asyncio.run(run())

        # "ro" is the only source read from by default if you don't specify `registers`.

        # We first convert the readout data to a ``RegisterMap`` to get a mapping of registers
        # (ie. "ro") to a [`RegisterMatrix`], `M`, where M[`shot`][`index`] is the value for
        # the memory offset `index` during shot `shot`.
        # There are some programs where QPU readout data does not fit into a [`RegisterMap`], in
        # which case you should build the matrix you need from [`QpuResultData`] directly. See
        # the [`RegisterMap`] documentation for more information on when this transformation
        # might fail.
    ```
    """
    def __new__(
        cls,
        quil: builtins.str,
        /,
        registers: typing.Sequence[builtins.str] = [],
        parameters: typing.Sequence[ExeParameter] = [],
        shots: typing.Optional[builtins.int] = None,
        quilc_client: typing.Optional[quilc.QuilcClient] = None,
        compiler_options: typing.Optional[quilc.CompilerOpts] = None,
    ) -> Executable: ...
    def execute_on_qpu(
        self,
        quantum_processor_id: builtins.str,
        endpoint_id: typing.Optional[builtins.str] = None,
        translation_options: typing.Optional[translation.TranslationOptions] = None,
        execution_options: typing.Optional[api.ExecutionOptions] = None,
    ) -> ExecutionData:
        r"""
        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.
        """
    def execute_on_qpu_async(
        self,
        quantum_processor_id: builtins.str,
        endpoint_id: typing.Optional[builtins.str] = None,
        translation_options: typing.Optional[translation.TranslationOptions] = None,
        execution_options: typing.Optional[api.ExecutionOptions] = None,
    ) -> collections.abc.Awaitable[ExecutionData]:
        r"""
        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 execute_on_qvm(self, client: qvm.QVMClient) -> ExecutionData:
        r"""
        Execute on a QVM which is accessible via the provided client.

        :raises `ExecutionError`: If the job fails to execute.
        """
    def execute_on_qvm_async(self, client: qvm.QVMClient) -> collections.abc.Awaitable[ExecutionData]:
        r"""
        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 retrieve_results(self, job_handle: JobHandle) -> ExecutionData:
        r"""
        Wait for the results of a job to complete.

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

        :raises `ExecutionError`: If the job fails to execute.
        """
    def submit_to_qpu(
        self,
        quantum_processor_id: builtins.str,
        endpoint_id: typing.Optional[builtins.str] = None,
        translation_options: typing.Optional[translation.TranslationOptions] = None,
        execution_options: typing.Optional[api.ExecutionOptions] = None,
    ) -> JobHandle:
        r"""
        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.
        """
    def submit_to_qpu_async(
        self,
        quantum_processor_id: builtins.str,
        endpoint_id: typing.Optional[builtins.str] = None,
        translation_options: typing.Optional[translation.TranslationOptions] = None,
        execution_options: typing.Optional[api.ExecutionOptions] = None,
    ) -> collections.abc.Awaitable[JobHandle]:
        r"""
        Compile the program and execute it on a QPU, without waiting for results
        (async analog of `Executable.submit_to_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.
        """

@typing.final
class ExecutionData:
    r"""
    The result of executing an [`Executable`](crate::Executable)
    """
    @property
    def duration(self) -> typing.Optional[datetime.timedelta]:
        r"""
        The time it took to execute the program on the QPU, not including any network or queueing
        time. If paying for on-demand execution, this is the amount you will be billed for.

        This will always be `None` for QVM execution.
        """
    @property
    def result_data(self) -> qvm.QVMResultData | qpu.QPUResultData:
        r"""
        The [`ResultData`] that was read from the [`Executable`](crate::Executable).
        """
    def __eq__(self, other: builtins.object, /) -> builtins.bool: ...
    def __getnewargs__(self) -> tuple[qvm.QVMResultData | qpu.QPUResultData, typing.Optional[datetime.timedelta]]: ...
    def __new__(
        cls, result_data: qvm.QVMResultData | qpu.QPUResultData, duration: typing.Optional[datetime.timedelta] = None
    ) -> ExecutionData:
        r"""
        Create `ExecutionData` from `ResultData` and an optional `duration`.
        """

class ExecutionError(QcsSdkError):
    r"""
    Errors which can occur when executing a program.
    """

    ...

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

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

class QcsSdkError(builtins.Exception):
    r"""
    Base exception type for errors raised by this package.
    """

    ...

class RegisterData:
    r"""
    Data resulting from [`Executable::execute_on_qvm`](`crate::Executable::execute_on_qvm`)

    This represents a single vector (or "register") of typed memory across some number of shots.
    The register corresponds to the usage of a `DECLARE` instruction in Quil, and the name of that
    register should be provided with [`Executable::read_from`](`crate::Executable::read_from`).

    There is a variant of this enum for each type of data that a register could hold. The register
    is represented as a 2-dimensional array `M` where the value `M[shot_number][memory_index]`
    represents the value at `memory_index` for `shot_number`.

    # Usage

    Typically, you will be interacting with this data through the [`crate::ResultData`] of an
    [`crate::ExecutionData`] returned after running a program. In those cases, you'll probably
    want to convert it to a readout map using [`crate::ResultData.to_register_map()`]. This
    will give you each register in the form of a [`crate::RegisterMatrix`] which is similar
    but backed by an [`ndarray::Array2`] and more convenient for working with matrices.

    If you are interacting with [`RegisterData`] directly, then you should already know what type of data it _should_
    have, so you can  use the [`mod@enum_as_inner`] methods (e.g. [`RegisterData::into_i8`]) in order to
    convert any variant type to its inner data.
    """
    def __getnewargs__(
        self,
    ) -> tuple[
        builtins.list[builtins.list[builtins.int]]
        | builtins.list[builtins.list[builtins.float]]
        | builtins.list[builtins.list[builtins.complex]]
    ]: ...
    def __new__(
        cls,
        inner: typing.Sequence[typing.Sequence[builtins.int]]
        | typing.Sequence[typing.Sequence[builtins.float]]
        | typing.Sequence[typing.Sequence[builtins.complex]],
    ) -> RegisterData: ...
    def as_ndarray(self) -> numpy.ndarray:
        r"""
        Return the inner values as a 2D Numpy ``ndarray``.
        """
    def inner(
        self,
    ) -> (
        builtins.list[builtins.list[builtins.int]]
        | builtins.list[builtins.list[builtins.float]]
        | builtins.list[builtins.list[builtins.complex]]
    ): ...
    @typing.final
    class Complex32(RegisterData):
        r"""
        Results containing complex numbers.
        """

        __match_args__ = ("_0",)
        @property
        def _0(self) -> builtins.list[builtins.list[builtins.complex]]: ...
        def __getitem__(self, key: builtins.int, /) -> typing.Any: ...
        def __len__(self) -> builtins.int: ...
        def __new__(cls, _0: typing.Sequence[typing.Sequence[builtins.complex]]) -> RegisterData.Complex32: ...

    @typing.final
    class F64(RegisterData):
        r"""
        Corresponds to the Quil `REAL` type.
        """

        __match_args__ = ("_0",)
        @property
        def _0(self) -> builtins.list[builtins.list[builtins.float]]: ...
        def __getitem__(self, key: builtins.int, /) -> typing.Any: ...
        def __len__(self) -> builtins.int: ...
        def __new__(cls, _0: typing.Sequence[typing.Sequence[builtins.float]]) -> RegisterData.F64: ...

    @typing.final
    class I16(RegisterData):
        r"""
        Corresponds to the Quil `INTEGER` type.
        """

        __match_args__ = ("_0",)
        @property
        def _0(self) -> builtins.list[builtins.list[builtins.int]]: ...
        def __getitem__(self, key: builtins.int, /) -> typing.Any: ...
        def __len__(self) -> builtins.int: ...
        def __new__(cls, _0: typing.Sequence[typing.Sequence[builtins.int]]) -> RegisterData.I16: ...

    @typing.final
    class I8(RegisterData):
        r"""
        Corresponds to the Quil `BIT` or `OCTET` types.
        """

        __match_args__ = ("_0",)
        @property
        def _0(self) -> builtins.list[builtins.list[builtins.int]]: ...
        def __getitem__(self, key: builtins.int, /) -> typing.Any: ...
        def __len__(self) -> builtins.int: ...
        def __new__(cls, _0: typing.Sequence[typing.Sequence[builtins.int]]) -> RegisterData.I8: ...

@typing.final
class RegisterMap:
    r"""
    A mapping of a register name (ie. "ro") to a [`RegisterMatrix`] containing the values for the
    register.
    """
    def __contains__(self, key: builtins.str) -> builtins.bool: ...
    def __getitem__(self, item: builtins.str) -> RegisterMatrix: ...
    def __iter__(self) -> RegisterMapKeysIter: ...
    def __len__(self) -> builtins.int: ...
    def get(
        self, key: builtins.str, default: typing.Optional[RegisterMatrix] = None
    ) -> typing.Optional[RegisterMatrix]: ...
    def get_register_matrix(self, register_name: builtins.str) -> typing.Optional[RegisterMatrix]:
        r"""
        Get the `RegisterMatrix` for the given register.

        Returns `None` if the register doesn't exist.
        """
    def items(self) -> RegisterMapItemsIter: ...
    def keys(self) -> RegisterMapKeysIter: ...
    def values(self) -> RegisterMapValuesIter: ...

@typing.final
class RegisterMapItemsIter:
    def __iter__(self) -> RegisterMapItemsIter: ...
    def __next__(self) -> tuple[builtins.str, RegisterMatrix]: ...

@typing.final
class RegisterMapKeysIter:
    def __iter__(self) -> RegisterMapKeysIter: ...
    def __next__(self) -> builtins.str: ...

@typing.final
class RegisterMapValuesIter:
    def __iter__(self) -> RegisterMapValuesIter: ...
    def __next__(self) -> RegisterMatrix: ...

class RegisterMatrix:
    r"""
    A 2-dimensional matrix of register values.

    Each variant corresponds to the possible data types a register can contain.
    """
    def to_ndarray(self) -> typing.Any:
        r"""
        Get the `RegisterMatrix` as Numpy ``ndarray``.
        """
    @typing.final
    class Complex(RegisterMatrix):
        r"""
        Complex numbered register.
        """

        __match_args__ = ("_0",)
        @property
        def _0(self) -> numpy.typing.NDArray[numpy.complex128]: ...
        def __getitem__(self, key: builtins.int, /) -> typing.Any: ...
        def __len__(self) -> builtins.int: ...
        def __new__(cls, _0: numpy.typing.NDArray[numpy.complex128]) -> RegisterMatrix.Complex: ...

    @typing.final
    class Integer(RegisterMatrix):
        r"""
        Integer register.
        """

        __match_args__ = ("_0",)
        @property
        def _0(self) -> numpy.typing.NDArray[numpy.int64]: ...
        def __getitem__(self, key: builtins.int, /) -> typing.Any: ...
        def __len__(self) -> builtins.int: ...
        def __new__(cls, _0: numpy.typing.NDArray[numpy.int64]) -> RegisterMatrix.Integer: ...

    @typing.final
    class Real(RegisterMatrix):
        r"""
        Real numbered register.
        """

        __match_args__ = ("_0",)
        @property
        def _0(self) -> numpy.typing.NDArray[numpy.float64]: ...
        def __getitem__(self, key: builtins.int, /) -> typing.Any: ...
        def __len__(self) -> builtins.int: ...
        def __new__(cls, _0: numpy.typing.NDArray[numpy.float64]) -> RegisterMatrix.Real: ...

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

    ...

@typing.final
class Service(enum.Enum):
    r"""
    The external services that this SDK may connect to. Used to differentiate between networking
    issues in [`Error::Connection`].
    """

    QUILC = ...
    r"""
    The open source [`quilc`](https://github.com/quil-lang/quilc) compiler.
    
    This compiler must be running before calling [`Executable::execute_on_qpu`] unless the
    [`Executable::compile_with_quilc`] option is set to `false`. By default, it's assumed that
    this is running on `tcp://localhost:5555`, but this can be overridden via
    `[profiles.<profile_name>.applications.pyquil.quilc_url]` in your `.qcs/settings.toml` file.
    """
    QVM = ...
    r"""
    The open source [`qvm`](https://github.com/quil-lang/qvm) simulator.
    
    This simulator must be running before calling [`Executable::execute_on_qvm`]. By default,
    it's assumed that this is running on `http://localhost:5000`, but this can be overridden via
    `[profiles.<profile_name>.applications.pyquil.qvm_url]` in your `.qcs/settings.toml` file.
    """
    QCS = ...
    r"""
    The connection to [`QCS`](https://docs.rigetti.com/qcs/), the API for authentication,
    QPU lookup, and translation.
    
    You should be able to reach this service as long as you have a connection to the internet.
    """
    QPU = ...
    r"""
    The connection to the QPU itself. You can only connect to the QPU from an authorized network
    (like QCS JupyterLab).
    """

def _gather_diagnostics() -> builtins.str: ...
def reset_logging() -> None:
    r"""
    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.
    """