Skip to main content

tk_pg_rebase/
tqe_rebase.rs

1use std::collections::HashSet;
2
3use tk_pg_core::{GateData, GateType, Op, PGPass, PauliGraph};
4
5fn add_rebased_gate(
6    output: &mut PauliGraph,
7    source: &GateData,
8    gate_type: GateType,
9    argument_order: &[usize],
10) {
11    output.add_op(Op::Gate {
12        data: GateData::new(
13            gate_type,
14            argument_order
15                .iter()
16                .map(|&index| source.get_args()[index])
17                .collect(),
18        )
19        .with_conditional(
20            source.get_conditional_bits().clone(),
21            source.get_conditional_values().clone(),
22        ),
23    });
24}
25
26fn rebase_tqe_to_zx(pg: &PauliGraph, allowed_tqes: &HashSet<GateType>) -> PauliGraph {
27    let mut output = PauliGraph::new(pg.get_n_qubits());
28    for op in pg.get_ops() {
29        if let Op::Gate { data } = op {
30            if allowed_tqes.contains(data.get_gate_type()) {
31                output.add_op(op.clone());
32                continue;
33            }
34            match data.get_gate_type() {
35                GateType::XX => {
36                    add_rebased_gate(&mut output, data, GateType::H, &[0]);
37                    add_rebased_gate(&mut output, data, GateType::ZX, &[0, 1]);
38                    add_rebased_gate(&mut output, data, GateType::H, &[0]);
39                }
40                GateType::XY => {
41                    if allowed_tqes.contains(&GateType::YX) {
42                        add_rebased_gate(&mut output, data, GateType::YX, &[1, 0]);
43                    } else {
44                        add_rebased_gate(&mut output, data, GateType::V, &[1]);
45                        add_rebased_gate(&mut output, data, GateType::ZX, &[1, 0]);
46                        add_rebased_gate(&mut output, data, GateType::Vdg, &[1]);
47                    }
48                }
49                GateType::XZ => {
50                    add_rebased_gate(&mut output, data, GateType::ZX, &[1, 0]);
51                }
52                GateType::YX => {
53                    if allowed_tqes.contains(&GateType::XY) {
54                        add_rebased_gate(&mut output, data, GateType::XY, &[1, 0]);
55                    } else {
56                        add_rebased_gate(&mut output, data, GateType::V, &[0]);
57                        add_rebased_gate(&mut output, data, GateType::ZX, &[0, 1]);
58                        add_rebased_gate(&mut output, data, GateType::Vdg, &[0]);
59                    }
60                }
61                GateType::YY => {
62                    add_rebased_gate(&mut output, data, GateType::V, &[0]);
63                    add_rebased_gate(&mut output, data, GateType::Sdg, &[1]);
64                    add_rebased_gate(&mut output, data, GateType::ZX, &[0, 1]);
65                    add_rebased_gate(&mut output, data, GateType::Vdg, &[0]);
66                    add_rebased_gate(&mut output, data, GateType::S, &[1]);
67                }
68                GateType::YZ => {
69                    if allowed_tqes.contains(&GateType::ZY) {
70                        add_rebased_gate(&mut output, data, GateType::ZY, &[1, 0]);
71                    } else {
72                        add_rebased_gate(&mut output, data, GateType::Sdg, &[0]);
73                        add_rebased_gate(&mut output, data, GateType::ZX, &[1, 0]);
74                        add_rebased_gate(&mut output, data, GateType::S, &[0]);
75                    }
76                }
77                GateType::ZY => {
78                    if allowed_tqes.contains(&GateType::YZ) {
79                        add_rebased_gate(&mut output, data, GateType::YZ, &[1, 0]);
80                    } else {
81                        add_rebased_gate(&mut output, data, GateType::Sdg, &[1]);
82                        add_rebased_gate(&mut output, data, GateType::ZX, &[0, 1]);
83                        add_rebased_gate(&mut output, data, GateType::S, &[1]);
84                    }
85                }
86                GateType::ZZ => {
87                    add_rebased_gate(&mut output, data, GateType::H, &[1]);
88                    add_rebased_gate(&mut output, data, GateType::ZX, &[0, 1]);
89                    add_rebased_gate(&mut output, data, GateType::H, &[1]);
90                }
91                _ => output.add_op(op.clone()),
92            }
93        } else {
94            output.add_op(op.clone());
95        }
96    }
97    output
98}
99
100/// Rebases two-qubit entangling gates to `ZX` and single-qubit Cliffords.
101///
102/// By default, `ZX` is the only retained TQE gate. Reversed `XY`/`YX` and
103/// `YZ`/`ZY` orientations are used directly when their counterpart is allowed.
104pub struct RebaseTQEToZXPass {
105    allowed_tqes: HashSet<GateType>,
106}
107
108impl Default for RebaseTQEToZXPass {
109    fn default() -> Self {
110        Self::new()
111    }
112}
113
114impl RebaseTQEToZXPass {
115    /// Creates a pass that rebases every TQE gate except `ZX`.
116    pub fn new() -> Self {
117        Self {
118            allowed_tqes: [GateType::ZX].into_iter().collect(),
119        }
120    }
121
122    /// Sets TQE gate types that should remain unchanged during rebasing.
123    ///
124    /// `ZX` is always retained because it is the target gate of the rebase.
125    pub fn with_allowed_tqes(mut self, allowed_tqes: Vec<GateType>) -> Self {
126        self.allowed_tqes = allowed_tqes.into_iter().collect();
127        self.allowed_tqes.insert(GateType::ZX);
128        self
129    }
130}
131
132impl PGPass for RebaseTQEToZXPass {
133    /// Rebases every disallowed TQE gate and leaves all other operations intact.
134    fn transform(&self, pg: &PauliGraph) -> PauliGraph {
135        rebase_tqe_to_zx(pg, &self.allowed_tqes)
136    }
137}
138#[cfg(test)]
139mod tests {
140    use super::*;
141    use rstest::rstest;
142    use tk_pg_converter::compare_unitaries_via_tk;
143    use tk_pg_core::{
144        BlackBoxData, GateData, GateType, Op, PGPass, Pauli, PauliGraph, RotationData,
145    };
146
147    fn graph(ops: Vec<Op>) -> PauliGraph {
148        PauliGraph::new(2).with_ops(ops)
149    }
150
151    fn gate(gate_type: GateType, args: Vec<usize>) -> Op {
152        Op::Gate {
153            data: GateData::new(gate_type, args),
154        }
155    }
156
157    fn is_tqe(gate_type: &GateType) -> bool {
158        matches!(
159            gate_type,
160            GateType::XX
161                | GateType::XY
162                | GateType::XZ
163                | GateType::YX
164                | GateType::YY
165                | GateType::YZ
166                | GateType::ZX
167                | GateType::ZY
168                | GateType::ZZ
169        )
170    }
171
172    #[rstest]
173    #[case::xx(GateType::XX)]
174    #[case::xy(GateType::XY)]
175    #[case::xz(GateType::XZ)]
176    #[case::yx(GateType::YX)]
177    #[case::yy(GateType::YY)]
178    #[case::yz(GateType::YZ)]
179    #[case::zx(GateType::ZX)]
180    #[case::zy(GateType::ZY)]
181    #[case::zz(GateType::ZZ)]
182    fn rebase_preserves_unitary(#[case] gate_type: GateType) {
183        let input = graph(vec![gate(gate_type, vec![0, 1])]);
184        let output = RebaseTQEToZXPass::new().transform(&input);
185        assert!(compare_unitaries_via_tk(&input, &output));
186        // Check that only ZX gates remain
187        assert!(output.get_ops().iter().all(|op| {
188            let Op::Gate { data } = op else {
189                return false;
190            };
191            !is_tqe(data.get_gate_type()) || data.get_gate_type() == &GateType::ZX
192        }));
193    }
194
195    #[test]
196    fn explicitly_allowed_tqe_is_unchanged() {
197        let input = graph(vec![gate(GateType::YY, vec![0, 1])]);
198        let output = RebaseTQEToZXPass::new()
199            .with_allowed_tqes(vec![GateType::YY])
200            .transform(&input);
201        assert_eq!(output, input);
202    }
203
204    #[rstest]
205    #[case::xy_to_yx(GateType::XY, GateType::YX)]
206    #[case::yx_to_xy(GateType::YX, GateType::XY)]
207    #[case::yz_to_zy(GateType::YZ, GateType::ZY)]
208    #[case::zy_to_yz(GateType::ZY, GateType::YZ)]
209    fn reversed_allowed_orientation_is_used(#[case] source: GateType, #[case] allowed: GateType) {
210        let input = graph(vec![gate(source, vec![0, 1])]);
211        let output = RebaseTQEToZXPass::new()
212            .with_allowed_tqes(vec![allowed.clone()])
213            .transform(&input);
214
215        assert_eq!(output, graph(vec![gate(allowed, vec![1, 0])]),);
216        assert!(compare_unitaries_via_tk(&input, &output));
217    }
218
219    #[test]
220    fn zx_remains_allowed_when_the_caller_omits_it() {
221        let input = graph(vec![gate(GateType::ZX, vec![0, 1])]);
222        let output = RebaseTQEToZXPass::new()
223            .with_allowed_tqes(vec![GateType::YY])
224            .transform(&input);
225
226        assert_eq!(output, input);
227    }
228
229    #[test]
230    fn rebase_preserves_conditions() {
231        let conditional = Op::Gate {
232            data: GateData::new(GateType::XX, vec![0, 1])
233                .with_conditional(vec![1, 3], vec![true, false]),
234        };
235        let input = graph(vec![conditional]);
236        let output = RebaseTQEToZXPass::new().transform(&input);
237
238        assert!(output.get_ops().len() > 1);
239        assert!(output.get_ops().iter().all(|op| {
240            matches!(
241                op,
242                Op::Gate { data }
243                    if data.get_conditional_bits() == &[1, 3]
244                        && data.get_conditional_values() == &[true, false]
245            )
246        }));
247
248        // Check equivalence after removing the conditions
249        let input_no_condition = graph(vec![gate(GateType::XX, vec![0, 1])]);
250        let output_no_condition = graph(
251            output
252                .get_ops()
253                .iter()
254                .map(|op| {
255                    let Op::Gate { data } = op else {
256                        unreachable!()
257                    };
258                    Op::Gate {
259                        data: data.clone().with_conditional(Vec::new(), Vec::new()),
260                    }
261                })
262                .collect(),
263        );
264        assert!(compare_unitaries_via_tk(
265            &input_no_condition,
266            &output_no_condition
267        ));
268    }
269
270    #[test]
271    fn rebase_preserves_non_tqe_ops() {
272        let op1 = Op::SetBoundary;
273        let op2 = Op::Rotation {
274            data: RotationData::new(vec![Pauli::X, Pauli::I], 0.37),
275        };
276        let op3 = Op::SetBoundary;
277        let op4 = gate(GateType::XX, vec![0, 1]);
278        let op5 = Op::BlackBox {
279            data: BlackBoxData::new(vec![0], "bb".into()),
280        };
281        let input = graph(vec![
282            op1.clone(),
283            op2.clone(),
284            op3.clone(),
285            op4,
286            op5.clone(),
287        ]);
288        let output = RebaseTQEToZXPass::new().transform(&input);
289        let expected = graph(vec![
290            op1,
291            op2,
292            op3,
293            gate(GateType::H, vec![0]),
294            gate(GateType::ZX, vec![0, 1]),
295            gate(GateType::H, vec![0]),
296            op5,
297        ]);
298        assert_eq!(output, expected);
299    }
300}