tk-pg-core 0.1.1

Core types and pass interfaces for Pauli graphs
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
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::errors::PauliGraphError;
use crate::{GateType, Pauli};

pub(crate) fn string_to_paulis(pstr: &str) -> Result<Vec<Pauli>, PauliGraphError> {
    pstr.chars()
        .map(|pauli| match pauli {
            'I' => Ok(Pauli::I),
            'X' => Ok(Pauli::X),
            'Y' => Ok(Pauli::Y),
            'Z' => Ok(Pauli::Z),
            _ => Err(PauliGraphError::InvalidInputJson(format!(
                "Invalid Pauli string: contains invalid character: {}",
                pauli
            ))),
        })
        .collect()
}

fn paulis_to_string(paulis: &[Pauli]) -> String {
    paulis
        .iter()
        .map(|p| match p {
            Pauli::I => 'I',
            Pauli::X => 'X',
            Pauli::Y => 'Y',
            Pauli::Z => 'Z',
        })
        .collect()
}

fn serialize_pauli_string<S>(v: &[Pauli], s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    s.serialize_str(&paulis_to_string(v))
}

fn serialize_pauli_string_bool_vec<S>(v: &Vec<(Vec<Pauli>, bool)>, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    use serde::ser::SerializeSeq;
    let mut seq = s.serialize_seq(Some(v.len()))?;
    for (paulis, sign_bit) in v {
        seq.serialize_element(&(paulis_to_string(paulis), sign_bit))?;
    }
    seq.end()
}

fn deserialize_pauli_string<'de, D>(deserializer: D) -> Result<Vec<Pauli>, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    string_to_paulis(&s).map_err(serde::de::Error::custom)
}

fn deserialize_pauli_string_bool_vec<'de, D>(
    deserializer: D,
) -> Result<Vec<(Vec<Pauli>, bool)>, D::Error>
where
    D: Deserializer<'de>,
{
    let items = Vec::<(String, bool)>::deserialize(deserializer)?;
    items
        .into_iter()
        .map(|(s, sign_bit)| {
            Ok((
                string_to_paulis(&s).map_err(serde::de::Error::custom)?,
                sign_bit,
            ))
        })
        .collect()
}

/// An operation node in a Pauli graph.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(tag = "type")]
pub enum Op {
    /// A Pauli rotation.
    Rotation {
        /// rotation data
        data: RotationData,
    },
    /// A measurement operation.
    Measure {
        /// measurement data
        data: MeasureData,
    },
    /// A reset operation.
    Reset {
        /// reset data
        data: ResetData,
    },
    /// An opaque operation.
    BlackBox {
        /// blackbox data
        data: BlackBoxData,
    },
    /// A box of operations with classical conditions.
    ConditionalBox {
        /// conditional box data
        data: ConditionalBoxData,
    },
    /// A forward facing Clifford tableau operation.
    Tableau {
        /// tableau data
        data: TableauData,
    },
    /// A gate operation.
    Gate {
        /// gate data
        data: GateData,
    },
    /// Special op to indicate commuting boundaries, which can be treated as identities in many passes.
    SetBoundary,
}

/// Data associated with a Pauli rotation.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct RotationData {
    #[serde(
        serialize_with = "serialize_pauli_string",
        deserialize_with = "deserialize_pauli_string"
    )]
    pub(crate) string: Vec<Pauli>,
    angle: f64,
}

impl RotationData {
    /// Creates rotation data from a Pauli string and rotation angle.
    pub fn new(string: Vec<Pauli>, angle: f64) -> Self {
        Self { string, angle }
    }

    /// Returns the Pauli string acted on by the rotation.
    pub fn get_string(&self) -> &Vec<Pauli> {
        &self.string
    }

    /// Returns the rotation angle.
    pub fn get_angle(&self) -> f64 {
        self.angle
    }
}

/// Data associated with a Pauli measurement.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct MeasureData {
    #[serde(
        serialize_with = "serialize_pauli_string",
        deserialize_with = "deserialize_pauli_string"
    )]
    pub(crate) string: Vec<Pauli>,
    sign_bit: bool,
    cbit: usize,
}

impl MeasureData {
    /// Creates measurement data from a Pauli string, sign bit, and classical bit target.
    /// `false` represents a positive sign and `true` represents a negative sign.
    pub fn new(string: Vec<Pauli>, sign_bit: bool, cbit: usize) -> Self {
        Self {
            string,
            sign_bit,
            cbit,
        }
    }

    /// Returns the measured Pauli string.
    pub fn get_string(&self) -> &Vec<Pauli> {
        &self.string
    }

    /// Returns the sign bit of the Pauli string (`false` = positive, `true` = negative).
    pub fn get_sign_bit(&self) -> bool {
        self.sign_bit
    }

    /// Returns the destination classical bit.
    pub fn get_cbit(&self) -> usize {
        self.cbit
    }
}

/// Data associated with a reset operation.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ResetData {
    #[serde(
        serialize_with = "serialize_pauli_string",
        deserialize_with = "deserialize_pauli_string"
    )]
    pub(crate) first_string: Vec<Pauli>,
    #[serde(
        serialize_with = "serialize_pauli_string",
        deserialize_with = "deserialize_pauli_string"
    )]
    pub(crate) second_string: Vec<Pauli>,
    first_sign_bit: bool,
    second_sign_bit: bool,
}

impl ResetData {
    /// Creates reset data from two anti-commuting Pauli strings and their sign bits.
    /// `false` represents a positive sign and `true` represents a negative sign.
    pub fn new(
        first_string: Vec<Pauli>,
        second_string: Vec<Pauli>,
        first_sign_bit: bool,
        second_sign_bit: bool,
    ) -> Self {
        Self {
            first_string,
            second_string,
            first_sign_bit,
            second_sign_bit,
        }
    }

