qcs 0.26.2-rc.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
use std::{collections::HashMap, sync::Arc};

use opentelemetry::trace::FutureExt;
use tokio::sync::Mutex;

use pyo3::prelude::*;
#[cfg(feature = "stubs")]
use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pymethods};
use rigetti_pyo3::sync::Awaitable;
use tracing::instrument;

use crate::{
    compiler::{python::PyQuilcClient, quilc::CompilerOpts},
    executable::Executable,
    execution_data::ExecutionData,
    python::{py_sync, NonZeroU16},
    qpu::{
        api::{ExecutionOptions, JobId},
        translation::TranslationOptions,
    },
    qvm::python::PyQvmClient,
    JobHandle,
};

// Note the Python PROGRAM example _must not_ use `"""`
// or it'll break the generated docstring associated with its stubfile.
/// 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.
/// ```
#[derive(Clone)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[pyclass(module = "qcs_sdk", name = "Executable", frozen)]
pub(crate) struct PyExecutable(Arc<Mutex<Executable<'static, 'static>>>);

/// The result of submitting a job to a QPU.
///
/// Used to retrieve the results of a job.
#[derive(Clone)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[pyclass(module = "qcs_sdk", name = "JobHandle", frozen)]
pub(crate) struct PyJobHandle(JobHandle<'static>);

#[cfg_attr(feature = "stubs", gen_stub_pymethods)]
#[pymethods]
impl PyJobHandle {
    /// Unique ID associated with a single job execution.
    #[getter]
    fn job_id(&self) -> JobId {
        self.0.job_id()
    }

    /// The readout map from "source readout memory locations"
    /// to the "filter pipeline node" which publishes the data.
    #[getter]
    fn readout_map(&self) -> &HashMap<String, String> {
        self.0.readout_map()
    }
}

/// Invoke a `PyExecutable`'s inner `Executable::method` with given arguments,
/// then mapped to `Future<Output = Result<ExecutionData, ExecutionError>>`.
macro_rules! py_executable_data {
    ($self: ident, $method: ident $(, $arg: expr)* $(,)?) => {{
        let arc = $self.0.clone();
        async move {
            arc.lock()
                .await
                .$method($($arg),*)
                .await
                .map(ExecutionData::from)
                .map_err(Into::into)
        }.with_current_context()
    }};
}

/// Invoke a `PyExecutable`'s inner `Executable::method` with given arguments,
/// then mapped to `Future<Output = Result<PyJobHandle, ExecutionError>>`
macro_rules! py_job_handle {
    ($self: ident, $method: ident $(, $arg: expr)* $(,)?) => {{
        let arc = $self.0.clone();
        async move {
            arc.lock()
                .await
                .$method($($arg),*)
                .await
                .map(JobHandle::from)
                .map(PyJobHandle)
                .map_err(Into::into)
        }
        .with_current_context()
    }};
}

#[cfg_attr(feature = "stubs", gen_stub_pymethods)]
#[pymethods]
impl PyExecutable {
    #[new]
    #[pyo3(signature = (
        quil,
        /,
        registers = Vec::new(),
        parameters = Vec::new(),
        shots = None,
        quilc_client = None,
        compiler_options = None,
    ))]
    pub(crate) fn __new__(
        quil: String,
        registers: Vec<String>,
        parameters: Vec<ExeParameter>,
        shots: Option<NonZeroU16>,
        quilc_client: Option<PyQuilcClient>,
        compiler_options: Option<CompilerOpts>,
    ) -> Self {
        let quilc_client = quilc_client.map(|c| c.inner);
        let mut exe = Executable::from_quil(quil).with_quilc_client(quilc_client);

        for reg in registers {
            exe = exe.read_from(reg);
        }

        for param in parameters {
            exe.with_parameter(param.name, param.index, param.value);
        }

        if let Some(shots) = shots {
            exe = exe.with_shots(shots.0);
        }

        if let Some(options) = compiler_options {
            exe = exe.compiler_options(options);
        }

        Self(Arc::new(Mutex::new(exe)))
    }
}

