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
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
//! This module provides types and functions for making HTTP-based API calls to the QVM.
//! Consider [`super::run_program`] for higher level access to the QVM that allows
//! for running parameterized programs.
use std::{collections::HashMap, num::NonZeroU16};

#[cfg(feature = "stubs")]
use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pyclass_complex_enum};

use reqwest::Response;
use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::{client::Qcs, RegisterData};

use super::{Error, QvmOptions};

#[derive(Serialize, Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
enum RequestType {
    Multishot,
    MultishotMeasure,
    Expectation,
    Wavefunction,
}

#[derive(Debug, Deserialize, Clone, Eq, PartialEq)]
pub(super) struct Failure {
    /// The message from QVM describing what went wrong.
    pub(super) status: String,
}

/// A QVM response that can be deserialized into some successful response type `T`, or into a
/// [`Failure`] containing an error message.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(untagged)]
pub(super) enum QvmResponse<T>
where
    T: DeserializeOwned,
{
    // This bound is required for `T` to be recognized as being `Deserialize`
    // https://github.com/serde-rs/serde/issues/1296
    #[serde(bound = "")]
    Success(T),
    Failure(Failure),
}

impl<T: DeserializeOwned> QvmResponse<T> {
    /// Converts a [`QvmResponse<T>`] into a [`Result<T, qvm::Error>`] containing the successful response,
    /// as the Ok value or an [`Error`] containing the error message from the [`Failure`] response.
    pub(super) fn into_result(self) -> Result<T, Error> {
        match self {
            Self::Success(response) => Ok(response),
            Self::Failure(response) => Err(Error::Qvm {
                message: response.status,
            }),
        }
    }
}

/// The request body needed to make a multishot [`run`] request to the QVM.
#[derive(Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(not(feature = "python"), optipy::strip_pyo3)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyo3::pyclass(module = "qcs_sdk.qvm.api"))]
pub struct MultishotRequest {
    /// The Quil program to run.
    #[pyo3(get, set)]
    pub compiled_quil: String,
    /// The memory regions to include in the response.
    #[pyo3(get, set)]
    pub addresses: HashMap<String, AddressRequest>,
    /// The number of trials ("shots") to run.
    // This also has a Python getter method, but it's defined directly to set the stub return type.
    pub trials: NonZeroU16,
    /// Simulated measurement noise for the X, Y, and Z axes.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[pyo3(get, set)]
    pub measurement_noise: Option<(f64, f64, f64)>,
    /// Simulated gate noise for the X, Y, and Z axes.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[pyo3(get, set)]
    pub gate_noise: Option<(f64, f64, f64)>,
    /// An optional seed for the random number generator.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[pyo3(get, set)]
    pub rng_seed: Option<i64>,
    #[serde(rename = "type")]
    request_type: RequestType,
}

/// An enum encapsulating the different ways to request data back from the QVM for an address.
#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
#[serde(untagged)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass_complex_enum)]
#[cfg_attr(feature = "python", pyo3::pyclass(module = "qcs_sdk.qvm.api", eq))]
pub enum AddressRequest {
    /// Get all values for the address.
    #[serde(serialize_with = "serialize_true")]
    IncludeAll(),
    /// Exclude all values for the address.
    #[serde(serialize_with = "serialize_false")]
    ExcludeAll(),
    /// A list of specific indices to get back for the address.
    Indices(Vec<usize>),
}

fn serialize_true<S>(serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_bool(true)
}

fn serialize_false<S>(serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_bool(false)
}

impl MultishotRequest {
    /// Creates a new [`MultishotRequest`] with the given parameters.
    #[must_use]
    pub fn new(
        compiled_quil: String,
        trials: NonZeroU16,
        addresses: HashMap<String, AddressRequest>,
        measurement_noise: Option<(f64, f64, f64)>,
        gate_noise: Option<(f64, f64, f64)>,
        rng_seed: Option<i64>,
    ) -> Self {
        Self {
            compiled_quil,
            addresses,
            trials,
            measurement_noise,
            gate_noise,
            rng_seed,
            request_type: RequestType::Multishot,
        }
    }
}

/// The response body returned by the QVM after a multishot [`run`] request.
#[derive(Debug, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyo3::pyclass(module = "qcs_sdk.qvm.api", get_all))]
pub struct MultishotResponse {
    /// The requested readout registers and their final values for each shot.
    #[serde(flatten)]
    pub registers: HashMap<String, RegisterData>,
}