    /// Returns the first Pauli string involved in the reset.
    pub fn get_first_string(&self) -> &Vec<Pauli> {
        &self.first_string
    }

    /// Returns the second Pauli string involved in the reset.
    pub fn get_second_string(&self) -> &Vec<Pauli> {
        &self.second_string
    }

    /// Returns the first string's sign bit (`false` = positive, `true` = negative).
    pub fn get_first_sign_bit(&self) -> bool {
        self.first_sign_bit
    }

    /// Returns the second string's sign bit (`false` = positive, `true` = negative).
    pub fn get_second_sign_bit(&self) -> bool {
        self.second_sign_bit
    }
}

/// Data associated with an opaque black-box operation.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct BlackBoxData {
    qubits: Vec<usize>,
    content: String,
}

impl BlackBoxData {
    /// Creates black-box data for the provided qubits and payload string.
    pub fn new(qubits: Vec<usize>, content: String) -> Self {
        Self { qubits, content }
    }

    /// Returns the qubits touched by the black-box operation.
    pub fn get_qubits(&self) -> &Vec<usize> {
        &self.qubits
    }

    /// Returns the opaque payload content.
    pub fn get_content(&self) -> &String {
        &self.content
    }
}

/// Data for a conditional box of operations.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ConditionalBoxData {
    conditional_bits: Vec<usize>,
    conditional_values: Vec<bool>,
    pub(crate) ops: Vec<Op>,
}

impl ConditionalBoxData {
    /// Creates a conditional box from its operations and classical control values.
    pub fn new(ops: Vec<Op>, conditional_bits: Vec<usize>, conditional_values: Vec<bool>) -> Self {
        Self {
            conditional_bits,
            conditional_values,
            ops,
        }
    }

    /// Returns the classical bits used as conditions.
    pub fn get_conditional_bits(&self) -> &Vec<usize> {
        &self.conditional_bits
    }

    /// Returns the boolean values required on the conditional bits.
    pub fn get_conditional_values(&self) -> &Vec<bool> {
        &self.conditional_values
    }

    /// Returns the operations contained in the box.
    pub fn get_ops(&self) -> &Vec<Op> {
        &self.ops
    }
}

/// Tableau image data for a Clifford operation.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct TableauData {
    #[serde(
        serialize_with = "serialize_pauli_string_bool_vec",
        deserialize_with = "deserialize_pauli_string_bool_vec"
    )]
    pub(crate) z_images: Vec<(Vec<Pauli>, bool)>,
    #[serde(
        serialize_with = "serialize_pauli_string_bool_vec",
        deserialize_with = "deserialize_pauli_string_bool_vec"
    )]
    pub(crate) x_images: Vec<(Vec<Pauli>, bool)>,
}

impl TableauData {
    /// Creates tableau data from the images of the input $Z$ and $X$ operators.
    /// Each image Boolean is a sign bit (`false` = positive, `true` = negative).
    pub fn new(z_images: Vec<(Vec<Pauli>, bool)>, x_images: Vec<(Vec<Pauli>, bool)>) -> Self {
        Self { z_images, x_images }
    }

    /// Returns the images of the input $Z$ operators and their sign bits.
    pub fn get_z_images(&self) -> &Vec<(Vec<Pauli>, bool)> {
        &self.z_images
    }

    /// Returns the images of the input $X$ operators and their sign bits.
    pub fn get_x_images(&self) -> &Vec<(Vec<Pauli>, bool)> {
        &self.x_images
    }
}

/// Data associated with a gate operation.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GateData {
    gate_type: GateType,
    params: Vec<f64>,
    args: Vec<usize>,
    data: Option<String>,
    conditional_bits: Vec<usize>,
    conditional_values: Vec<bool>,
}

impl GateData {
    /// Creates gate data with a gate type and positional arguments.
    pub fn new(gate_type: GateType, args: Vec<usize>) -> Self {
        Self {
            gate_type,
            params: vec![],
            args,
            data: None,
            conditional_bits: vec![],
            conditional_values: vec![],
        }
    }

    /// Sets the floating-point parameters associated with the gate.
    pub fn with_params(mut self, params: Vec<f64>) -> Self {
        self.params = params;
        self
    }

    /// Sets the optional opaque payload associated with the gate.
    pub fn with_data(mut self, data: String) -> Self {
        self.data = Some(data);
        self
    }

    /// Sets the classical conditions required for the gate to execute.
    pub fn with_conditional(
        mut self,
        conditional_bits: Vec<usize>,
        conditional_values: Vec<bool>,
    ) -> Self {
        self.conditional_bits = conditional_bits;
        self.conditional_values = conditional_values;
        self
    }

    /// Returns the gate type.
    pub fn get_gate_type(&self) -> &GateType {
        &self.gate_type
    }

    /// Returns the gate parameters.
    pub fn get_params(&self) -> &Vec<f64> {
        &self.params
    }

    /// Returns the gate argument indices.
    pub fn get_args(&self) -> &Vec<usize> {
        &self.args
    }

    /// Returns the optional opaque gate payload.
    pub fn get_data(&self) -> &Option<String> {
        &self.data
    }

    /// Returns the classical bits used as conditions.
    pub fn get_conditional_bits(&self) -> &Vec<usize> {
        &self.conditional_bits
    }

    /// Returns the required values for the classical conditions.
    pub fn get_conditional_values(&self) -> &Vec<bool> {
        &self.conditional_values
    }
}