qcs 0.26.1

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
use std::collections::HashMap;
use std::convert::TryFrom;
use std::f64::consts::{FRAC_PI_2, PI};

use serde::{Deserialize, Serialize};

use qcs_api_client_openapi::models::{Characteristic, Node, Operation};

use super::operator::{
    self, wildcard, Argument, Operator, Parameter, PERFECT_DURATION, PERFECT_FIDELITY,
};

/// Represents a single Qubit on a QPU and its capabilities. Needed by quilc for optimization.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub(crate) struct Qubit {
    id: i64,
    #[serde(skip_serializing_if = "is_false")]
    #[serde(default)]
    dead: bool,
    gates: Vec<Operator>,
}

// Gross hack to not include `dead` if unneeded, to follow pyQuil's implementation
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(val: &bool) -> bool {
    !*val
}

impl Qubit {
    pub(crate) fn from_nodes(nodes: &[Node]) -> HashMap<i64, Qubit> {
        nodes
            .iter()
            .map(|node| (node.node_id, Qubit::from(node)))
            .collect()
    }

    /// Add an operation to a particular Qubit.
    ///
    /// In the QCS ISA, the definition of Qubits is separate from the definition of which operations
    /// those Qubits can perform and what stats (fidelity, timing, etc.) they have. Those operations
    /// are defined later, and must be added to the defined Qubits via this function.
    ///
    /// # Arguments
    /// 1. `op_name`: The name of the operation defined on this Qubit. This comes from
    ///    `instructions[n].name` in the QCS response.
    /// 2. `characteristics`: Data related to the operation at a this site (Qubit). Comes from
    ///    `instructions[n].sites[m].characteristics` in the QCS response.
    /// 3. `benchmarks`: Top level benchmarks on the Qubits, comes from `benchmarks` in the QCS
    ///    response.
    ///
    /// # Errors
    /// 1. `randomized_benchmark_simultaneous_1q` was not present in `benchmarks`: this is necessary
    ///    for RX and RZ gates.
    /// 2. An unknown `op_name` was provided.
    pub(crate) fn add_operation(
        &mut self,
        op_name: &str,
        characteristics: &[Characteristic],
        frb_sim_1q: &FrbSim1q,
    ) -> Result<(), Error> {
        let operators = match op_name {
            "RX" => rx_gates(self.id, frb_sim_1q)?,
            "RZ" => rz_gates(self.id),
            "MEASURE" => measure(self.id, characteristics),
            "WILDCARD" => vec![wildcard(Some(self.id))],
            "I" | "RESET" => vec![],
            unknown => return Err(Error::UnknownOperator(String::from(unknown))),
        };
        self.gates.extend(operators);
        self.dead = false;
        Ok(())
    }
}

/// All the errors that can occur within this module.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("Required benchmark `randomized_benchmark_simultaneous_1q` was not present")]
    MissingBenchmark,
    #[error("Benchmark `randomized_benchmark_simultaneous_1q` must have a single call site")]
    InvalidBenchmark,
    #[error("Benchmark missing for qubit {0}")]
    MissingBenchmarkForQubit(i64),
    #[error("Unknown operator {0}")]
    UnknownOperator(String),
}

impl From<&Node> for Qubit {
    fn from(node: &Node) -> Self {
        Self {
            id: node.node_id,
            dead: true,
            gates: vec![],
        }
    }
}

#[cfg(test)]
mod describe_qubit {
    use super::Qubit;