#[pyo3_opentelemetry::pypropagate(on_context_extraction_failure = "ignore")]
#[cfg_attr(feature = "stubs", gen_stub_pymethods)]
#[pymethods]
impl PyExecutable {
    /// Execute on a QVM which is accessible via the provided client.
    ///
    /// :raises `ExecutionError`: If the job fails to execute.
    #[instrument(skip_all)]
    pub fn execute_on_qvm<'py>(
        &self,
        py: Python<'py>,
        client: PyQvmClient,
    ) -> PyResult<ExecutionData> {
        py_sync!(py, py_executable_data!(self, execute_on_qvm, &client))
    }

    /// 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.
    #[instrument(skip_all)]
    pub fn execute_on_qvm_async<'py>(
        &self,
        py: Python<'py>,
        client: PyQvmClient,
    ) -> PyResult<Awaitable<'py, ExecutionData>> {
        pyo3_async_runtimes::tokio::future_into_py(
            py,
            py_executable_data!(self, execute_on_qvm, &client),
        )
        .map(Into::into)
    }

    /// 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.
    #[pyo3(signature = (quantum_processor_id, endpoint_id = None, translation_options = None, execution_options = None))]
    pub fn execute_on_qpu(
        &self,
        py: Python<'_>,
        quantum_processor_id: String,
        endpoint_id: Option<String>,
        translation_options: Option<TranslationOptions>,
        execution_options: Option<ExecutionOptions>,
    ) -> PyResult<ExecutionData> {
        match endpoint_id {
            Some(endpoint_id) => py_sync!(
                py,
                py_executable_data!(
                    self,
                    execute_on_qpu_with_endpoint,
                    quantum_processor_id,
                    endpoint_id,
                    translation_options,
                )
            ),
            None => py_sync!(
                py,
                py_executable_data!(
                    self,
                    execute_on_qpu,
                    quantum_processor_id,
                    translation_options,
                    &execution_options.unwrap_or_default(),
                )
            ),
        }
    }
    /// 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.
    #[pyo3(signature = (quantum_processor_id, endpoint_id = None, translation_options = None, execution_options = None))]
    pub fn execute_on_qpu_async<'py>(
        &self,
        py: Python<'py>,
        quantum_processor_id: String,
        endpoint_id: Option<String>,
        translation_options: Option<TranslationOptions>,
        execution_options: Option<ExecutionOptions>,
    ) -> PyResult<Awaitable<'py, ExecutionData>> {
        match endpoint_id {
            Some(endpoint_id) => pyo3_async_runtimes::tokio::future_into_py(
                py,
                py_executable_data!(
                    self,
                    execute_on_qpu_with_endpoint,
                    quantum_processor_id,
                    endpoint_id,
                    translation_options,
                ),
            ),
            None => pyo3_async_runtimes::tokio::future_into_py(
                py,
                py_executable_data!(
                    self,
                    execute_on_qpu,
                    quantum_processor_id,
                    translation_options,
                    &execution_options.unwrap_or_default(),
                ),
            ),
        }
        .map(Into::into)
    }

    /// 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.
    #[pyo3(signature = (quantum_processor_id, endpoint_id = None, translation_options = None, execution_options = None))]
    pub fn submit_to_qpu(
        &self,
        py: Python<'_>,
        quantum_processor_id: String,
        endpoint_id: Option<String>,
        translation_options: Option<TranslationOptions>,
        execution_options: Option<ExecutionOptions>,
    ) -> PyResult<PyJobHandle> {
        match endpoint_id {
            Some(endpoint_id) => py_sync!(
                py,
                py_job_handle!(
                    self,
                    submit_to_qpu_with_endpoint,
                    quantum_processor_id,
                    endpoint_id,
                    translation_options,
                )
            ),
            None => py_sync!(
                py,
                py_job_handle!(
                    self,
                    submit_to_qpu,
                    quantum_processor_id,
                    translation_options,
                    &execution_options.unwrap_or_default(),
                )
            ),
        }
    }

    /// 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.
    #[pyo3(signature = (quantum_processor_id, endpoint_id = None, translation_options = None, execution_options = None))]
    pub fn submit_to_qpu_async<'py>(
        &self,
        py: Python<'py>,
        quantum_processor_id: String,
        endpoint_id: Option<String>,
        translation_options: Option<TranslationOptions>,
        execution_options: Option<ExecutionOptions>,
    ) -> PyResult<Awaitable<'py, PyJobHandle>> {
        match endpoint_id {
            Some(endpoint_id) => pyo3_async_runtimes::tokio::future_into_py(
                py,
                py_job_handle!(
                    self,
                    submit_to_qpu_with_endpoint,
                    quantum_processor_id,
                    endpoint_id,
                    translation_options,
                ),
            ),
            None => pyo3_async_runtimes::tokio::future_into_py(
                py,
                py_job_handle!(
                    self,
                    submit_to_qpu,
                    quantum_processor_id,
                    translation_options,
                    &execution_options.unwrap_or_default(),
                ),
            ),
        }
        .map(Into::into)
    }

    /// Wait for the results of a job to complete.
    ///
    /// :raises `ExecutionError`: If the job fails to execute.
    pub fn retrieve_results(
        &self,
        py: Python<'_>,
        job_handle: PyJobHandle,
    ) -> PyResult<ExecutionData> {
        py_sync!(
            py,
            py_executable_data!(self, retrieve_results, job_handle.0)
        )
    }

    /// Wait for the results of a job to complete
    /// (async analog of `Executable.retrieve_results`).
    ///
    /// :raises `ExecutionError`: If the job fails to execute.
    pub fn retrieve_results_async<'py>(
        &self,
        py: Python<'py>,
        job_handle: PyJobHandle,
    ) -> PyResult<Awaitable<'py, ExecutionData>> {
        pyo3_async_runtimes::tokio::future_into_py(
            py,
            py_executable_data!(self, retrieve_results, job_handle.0),
        )
        .map(Into::into)
    }
}

/// Program execution parameters.
///
/// Note: The validity of parameters is not checked until execution.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[pyclass(module = "qcs_sdk", get_all, set_all)]
pub(crate) struct ExeParameter {
    name: String,
    index: usize,
    value: f64,
}

#[cfg_attr(feature = "stubs", gen_stub_pymethods)]
#[pymethods]
impl ExeParameter {
    #[new]
    fn __new__(name: String, index: usize, value: f64) -> Self {
        Self { name, index, value }
    }
}