tk-pg-optimize 0.1.0

Optimization passes 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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
use crate::packed_op::{PackedOp, PendingPackedOp};
use tk_pg_core::{Op, PGPass, PauliGraph};

fn group_ops(pg: &PauliGraph, max_set_size: usize) -> PauliGraph {
    let mut output_pg = PauliGraph::new(pg.get_n_qubits());
    let mut commuting_set: Vec<PackedOp> = Vec::new();
    if pg.get_ops().is_empty() {
        return output_pg;
    }
    output_pg.add_op(Op::SetBoundary);
    for op in pg.get_ops() {
        if matches!(op, Op::SetBoundary) {
            continue;
        }
        let pending_op = PendingPackedOp::new(op.clone());
        if commuting_set.iter().all(|s| s.commute_with(&pending_op))
            && commuting_set.len() < max_set_size
        {
            commuting_set.push(pending_op.into());
        } else if !commuting_set.is_empty() {
            commuting_set
                .drain(..)
                .for_each(|set_op| output_pg.add_op(set_op.into()));
            output_pg.add_op(Op::SetBoundary);
            commuting_set.push(pending_op.into());
        }
    }
    if !commuting_set.is_empty() {
        commuting_set
            .drain(..)
            .for_each(|set_op| output_pg.add_op(set_op.into()));
        output_pg.add_op(Op::SetBoundary);
    }
    if output_pg.get_ops().len() == 1 {
        output_pg.remove_op(0);
    }
    output_pg
}

/// Groups commuting [`PauliGraph`] operations by inserting [`Op::SetBoundary`]
/// operations.
///
/// This pass checks only the commutation of [`Op::Rotation`], [`Op::Measure`],
/// [`Op::Reset`], and [`Op::ConditionalBox`]. All other operations are treated
/// as non-commuting.
///
/// Consider running the `CanonicalFormPass` first.
///
/// # Warning
///
/// This pass does not insert group boundaries inside an [`Op::ConditionalBox`].
///
/// # Fields
///
/// - `max_set_size` (`usize`) - Maximum size of a commuting set. The default is
///   50.
///
/// # Examples
///
/// ```
/// use tk_pg_optimize::GroupCommutingOpsPass;
///
/// let s = GroupCommutingOpsPass::new().with_max_set_size(100);
/// ```
pub struct GroupCommutingOpsPass {
    max_set_size: usize,
}

impl Default for GroupCommutingOpsPass {
    fn default() -> Self {
        Self::new()
    }
}

impl GroupCommutingOpsPass {
    /// Create a new instance of `GroupCommutingOpsPass` with default parameters.
    pub fn new() -> Self {
        Self { max_set_size: 50 }
    }

    /// Set the maximum size of a commuting set.
    ///
    /// # Arguments
    ///
    /// - `mut self` (`GroupCommutingOpsPass`) - The current instance of the pass.
    /// - `max_set_size` (`usize`) - Maximum size of a commuting set.
    ///
    /// # Returns
    ///
    /// - `Self` - The updated instance of the pass.
    ///
    /// # Panics
    ///
    /// Panics if `max_set_size` is zero.
    ///
    pub fn with_max_set_size(mut self, max_set_size: usize) -> Self {
        if max_set_size == 0 {
            panic!("max_set_size must be greater than 0");
        }
        self.max_set_size = max_set_size;
        self
    }
}

impl PGPass for GroupCommutingOpsPass {
    fn transform(&self, pg: &PauliGraph) -> PauliGraph {
        group_ops(pg, self.max_set_size)
    }
}

#[cfg(test)]
mod tests {
    use tk_pg_core::{
        BlackBoxData, ConditionalBoxData, GateData, GateType, MeasureData, Pauli, ResetData,
        RotationData,
    };

    use super::*;

    #[test]
    fn test_empty_graph() {
        let pg = PauliGraph::new(2);
        let grouped_pg = GroupCommutingOpsPass::new().transform(&pg);
        assert_eq!(grouped_pg, pg);
    }