/// The request body needed for a [`run_and_measure`] request to the QVM.
#[derive(Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(not(feature = "python"), optipy::strip_pyo3)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyo3::pyclass(module = "qcs_sdk.qvm.api"))]
pub struct MultishotMeasureRequest {
    /// The Quil program to run.
    #[pyo3(get)]
    pub compiled_quil: String,
    /// The number of trials ("shots") to run the program.
    // This also has a Python getter method, but it's defined directly to set the stub return type.
    pub trials: NonZeroU16,
    /// Qubits to measure
    #[pyo3(get)]
    pub qubits: Vec<u64>,
    /// Simulated measurement noise for the X, Y, and Z axes.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[pyo3(get)]
    pub measurement_noise: Option<(f64, f64, f64)>,
    /// Simulated gate noise for the X, Y, and Z axes.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[pyo3(get)]
    pub gate_noise: Option<(f64, f64, f64)>,
    /// An optional seed for the random number generator.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[pyo3(get)]
    pub rng_seed: Option<i64>,
    #[serde(rename = "type")]
    request_type: RequestType,
}

impl MultishotMeasureRequest {
    /// Construct a new [`MultishotMeasureRequest`] using the given parameters.
    #[must_use]
    pub fn new(
        compiled_quil: String,
        trials: NonZeroU16,
        qubits: &[u64],
        measurement_noise: Option<(f64, f64, f64)>,
        gate_noise: Option<(f64, f64, f64)>,
        rng_seed: Option<i64>,
    ) -> Self {
        Self {
            compiled_quil,
            trials,
            qubits: qubits.to_vec(),
            measurement_noise,
            gate_noise,
            rng_seed,
            request_type: RequestType::MultishotMeasure,
        }
    }
}

/// The request body needed for a [`measure_expectation`] request to the QVM.
#[derive(Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(not(feature = "python"), optipy::strip_pyo3)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyo3::pyclass(module = "qcs_sdk.qvm.api"))]
pub struct ExpectationRequest {
    /// A Quil program defining the state.
    #[pyo3(get)]
    pub state_preparation: String,
    /// A list of Pauli operators to measure.
    #[pyo3(get)]
    pub operators: Vec<String>,
    /// An optional seed for the random number generator.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[pyo3(get)]
    pub rng_seed: Option<i64>,
    #[serde(rename = "type")]
    request_type: RequestType,
}

impl ExpectationRequest {
    /// Creates a new [`ExpectationRequest`] using the given parameters.
    #[must_use]
    pub fn new(state_preparation: String, operators: &[String], rng_seed: Option<i64>) -> Self {
        Self {
            state_preparation,
            operators: operators.to_vec(),
            rng_seed,
            request_type: RequestType::Expectation,
        }
    }
}

/// The request body needed to make a [`get_wavefunction`] request to the QVM.
#[derive(Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(not(feature = "python"), optipy::strip_pyo3)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyo3::pyclass(module = "qcs_sdk.qvm.api"))]
pub struct WavefunctionRequest {
    /// The Quil program to run.
    #[pyo3(get)]
    pub compiled_quil: String,
    /// Simulated measurement noise for the X, Y, and Z axes.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[pyo3(get)]
    pub measurement_noise: Option<(f64, f64, f64)>,
    /// Simulated gate noise for the X, Y, and Z axes.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[pyo3(get)]
    pub gate_noise: Option<(f64, f64, f64)>,
    /// An optional seed for the random number generator.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[pyo3(get)]
    pub rng_seed: Option<i64>,
    #[serde(rename = "type")]
    request_type: RequestType,
}

impl WavefunctionRequest {
    /// Create a new [`WavefunctionRequest`] with the given parameters.
    #[must_use]
    pub fn new(
        compiled_quil: String,
        measurement_noise: Option<(f64, f64, f64)>,
        gate_noise: Option<(f64, f64, f64)>,
        rng_seed: Option<i64>,
    ) -> Self {
        Self {
            compiled_quil,
            measurement_noise,
            gate_noise,
            rng_seed,
            request_type: RequestType::Wavefunction,
        }
    }
}

/// Provides HTTP-based access to QVM functionality
#[derive(Debug, Clone)]
#[allow(clippy::module_name_repetitions)]
pub struct HttpClient {
    client: reqwest::Client,
    /// Address used to connect to the QVM
    pub qvm_url: String,
}

impl HttpClient {
    /// Build a new [`HttpClient`] to connect to a QVM server at `qvm_url`.
    #[must_use]
    pub fn new(qvm_url: String) -> Self {
        let client = reqwest::Client::new();
        Self { client, qvm_url }
    }
}

impl From<&Qcs> for HttpClient {
    fn from(qcs: &Qcs) -> Self {
        Self::new(qcs.get_config().qvm_url().to_string())
    }
}