    #[test]
    fn it_skips_serializing_dead_if_false() {
        let undead_qubit = Qubit {
            id: 0,
            dead: false,
            gates: vec![],
        };
        let dead_qubit = Qubit {
            id: 0,
            dead: true,
            gates: vec![],
        };

        let expected_dead = serde_json::json!({
            "id": 0,
            "dead": true,
            "gates": []
        });
        let expected_undead = serde_json::json!({
            "id": 0,
            "gates": []
        });

        let undead = serde_json::to_value(undead_qubit).unwrap();
        let dead = serde_json::to_value(dead_qubit).unwrap();

        assert_eq!(undead, expected_undead);
        assert_eq!(dead, expected_dead);
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct FrbSim1q(Vec<Characteristic>);

impl TryFrom<Vec<Operation>> for FrbSim1q {
    type Error = Error;

    fn try_from(ops: Vec<Operation>) -> Result<FrbSim1q, Error> {
        const BENCH_NAME: &str = "randomized_benchmark_simultaneous_1q";
        let mut operation = ops
            .into_iter()
            .find(|op| op.name == BENCH_NAME)
            .ok_or(Error::MissingBenchmark)?;
        if operation.sites.len() != 1 {
            return Err(Error::InvalidBenchmark);
        }
        let site = operation.sites.remove(0);

        Ok(Self(site.characteristics))
    }
}

impl FrbSim1q {
    fn fidelity_for_qubit(&self, qubit: i64) -> Result<f64, Error> {
        self.0
            .iter()
            .find(|characteristic| {
                characteristic
                    .node_ids
                    .as_ref()
                    .is_some_and(|node_ids| node_ids.len() == 1 && node_ids[0] == qubit)
            })
            .map(|characteristic| characteristic.value)
            .ok_or(Error::MissingBenchmarkForQubit(qubit))
    }
}

const DEFAULT_DURATION_RX: f64 = 50.0;

fn rx_gates(node_id: i64, frb_sim_1q: &FrbSim1q) -> Result<Vec<Operator>, Error> {
    let fidelity = frb_sim_1q
        .fidelity_for_qubit(node_id)
        .or_else(|e| match e {
            // Prevents compilation error when building without the `tracing` feature flag
            #[allow(unused_variables)]
            error @ Error::MissingBenchmarkForQubit(_) => {
                #[cfg(feature = "tracing")]
                tracing::warn!(%error);
                Ok(0.0)
            }
            _ => Err(e),
        })?;
    let mut gates = Vec::with_capacity(5);
    let operator = "RX".to_string();
    gates.push(Operator::Gate {
        operator: operator.clone(),
        parameters: vec![Parameter::Float(0.0)],
        arguments: vec![Argument::Int(node_id)],
        fidelity: 1.0,
        duration: DEFAULT_DURATION_RX,
    });

    gates.extend(
        IntoIterator::into_iter([PI, -PI, FRAC_PI_2, -FRAC_PI_2]).map(|param| Operator::Gate {
            operator: operator.clone(),
            parameters: vec![Parameter::Float(param)],
            arguments: vec![Argument::Int(node_id)],
            fidelity,
            duration: DEFAULT_DURATION_RX,
        }),
    );
    Ok(gates)
}

#[cfg(test)]
mod describe_rx_gates {
    use std::f64::consts::{FRAC_PI_2, PI};

    use qcs_api_client_openapi::models::Characteristic;

    use super::super::{
        operator::{Argument, Operator, Parameter},
        qubit::{rx_gates, FrbSim1q},
    };

    /// This data is copied from the pyQuil ISA integration test.
    #[test]
    fn it_passes_the_pyquil_aspen_8_test() {
        let node_id = 1;
        let frb_sim_1q = FrbSim1q(vec![
            Characteristic {
                name: "fRB".to_string(),
                value: 0.989_821_55,
                error: Some(0.000_699_235_5),
                node_ids: Some(vec![0]),
                parameter_values: None,
                timestamp: "1970-01-01T00:00:00+00:00".to_string(),
            },
            Characteristic {
                name: "fRB".to_string(),
                value: 0.996_832_6,
                error: Some(0.000_100_896_78),
                node_ids: Some(vec![1]),
                timestamp: "1970-01-01T00:00:00+00:00".to_string(),
                parameter_values: None,
            },
        ]);
        let gates = rx_gates(node_id, &frb_sim_1q).expect("Should create RX gates");
        let expected = vec![
            Operator::Gate {
                arguments: vec![Argument::Int(1)],
                duration: 50.0,
                fidelity: 1.0,
                operator: "RX".to_string(),
                parameters: vec![Parameter::Float(0.0)],
            },
            Operator::Gate {
                arguments: vec![Argument::Int(1)],
                duration: 50.0,
                fidelity: 0.996_832_6,
                operator: "RX".to_string(),
                parameters: vec![Parameter::Float(PI)],
            },
            Operator::Gate {
                arguments: vec![Argument::Int(1)],
                duration: 50.0,
                fidelity: 0.996_832_6,
                operator: "RX".to_string(),
                parameters: vec![Parameter::Float(-PI)],
            },
            Operator::Gate {
                arguments: vec![Argument::Int(1)],
                duration: 50.0,
                fidelity: 0.996_832_6,
                operator: "RX".to_string(),
                parameters: vec![Parameter::Float(FRAC_PI_2)],
            },
            Operator::Gate {
                arguments: vec![Argument::Int(1)],
                duration: 50.0,
                fidelity: 0.996_832_6,
                operator: "RX".to_string(),
                parameters: vec![Parameter::Float(-FRAC_PI_2)],
            },
        ];
        assert_eq!(gates, expected);
    }

    #[test]
    fn it_defaults_to_0_for_missing_benchmark() {
        let frb_sim_1q = FrbSim1q(Vec::new());
        let gates = rx_gates(1, &frb_sim_1q).expect("should not error for missing benchmark");
        let expected = vec![
            Operator::Gate {
                arguments: vec![Argument::Int(1)],
                duration: 50.0,
                fidelity: 1.0,
                operator: "RX".to_string(),
                parameters: vec![Parameter::Float(0.0)],
            },
            Operator::Gate {
                arguments: vec![Argument::Int(1)],
                duration: 50.0,
                fidelity: 0.0,
                operator: "RX".to_string(),
                parameters: vec![Parameter::Float(PI)],
            },
            Operator::Gate {
                arguments: vec![Argument::Int(1)],
                duration: 50.0,
                fidelity: 0.0,
                operator: "RX".to_string(),
                parameters: vec![Parameter::Float(-PI)],
            },
            Operator::Gate {
                arguments: vec![Argument::Int(1)],
                duration: 50.0,
                fidelity: 0.0,
                operator: "RX".to_string(),
                parameters: vec![Parameter::Float(FRAC_PI_2)],
            },
            Operator::Gate {
                arguments: vec![Argument::Int(1)],
                duration: 50.0,
                fidelity: 0.0,
                operator: "RX".to_string(),
                parameters: vec![Parameter::Float(-FRAC_PI_2)],
            },
        ];
        assert_eq!(gates, expected);
    }
}

fn rz_gates(node_id: i64) -> Vec<Operator> {
    vec![Operator::Gate {
        operator: "RZ".to_string(),
        parameters: vec![Parameter::String("_".to_owned())],
        fidelity: PERFECT_FIDELITY,
        duration: PERFECT_DURATION,
        arguments: vec![Argument::Int(node_id)],
    }]
}

#[cfg(test)]
mod describe_rz_gates {
    use super::{rz_gates, Argument, Operator, Parameter};

    /// This data is copied from the pyQuil ISA integration test.
    #[test]
    fn it_passes_the_pyquil_aspen_8_test() {
        let node_id = 1;
        let gates = rz_gates(node_id);
        let expected = vec![Operator::Gate {
            arguments: vec![Argument::Int(1)],
            duration: 0.01,
            fidelity: 1.0,
            operator: "RZ".to_string(),
            parameters: vec![Parameter::String("_".to_owned())],
        }];
        assert_eq!(gates, expected);
    }
}

const MEASURE_DEFAULT_DURATION: f64 = 2000.0;
const MEASURE_DEFAULT_FIDELITY: f64 = 0.90;

/// Process a "MEASURE" operation.
fn measure(node_id: i64, characteristics: &[Characteristic]) -> Vec<Operator> {
    let fidelity = characteristics
        .iter()
        .find(|characteristic| &characteristic.name == "fRO")
        .map_or(MEASURE_DEFAULT_FIDELITY, |characteristic| {
            characteristic.value
        });

    vec![
        Operator::Measure {
            operator: "MEASURE".to_string(),
            duration: MEASURE_DEFAULT_DURATION,
            fidelity,
            qubit: operator::Qubit::Int(node_id),
            target: Some("_".to_string()),
        },
        Operator::Measure {
            operator: "MEASURE".to_string(),
            duration: MEASURE_DEFAULT_DURATION,
            fidelity,
            qubit: operator::Qubit::Int(node_id),
            target: None,
        },
    ]
}

#[cfg(test)]
mod describe_measure {
    use qcs_api_client_openapi::models::Characteristic;

    use super::{super::operator, measure, Operator};

    /// This test copies data from pyQuil's integration test for ISA conversion.
    #[test]
    fn it_passes_pyquil_integration() {
        let characteristics = [Characteristic {
            error: None,
            name: String::from("fRO"),
            node_ids: None,
            parameter_values: None,
            timestamp: "1970-01-01T00:00:00+00:00".to_string(),
            value: 0.981,
        }];
        let result = measure(0, &characteristics);
        let expected = vec![
            Operator::Measure {
                operator: "MEASURE".to_string(),
                duration: 2000.0,
                fidelity: 0.981,
                qubit: operator::Qubit::Int(0),
                target: Some("_".to_string()),
            },
            Operator::Measure {
                operator: "MEASURE".to_string(),
                duration: 2000.0,
                fidelity: 0.981,
                qubit: operator::Qubit::Int(0),
                target: None,
            },
        ];
        assert_eq!(result, expected);
    }
}