    #[test]
    fn test_group_ops() {
        let mut pg = PauliGraph::new(2);
        // boundary
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::I], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::X], 0.1),
        });
        // boundary
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::Z, Pauli::I], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::Z, Pauli::X], 0.2),
        });
        pg.add_op(Op::Measure {
            data: MeasureData::new(vec![Pauli::Z, Pauli::X], true, 0),
        });
        // boundary
        pg.add_op(Op::Reset {
            data: ResetData::new(
                vec![Pauli::Z, Pauli::I],
                vec![Pauli::X, Pauli::I],
                true,
                true,
            ),
        });
        // boundary
        let group_pass = GroupCommutingOpsPass::new();
        let grouped_pg = group_pass.transform(&pg);
        // 3 groups
        assert_eq!(grouped_pg.get_ops().len(), 10);
    }

    #[test]
    fn test_measurements_writing_same_cbit_are_in_separate_sets() {
        let first_measurement = Op::Measure {
            data: MeasureData::new(vec![Pauli::X, Pauli::I], false, 0),
        };
        let second_measurement = Op::Measure {
            data: MeasureData::new(vec![Pauli::I, Pauli::Z], false, 0),
        };
        let pg = PauliGraph::new(2)
            .with_ops(vec![first_measurement.clone(), second_measurement.clone()]);

        let grouped_pg = GroupCommutingOpsPass::new().transform(&pg);

        assert_eq!(
            grouped_pg,
            PauliGraph::new(2).with_ops(vec![
                Op::SetBoundary,
                first_measurement,
                Op::SetBoundary,
                second_measurement,
                Op::SetBoundary,
            ])
        );
    }

    #[test]
    fn test_black_boxes() {
        let mut pg = PauliGraph::new(2);
        // boundary
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::I], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::X], 0.5),
        });
        // boundary
        pg.add_op(Op::BlackBox {
            data: BlackBoxData::new(vec![0], "bb".into()),
        });
        // boundary
        pg.add_op(Op::BlackBox {
            data: BlackBoxData::new(vec![1], "bb2".into()),
        });
        // boundary
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::Z, Pauli::Z], 0.5),
        });
        // boundary
        let group_pass = GroupCommutingOpsPass::new();
        let grouped_pg = group_pass.transform(&pg);
        // Each black box should occupy its own group.
        assert_eq!(grouped_pg.get_ops().len(), 10);
    }

    #[test]
    fn test_non_pauli_ops() {
        let mut pg = PauliGraph::new(2);
        // boundary
        pg.add_op(Op::Gate {
            data: GateData::new(GateType::RX, vec![0]).with_params(vec![1.5]),
        });
        // boundary
        pg.add_op(Op::Gate {
            data: GateData::new(GateType::RX, vec![0]).with_params(vec![1.2]),
        });
        // boundary
        let group_pass = GroupCommutingOpsPass::new();
        let grouped_pg = group_pass.transform(&pg);
        assert_eq!(grouped_pg.get_ops().len(), 5);
    }

    #[test]
    fn test_conditional_boxes() {
        let mut pg = PauliGraph::new(2);
        // boundary
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::I], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::X], 0.5),
        });
        pg.add_op(Op::ConditionalBox {
            data: ConditionalBoxData::new(
                vec![
                    Op::Rotation {
                        data: RotationData::new(vec![Pauli::X, Pauli::I], 0.1),
                    },
                    Op::Rotation {
                        data: RotationData::new(vec![Pauli::X, Pauli::X], 0.1),
                    },
                ],
                vec![0],
                vec![true],
            ),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::I, Pauli::X], 0.5),
        });
        // boundary
        let group_pass = GroupCommutingOpsPass::new();
        let grouped_pg = group_pass.transform(&pg);
        // One set
        assert_eq!(grouped_pg.get_ops().len(), 6);
    }

    #[test]
    fn test_measurement_writing_condition_bit_is_separate_from_conditional_box() {
        let mut pg = PauliGraph::new(2);
        pg.add_op(Op::Measure {
            data: MeasureData::new(vec![Pauli::X, Pauli::I], false, 0),
        });
        pg.add_op(Op::ConditionalBox {
            data: ConditionalBoxData::new(
                vec![Op::Rotation {
                    data: RotationData::new(vec![Pauli::X, Pauli::I], 0.1),
                }],
                vec![0],
                vec![true],
            ),
        });

        let grouped_pg = GroupCommutingOpsPass::new().transform(&pg);

        assert_eq!(grouped_pg.get_ops().len(), 5);
        assert!(matches!(grouped_pg.get_ops()[2], Op::SetBoundary));
    }

    #[test]
    fn test_measurement_and_conditional_measurement_writing_same_cbit_are_separate() {
        let mut pg = PauliGraph::new(2);
        pg.add_op(Op::Measure {
            data: MeasureData::new(vec![Pauli::X, Pauli::I], false, 0),
        });
        pg.add_op(Op::ConditionalBox {
            data: ConditionalBoxData::new(
                vec![Op::Measure {
                    data: MeasureData::new(vec![Pauli::I, Pauli::Z], false, 0),
                }],
                vec![1],
                vec![true],
            ),
        });

        let grouped_pg = GroupCommutingOpsPass::new().transform(&pg);

        assert_eq!(grouped_pg.get_ops().len(), 5);
        assert!(matches!(grouped_pg.get_ops()[2], Op::SetBoundary));
    }

    #[test]
    fn test_conditional_boxes_with_classical_dependencies_are_separate() {
        let writer = Op::ConditionalBox {
            data: ConditionalBoxData::new(
                vec![Op::Measure {
                    data: MeasureData::new(vec![Pauli::X, Pauli::I], false, 0),
                }],
                vec![1],
                vec![true],
            ),
        };
        let reader = Op::ConditionalBox {
            data: ConditionalBoxData::new(
                vec![Op::Rotation {
                    data: RotationData::new(vec![Pauli::I, Pauli::Z], 0.1),
                }],
                vec![0],
                vec![true],
            ),
        };
        let second_writer = Op::ConditionalBox {
            data: ConditionalBoxData::new(
                vec![Op::Measure {
                    data: MeasureData::new(vec![Pauli::I, Pauli::Z], false, 0),
                }],
                vec![2],
                vec![true],
            ),
        };
        let dependent_pairs = [
            ("write followed by read", writer.clone(), reader.clone()),
            ("read followed by write", reader, writer.clone()),
            ("write followed by write", writer, second_writer),
        ];

        for (case, first_box, second_box) in dependent_pairs {
            let grouped_pg = GroupCommutingOpsPass::new().transform(
                &PauliGraph::new(2).with_ops(vec![first_box.clone(), second_box.clone()]),
            );

            assert_eq!(
                grouped_pg,
                PauliGraph::new(2).with_ops(vec![
                    Op::SetBoundary,
                    first_box,
                    Op::SetBoundary,
                    second_box,
                    Op::SetBoundary,
                ]),
                "failed case: {case}"
            );
        }
    }

    #[test]
    fn test_conditional_boxes_reading_same_cbit_commute() {
        let first_box = Op::ConditionalBox {
            data: ConditionalBoxData::new(
                vec![Op::Rotation {
                    data: RotationData::new(vec![Pauli::X, Pauli::I], 0.1),
                }],
                vec![0],
                vec![true],
            ),
        };
        let second_box = Op::ConditionalBox {
            data: ConditionalBoxData::new(
                vec![Op::Rotation {
                    data: RotationData::new(vec![Pauli::I, Pauli::Z], 0.1),
                }],
                vec![0],
                vec![true],
            ),
        };

        let grouped_pg = GroupCommutingOpsPass::new()
            .transform(&PauliGraph::new(2).with_ops(vec![first_box.clone(), second_box.clone()]));

        assert_eq!(
            grouped_pg,
            PauliGraph::new(2).with_ops(vec![
                Op::SetBoundary,
                first_box,
                second_box,
                Op::SetBoundary,
            ])
        );
    }

    #[test]
    fn test_measurement_commutes_with_classically_independent_conditional_box() {
        let mut pg = PauliGraph::new(2);
        pg.add_op(Op::Measure {
            data: MeasureData::new(vec![Pauli::X, Pauli::I], false, 0),
        });
        pg.add_op(Op::ConditionalBox {
            data: ConditionalBoxData::new(
                vec![Op::Rotation {
                    data: RotationData::new(vec![Pauli::I, Pauli::Z], 0.1),
                }],
                vec![1],
                vec![true],
            ),
        });

        let grouped_pg = GroupCommutingOpsPass::new().transform(&pg);

        assert_eq!(grouped_pg.get_ops().len(), 4);
    }

    #[test]
    fn test_max_set_size() {
        let mut pg = PauliGraph::new(2);
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::I], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::X], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::Z, Pauli::I], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::Z, Pauli::X], 0.2),
        });
        let group_pass = GroupCommutingOpsPass::new().with_max_set_size(1);
        let grouped_pg = group_pass.transform(&pg);
        assert_eq!(grouped_pg.get_ops().len(), 9);
    }

    #[test]
    fn test_pg_contains_set_boundary() {
        let mut pg = PauliGraph::new(2);
        pg.add_op(Op::SetBoundary);
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::I], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::X], 0.1),
        });
        let group_pass = GroupCommutingOpsPass::new();
        let grouped_pg = group_pass.transform(&pg);
        assert_eq!(grouped_pg.get_ops().len(), 4);
    }

    #[test]
    fn test_pg_contains_only_set_boundaries() {
        let pg = PauliGraph::new(2).with_ops(vec![Op::SetBoundary, Op::SetBoundary]);
        let grouped_pg = GroupCommutingOpsPass::new().transform(&pg);
        assert_eq!(grouped_pg, PauliGraph::new(2));
    }

    #[test]
    fn test_idempotent() {
        let mut pg = PauliGraph::new(2);
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::I], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::X, Pauli::X], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::Z, Pauli::I], 0.1),
        });
        pg.add_op(Op::Rotation {
            data: RotationData::new(vec![Pauli::Z, Pauli::X], 0.2),
        });
        let group_pass = GroupCommutingOpsPass::new();
        let grouped_pg = group_pass.transform(&pg);
        let regrouped_pg = group_pass.transform(&grouped_pg);
        assert_eq!(grouped_pg, regrouped_pg);
    }
}