#[async_trait::async_trait]
impl super::Client for HttpClient {
    async fn get_version_info(&self, options: &QvmOptions) -> Result<String, Error> {
        #[cfg(feature = "tracing")]
        tracing::debug!("requesting qvm version information");
        let params = HashMap::from([("type", "version")]);
        let response = make_request(&params, self, options).await?;
        let qvm_url = self.qvm_url.clone();
        if response.status() == 200 {
            response
                .text()
                .await
                .map_err(|source| Error::QvmCommunication { qvm_url, source })
        } else {
            match response.json::<Failure>().await {
                Ok(Failure { status: message }) => Err(Error::Qvm { message }),
                Err(source) => Err(Error::QvmCommunication { qvm_url, source }),
            }
        }
    }

    async fn run(
        &self,
        request: &MultishotRequest,
        options: &QvmOptions,
    ) -> Result<MultishotResponse, Error> {
        #[cfg(feature = "tracing")]
        tracing::debug!("making a multishot request to the QVM");
        let response = make_request(request, self, options).await?;
        response
            .json::<QvmResponse<MultishotResponse>>()
            .await
            .map(QvmResponse::into_result)
            .map_err(|source| Error::QvmCommunication {
                qvm_url: self.qvm_url.clone(),
                source,
            })?
    }

    async fn run_and_measure(
        &self,
        request: &MultishotMeasureRequest,
        options: &QvmOptions,
    ) -> Result<Vec<Vec<i64>>, Error> {
        let response = make_request(request, self, options).await?;
        response
            .json::<QvmResponse<Vec<Vec<i64>>>>()
            .await
            .map(QvmResponse::into_result)
            .map_err(|source| Error::QvmCommunication {
                qvm_url: self.qvm_url.clone(),
                source,
            })?
    }

    async fn measure_expectation(
        &self,
        request: &ExpectationRequest,
        options: &QvmOptions,
    ) -> Result<Vec<f64>, Error> {
        let response = make_request(request, self, options).await?;
        response
            .json::<QvmResponse<Vec<f64>>>()
            .await
            .map(QvmResponse::into_result)
            .map_err(|source| Error::QvmCommunication {
                qvm_url: self.qvm_url.clone(),
                source,
            })?
    }

    async fn get_wavefunction(
        &self,
        request: &WavefunctionRequest,
        options: &QvmOptions,
    ) -> Result<Vec<u8>, Error> {
        let response = make_request(request, self, options).await?;
        if response.status() == 200 {
            response
                .bytes()
                .await
                .map(Into::into)
                .map_err(|source| Error::QvmCommunication {
                    qvm_url: self.qvm_url.clone(),
                    source,
                })
        } else {
            match response.json::<Failure>().await {
                Ok(Failure { status: message }) => Err(Error::Qvm { message }),
                Err(source) => Err(Error::QvmCommunication {
                    qvm_url: self.qvm_url.clone(),
                    source,
                }),
            }
        }
    }
}

async fn make_request<T>(
    request: &T,
    client: &HttpClient,
    options: &QvmOptions,
) -> Result<Response, Error>
where
    T: Serialize,
{
    let mut post = client.client.post(&client.qvm_url).json(request);
    if let Some(timeout) = options.timeout {
        post = post.timeout(timeout);
    }
    post.send().await.map_err(|source| Error::QvmCommunication {
        qvm_url: client.qvm_url.clone(),
        source,
    })
}

#[cfg(test)]
mod describe_request {
    use std::{collections::HashMap, num::NonZeroU16};

    use crate::qvm::http::AddressRequest;

    use super::MultishotRequest;

    #[test]
    fn it_includes_the_program() {
        let program = "H 0";
        let request = MultishotRequest::new(
            program.to_string(),
            NonZeroU16::new(1).expect("value is non-zero"),
            HashMap::new(),
            None,
            None,
            None,
        );
        assert_eq!(&request.compiled_quil, program);
    }

    #[test]
    fn it_uses_kebab_case_for_json() {
        let request = MultishotRequest::new(
            "H 0".to_string(),
            NonZeroU16::new(10).expect("value is non-zero"),
            [("ro".to_string(), AddressRequest::IncludeAll())]
                .iter()
                .cloned()
                .collect(),
            Some((1.0, 2.0, 3.0)),
            Some((3.0, 2.0, 1.0)),
            Some(100),
        );
        let json_string = serde_json::to_string(&request).expect("Could not serialize QVMRequest");
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&json_string).unwrap(),
            serde_json::json!({"type": "multishot", "addresses": {"ro": true}, "trials": 10, "compiled-quil": "H 0", "measurement-noise": [1.0, 2.0, 3.0], "gate-noise": [3.0, 2.0, 1.0], "rng-seed": 100})
        );
    }
}