Skip to main content

tk_pg_core/
ops.rs

1use serde::{Deserialize, Deserializer, Serialize, Serializer};
2
3use crate::errors::PauliGraphError;
4use crate::{GateType, Pauli};
5
6pub(crate) fn string_to_paulis(pstr: &str) -> Result<Vec<Pauli>, PauliGraphError> {
7    pstr.chars()
8        .map(|pauli| match pauli {
9            'I' => Ok(Pauli::I),
10            'X' => Ok(Pauli::X),
11            'Y' => Ok(Pauli::Y),
12            'Z' => Ok(Pauli::Z),
13            _ => Err(PauliGraphError::InvalidInputJson(format!(
14                "Invalid Pauli string: contains invalid character: {}",
15                pauli
16            ))),
17        })
18        .collect()
19}
20
21fn paulis_to_string(paulis: &[Pauli]) -> String {
22    paulis
23        .iter()
24        .map(|p| match p {
25            Pauli::I => 'I',
26            Pauli::X => 'X',
27            Pauli::Y => 'Y',
28            Pauli::Z => 'Z',
29        })
30        .collect()
31}
32
33fn serialize_pauli_string<S>(v: &[Pauli], s: S) -> Result<S::Ok, S::Error>
34where
35    S: Serializer,
36{
37    s.serialize_str(&paulis_to_string(v))
38}
39
40fn serialize_pauli_string_bool_vec<S>(v: &Vec<(Vec<Pauli>, bool)>, s: S) -> Result<S::Ok, S::Error>
41where
42    S: Serializer,
43{
44    use serde::ser::SerializeSeq;
45    let mut seq = s.serialize_seq(Some(v.len()))?;
46    for (paulis, sign_bit) in v {
47        seq.serialize_element(&(paulis_to_string(paulis), sign_bit))?;
48    }
49    seq.end()
50}
51
52fn deserialize_pauli_string<'de, D>(deserializer: D) -> Result<Vec<Pauli>, D::Error>
53where
54    D: Deserializer<'de>,
55{
56    let s = String::deserialize(deserializer)?;
57    string_to_paulis(&s).map_err(serde::de::Error::custom)
58}
59
60fn deserialize_pauli_string_bool_vec<'de, D>(
61    deserializer: D,
62) -> Result<Vec<(Vec<Pauli>, bool)>, D::Error>
63where
64    D: Deserializer<'de>,
65{
66    let items = Vec::<(String, bool)>::deserialize(deserializer)?;
67    items
68        .into_iter()
69        .map(|(s, sign_bit)| {
70            Ok((
71                string_to_paulis(&s).map_err(serde::de::Error::custom)?,
72                sign_bit,
73            ))
74        })
75        .collect()
76}
77
78/// An operation node in a Pauli graph.
79#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
80#[serde(tag = "type")]
81pub enum Op {
82    /// A Pauli rotation.
83    Rotation {
84        /// rotation data
85        data: RotationData,
86    },
87    /// A measurement operation.
88    Measure {
89        /// measurement data
90        data: MeasureData,
91    },
92    /// A reset operation.
93    Reset {
94        /// reset data
95        data: ResetData,
96    },
97    /// An opaque operation.
98    BlackBox {
99        /// blackbox data
100        data: BlackBoxData,
101    },
102    /// A box of operations with classical conditions.
103    ConditionalBox {
104        /// conditional box data
105        data: ConditionalBoxData,
106    },
107    /// A forward facing Clifford tableau operation.
108    Tableau {
109        /// tableau data
110        data: TableauData,
111    },
112    /// A gate operation.
113    Gate {
114        /// gate data
115        data: GateData,
116    },
117    /// Special op to indicate commuting boundaries, which can be treated as identities in many passes.
118    SetBoundary,
119}
120
121/// Data associated with a Pauli rotation.
122#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
123pub struct RotationData {
124    #[serde(
125        serialize_with = "serialize_pauli_string",
126        deserialize_with = "deserialize_pauli_string"
127    )]
128    pub(crate) string: Vec<Pauli>,
129    angle: f64,
130}
131
132impl RotationData {
133    /// Creates rotation data from a Pauli string and rotation angle.
134    pub fn new(string: Vec<Pauli>, angle: f64) -> Self {
135        Self { string, angle }
136    }
137
138    /// Returns the Pauli string acted on by the rotation.
139    pub fn get_string(&self) -> &Vec<Pauli> {
140        &self.string
141    }
142
143    /// Returns the rotation angle.
144    pub fn get_angle(&self) -> f64 {
145        self.angle
146    }
147}
148
149/// Data associated with a Pauli measurement.
150#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
151pub struct MeasureData {
152    #[serde(
153        serialize_with = "serialize_pauli_string",
154        deserialize_with = "deserialize_pauli_string"
155    )]
156    pub(crate) string: Vec<Pauli>,
157    sign_bit: bool,
158    cbit: usize,
159}
160
161impl MeasureData {
162    /// Creates measurement data from a Pauli string, sign bit, and classical bit target.
163    /// `false` represents a positive sign and `true` represents a negative sign.
164    pub fn new(string: Vec<Pauli>, sign_bit: bool, cbit: usize) -> Self {
165        Self {
166            string,
167            sign_bit,
168            cbit,
169        }
170    }
171
172    /// Returns the measured Pauli string.
173    pub fn get_string(&self) -> &Vec<Pauli> {
174        &self.string
175    }
176
177    /// Returns the sign bit of the Pauli string (`false` = positive, `true` = negative).
178    pub fn get_sign_bit(&self) -> bool {
179        self.sign_bit
180    }
181
182    /// Returns the destination classical bit.
183    pub fn get_cbit(&self) -> usize {
184        self.cbit
185    }
186}
187
188/// Data associated with a reset operation.
189#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
190pub struct ResetData {
191    #[serde(
192        serialize_with = "serialize_pauli_string",
193        deserialize_with = "deserialize_pauli_string"
194    )]
195    pub(crate) first_string: Vec<Pauli>,
196    #[serde(
197        serialize_with = "serialize_pauli_string",
198        deserialize_with = "deserialize_pauli_string"
199    )]
200    pub(crate) second_string: Vec<Pauli>,
201    first_sign_bit: bool,
202    second_sign_bit: bool,
203}
204
205impl ResetData {
206    /// Creates reset data from two anti-commuting Pauli strings and their sign bits.
207    /// `false` represents a positive sign and `true` represents a negative sign.
208    pub fn new(
209        first_string: Vec<Pauli>,
210        second_string: Vec<Pauli>,
211        first_sign_bit: bool,
212        second_sign_bit: bool,
213    ) -> Self {
214        Self {
215            first_string,
216            second_string,
217            first_sign_bit,
218            second_sign_bit,
219        }
220    }
221
222    /// Returns the first Pauli string involved in the reset.
223    pub fn get_first_string(&self) -> &Vec<Pauli> {
224        &self.first_string
225    }
226
227    /// Returns the second Pauli string involved in the reset.
228    pub fn get_second_string(&self) -> &Vec<Pauli> {
229        &self.second_string
230    }
231
232    /// Returns the first string's sign bit (`false` = positive, `true` = negative).
233    pub fn get_first_sign_bit(&self) -> bool {
234        self.first_sign_bit
235    }
236
237    /// Returns the second string's sign bit (`false` = positive, `true` = negative).
238    pub fn get_second_sign_bit(&self) -> bool {
239        self.second_sign_bit
240    }
241}
242
243/// Data associated with an opaque black-box operation.
244#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
245pub struct BlackBoxData {
246    qubits: Vec<usize>,
247    content: String,
248}
249
250impl BlackBoxData {
251    /// Creates black-box data for the provided qubits and payload string.
252    pub fn new(qubits: Vec<usize>, content: String) -> Self {
253        Self { qubits, content }
254    }
255
256    /// Returns the qubits touched by the black-box operation.
257    pub fn get_qubits(&self) -> &Vec<usize> {
258        &self.qubits
259    }
260
261    /// Returns the opaque payload content.
262    pub fn get_content(&self) -> &String {
263        &self.content
264    }
265}
266
267/// Data for a conditional box of operations.
268#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
269pub struct ConditionalBoxData {
270    conditional_bits: Vec<usize>,
271    conditional_values: Vec<bool>,
272    pub(crate) ops: Vec<Op>,
273}
274
275impl ConditionalBoxData {
276    /// Creates a conditional box from its operations and classical control values.
277    pub fn new(ops: Vec<Op>, conditional_bits: Vec<usize>, conditional_values: Vec<bool>) -> Self {
278        Self {
279            conditional_bits,
280            conditional_values,
281            ops,
282        }
283    }
284
285    /// Returns the classical bits used as conditions.
286    pub fn get_conditional_bits(&self) -> &Vec<usize> {
287        &self.conditional_bits
288    }
289
290    /// Returns the boolean values required on the conditional bits.
291    pub fn get_conditional_values(&self) -> &Vec<bool> {
292        &self.conditional_values
293    }
294
295    /// Returns the operations contained in the box.
296    pub fn get_ops(&self) -> &Vec<Op> {
297        &self.ops
298    }
299}
300
301/// Tableau image data for a Clifford operation.
302#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
303pub struct TableauData {
304    #[serde(
305        serialize_with = "serialize_pauli_string_bool_vec",
306        deserialize_with = "deserialize_pauli_string_bool_vec"
307    )]
308    pub(crate) z_images: Vec<(Vec<Pauli>, bool)>,
309    #[serde(
310        serialize_with = "serialize_pauli_string_bool_vec",
311        deserialize_with = "deserialize_pauli_string_bool_vec"
312    )]
313    pub(crate) x_images: Vec<(Vec<Pauli>, bool)>,
314}
315
316impl TableauData {
317    /// Creates tableau data from the images of the input $Z$ and $X$ operators.
318    /// Each image Boolean is a sign bit (`false` = positive, `true` = negative).
319    pub fn new(z_images: Vec<(Vec<Pauli>, bool)>, x_images: Vec<(Vec<Pauli>, bool)>) -> Self {
320        Self { z_images, x_images }
321    }
322
323    /// Returns the images of the input $Z$ operators and their sign bits.
324    pub fn get_z_images(&self) -> &Vec<(Vec<Pauli>, bool)> {
325        &self.z_images
326    }
327
328    /// Returns the images of the input $X$ operators and their sign bits.
329    pub fn get_x_images(&self) -> &Vec<(Vec<Pauli>, bool)> {
330        &self.x_images
331    }
332}
333
334/// Data associated with a gate operation.
335#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
336pub struct GateData {
337    gate_type: GateType,
338    params: Vec<f64>,
339    args: Vec<usize>,
340    data: Option<String>,
341    conditional_bits: Vec<usize>,
342    conditional_values: Vec<bool>,
343}
344
345impl GateData {
346    /// Creates gate data with a gate type and positional arguments.
347    pub fn new(gate_type: GateType, args: Vec<usize>) -> Self {
348        Self {
349            gate_type,
350            params: vec![],
351            args,
352            data: None,
353            conditional_bits: vec![],
354            conditional_values: vec![],
355        }
356    }
357
358    /// Sets the floating-point parameters associated with the gate.
359    pub fn with_params(mut self, params: Vec<f64>) -> Self {
360        self.params = params;
361        self
362    }
363
364    /// Sets the optional opaque payload associated with the gate.
365    pub fn with_data(mut self, data: String) -> Self {
366        self.data = Some(data);
367        self
368    }
369
370    /// Sets the classical conditions required for the gate to execute.
371    pub fn with_conditional(
372        mut self,
373        conditional_bits: Vec<usize>,
374        conditional_values: Vec<bool>,
375    ) -> Self {
376        self.conditional_bits = conditional_bits;
377        self.conditional_values = conditional_values;
378        self
379    }
380
381    /// Returns the gate type.
382    pub fn get_gate_type(&self) -> &GateType {
383        &self.gate_type
384    }
385
386    /// Returns the gate parameters.
387    pub fn get_params(&self) -> &Vec<f64> {
388        &self.params
389    }
390
391    /// Returns the gate argument indices.
392    pub fn get_args(&self) -> &Vec<usize> {
393        &self.args
394    }
395
396    /// Returns the optional opaque gate payload.
397    pub fn get_data(&self) -> &Option<String> {
398        &self.data
399    }
400
401    /// Returns the classical bits used as conditions.
402    pub fn get_conditional_bits(&self) -> &Vec<usize> {
403        &self.conditional_bits
404    }
405
406    /// Returns the required values for the classical conditions.
407    pub fn get_conditional_values(&self) -> &Vec<bool> {
408        &self.conditional_values
409    }
410}