stabilizer_qec 2.1.0

Quantum error-correction simulation and decoding: Stim-format circuits and error models, a bit-parallel sampler, sparse-blossom, correlated and belief matching, BP+OSD, window decoders, bivariate bicycle codes, lattice surgery, Clifford+T circuits with coherent noise, and sampling and BP on the GPU.
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
// Ported from Fusion Blossom 0.2.13 (Yue Wu; MIT; see src/fusion/LICENSE and
// THIRD_PARTY_NOTICES.md): its default features, its dependencies replaced by src/fusion/shim.rs.

//! Example Partition
//!
//! This module contains example partition for some of the example codes
//!

use super::example_codes::*;
use super::util::*;
use std::collections::VecDeque;

pub trait ExamplePartition {
    /// customize partition, note that this process may re-order the vertices in `code`
    fn build_apply(&mut self, code: &mut dyn ExampleCode) -> PartitionConfig {
        // first apply reorder
        if let Some(reordered_vertices) = self.build_reordered_vertices(code) {
            code.reorder_vertices(&reordered_vertices);
        }
        self.build_partition(code)
    }

    fn re_index_defect_vertices(&mut self, code: &dyn ExampleCode, defect_vertices: &[VertexIndex]) -> Vec<VertexIndex> {
        if let Some(reordered_vertices) = self.build_reordered_vertices(code) {
            translated_defect_to_reordered(&reordered_vertices, defect_vertices)
        } else {
            defect_vertices.into()
        }
    }

    /// build reorder vertices
    fn build_reordered_vertices(&mut self, _code: &dyn ExampleCode) -> Option<Vec<VertexIndex>> {
        None
    }

    /// build the partition, using the indices after reordered vertices
    fn build_partition(&mut self, code: &dyn ExampleCode) -> PartitionConfig;
}

/// no partition
pub struct NoPartition {}

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

impl NoPartition {
    pub fn new() -> Self {
        Self {}
    }
}

impl ExamplePartition for NoPartition {
    fn build_partition(&mut self, code: &dyn ExampleCode) -> PartitionConfig {
        PartitionConfig::new(code.vertex_num())
    }
}

/// partition into top half and bottom half
#[derive(Default)]
pub struct CodeCapacityPlanarCodeVerticalPartitionHalf {
    d: VertexNum,
    /// the row of splitting: in the visualization tool, the top row is the 1st row, the bottom row is the d-th row
    partition_row: VertexNum,
}

impl CodeCapacityPlanarCodeVerticalPartitionHalf {
    pub fn new(d: VertexNum, partition_row: VertexNum) -> Self {
        Self { d, partition_row }
    }
}

impl ExamplePartition for CodeCapacityPlanarCodeVerticalPartitionHalf {
    fn build_partition(&mut self, code: &dyn ExampleCode) -> PartitionConfig {
        let (d, partition_row) = (self.d, self.partition_row);
        assert_eq!(code.vertex_num(), d * (d + 1), "code size incompatible");
        let mut config = PartitionConfig::new(code.vertex_num());
        assert!(partition_row > 1 && partition_row < d);
        config.partitions = vec![
            VertexRange::new(0, (partition_row - 1) * (d + 1)),
            VertexRange::new(partition_row * (d + 1), d * (d + 1)),
        ];
        config.fusions = vec![(0, 1)];
        config
    }
}

/// partition into top half and bottom half
#[derive(Default)]
pub struct CodeCapacityRotatedCodeVerticalPartitionHalf {
    d: VertexNum,
    /// the row of splitting: in the visualization tool, the top row is the 1st row, the bottom row is the d-th row
    partition_row: VertexNum,
}

impl CodeCapacityRotatedCodeVerticalPartitionHalf {
    pub fn new(d: VertexNum, partition_row: VertexNum) -> Self {
        Self { d, partition_row }
    }
}

impl ExamplePartition for CodeCapacityRotatedCodeVerticalPartitionHalf {
    fn build_partition(&mut self, code: &dyn ExampleCode) -> PartitionConfig {
        let (d, partition_row) = (self.d, self.partition_row);
        let row_vertex_num = (d - 1) / 2 + 1;
        assert_eq!(code.vertex_num(), row_vertex_num * (d + 1), "code size incompatible");
        let mut config = PartitionConfig::new(code.vertex_num());
        assert!(partition_row >= 1 && partition_row < d);
        config.partitions = vec![
            VertexRange::new(0, partition_row * row_vertex_num),
            VertexRange::new((partition_row + 1) * row_vertex_num, row_vertex_num * (d + 1)),
        ];
        config.fusions = vec![(0, 1)];
        config
    }
}

/// partition into 4 pieces: top left and right, bottom left and right
#[derive(Default)]
pub struct CodeCapacityPlanarCodeVerticalPartitionFour {
    d: VertexNum,
    /// the row of splitting: in the visualization tool, the top row is the 1st row, the bottom row is the d-th row
    partition_row: VertexNum,
    /// the row of splitting: in the visualization tool, the left (non-virtual) column is the 1st column, the right (non-virtual) column is the (d-1)-th column
    partition_column: VertexNum,
}

impl CodeCapacityPlanarCodeVerticalPartitionFour {
    pub fn new(d: VertexNum, partition_row: VertexNum, partition_column: VertexNum) -> Self {
        Self {
            d,
            partition_row,
            partition_column,
        }
    }
}

impl ExamplePartition for CodeCapacityPlanarCodeVerticalPartitionFour {
    fn build_reordered_vertices(&mut self, code: &dyn ExampleCode) -> Option<Vec<VertexIndex>> {
        let (d, partition_row, partition_column) = (self.d, self.partition_row, self.partition_column);
        assert_eq!(code.vertex_num(), d * (d + 1), "code size incompatible");
        assert!(partition_row > 1 && partition_row < d);
        let mut reordered_vertices = vec![];
        let split_horizontal = partition_row - 1;
        let split_vertical = partition_column - 1;
        for i in 0..split_horizontal {
            // left-top block
            for j in 0..split_vertical {
                reordered_vertices.push(i * (d + 1) + j);
            }
            reordered_vertices.push(i * (d + 1) + d);
        }
        for i in 0..split_horizontal {
            // interface between the left-top block and the right-top block
            reordered_vertices.push(i * (d + 1) + split_vertical);
        }
        for i in 0..split_horizontal {
            // right-top block
            for j in (split_vertical + 1)..d {
                reordered_vertices.push(i * (d + 1) + j);
            }
        }
        {
            // the big interface between top and bottom
            for j in 0..(d + 1) {
                reordered_vertices.push(split_horizontal * (d + 1) + j);
            }
        }
        for i in (split_horizontal + 1)..d {
            // left-bottom block
            for j in 0..split_vertical {
                reordered_vertices.push(i * (d + 1) + j);
            }
            reordered_vertices.push(i * (d + 1) + d);
        }
        for i in (split_horizontal + 1)..d {
            // interface between the left-bottom block and the right-bottom block
            reordered_vertices.push(i * (d + 1) + split_vertical);
        }
        for i in (split_horizontal + 1)..d {
            // right-bottom block
            for j in (split_vertical + 1)..d {
                reordered_vertices.push(i * (d + 1) + j);
            }
        }
        Some(reordered_vertices)
    }
    fn build_partition(&mut self, _code: &dyn ExampleCode) -> PartitionConfig {
        let (d, partition_row, partition_column) = (self.d, self.partition_row, self.partition_column);
        let mut config = PartitionConfig::new(d * (d + 1));
        let b0_count = (partition_row - 1) * partition_column;
        let b1_count = (partition_row - 1) * (d - partition_column);
        let b2_count = (d - partition_row) * partition_column;
        let b3_count = (d - partition_row) * (d - partition_column);
        config.partitions = vec![
            VertexRange::new_length(0, b0_count),
            VertexRange::new_length(b0_count + (partition_row - 1), b1_count),
            VertexRange::new_length(partition_row * (d + 1), b2_count),
            VertexRange::new_length(partition_row * (d + 1) + b2_count + (d - partition_row), b3_count),
        ];
        config.fusions = vec![(0, 1), (2, 3), (4, 5)];
        config
    }
}

/// partition into top half and bottom half
#[derive(Default)]
pub struct CodeCapacityRepetitionCodePartitionHalf {
    d: VertexNum,
    /// the position of splitting: in the visualization tool, the left (non-virtual) vertex is the 1st column, the right (non-virtual) vertex is the (d-1)-th column
    partition_index: VertexIndex,
}

impl CodeCapacityRepetitionCodePartitionHalf {
    pub fn new(d: VertexNum, partition_index: VertexIndex) -> Self {
        Self { d, partition_index }
    }
}

impl ExamplePartition for CodeCapacityRepetitionCodePartitionHalf {
    fn build_reordered_vertices(&mut self, code: &dyn ExampleCode) -> Option<Vec<VertexIndex>> {
        let (d, partition_index) = (self.d, self.partition_index);
        assert_eq!(code.vertex_num(), d + 1, "code size incompatible");
        assert!(partition_index > 1 && partition_index < d);
        let mut reordered_vertices = vec![];
        let split_vertical = partition_index - 1;
        for j in 0..split_vertical {
            reordered_vertices.push(j);
        }
        reordered_vertices.push(d);
        for j in split_vertical..d {
            reordered_vertices.push(j);
        }
        Some(reordered_vertices)
    }
    fn build_partition(&mut self, _code: &dyn ExampleCode) -> PartitionConfig {
        let (d, partition_index) = (self.d, self.partition_index);
        let mut config = PartitionConfig::new(d + 1);
        config.partitions = vec![
            VertexRange::new(0, partition_index),
            VertexRange::new(partition_index + 1, d + 1),
        ];
        config.fusions = vec![(0, 1)];
        config
    }
}

/// evenly partition along the time axis
pub struct PhenomenologicalPlanarCodeTimePartition {
    d: VertexNum,
    noisy_measurements: VertexNum,
    /// the number of partition
    partition_num: usize,
    /// enable tree fusion (to minimize latency but incur log(partition_num) more memory copy)
    enable_tree_fusion: bool,
    /// maximum amount of tree leaf; if the total partition is greater than this, it will be cut into multiple regions and each region is a separate tree;
    /// those trees are then fused sequentially
    maximum_tree_leaf_size: usize,
}

impl PhenomenologicalPlanarCodeTimePartition {
    pub fn new_tree(
        d: VertexNum,
        noisy_measurements: VertexNum,
        partition_num: usize,
        enable_tree_fusion: bool,
        maximum_tree_leaf_size: usize,
    ) -> Self {
        Self {
            d,
            noisy_measurements,
            partition_num,
            enable_tree_fusion,
            maximum_tree_leaf_size,
        }
    }
    pub fn new(d: VertexNum, noisy_measurements: VertexNum, partition_num: usize) -> Self {
        Self::new_tree(d, noisy_measurements, partition_num, false, usize::MAX)
    }
}

impl ExamplePartition for PhenomenologicalPlanarCodeTimePartition {
    #[allow(clippy::unnecessary_cast)]
    fn build_partition(&mut self, code: &dyn ExampleCode) -> PartitionConfig {
        let (d, noisy_measurements, partition_num) = (self.d, self.noisy_measurements, self.partition_num);
        let round_vertex_num = d * (d + 1);
        let vertex_num = round_vertex_num * (noisy_measurements + 1);
        assert_eq!(code.vertex_num(), vertex_num, "code size incompatible");
        assert!(partition_num >= 1 && partition_num <= noisy_measurements as usize + 1);
        // do not use fixed partition_length, because it would introduce super long partition; do it on the fly
        let mut config = PartitionConfig::new(vertex_num);
        config.partitions.clear();
        for partition_index in 0..partition_num as VertexIndex {
            let start_round_index = partition_index * (noisy_measurements + 1) / partition_num as VertexNum;
            let end_round_index = (partition_index + 1) * (noisy_measurements + 1) / partition_num as VertexNum;
            assert!(end_round_index > start_round_index, "empty partition occurs");
            if partition_index == 0 {
                config.partitions.push(VertexRange::new(
                    start_round_index * round_vertex_num,
                    end_round_index * round_vertex_num,
                ));
            } else {
                config.partitions.push(VertexRange::new(
                    (start_round_index + 1) * round_vertex_num,
                    end_round_index * round_vertex_num,
                ));
            }
        }
        config.fusions.clear();
        if !self.enable_tree_fusion || self.maximum_tree_leaf_size == 1 {
            for unit_index in partition_num..(2 * partition_num - 1) {
                if unit_index == partition_num {
                    config.fusions.push((0, 1));
                } else {
                    config.fusions.push((unit_index as usize - 1, unit_index - partition_num + 1));
                }
            }
        } else {
            let mut whole_ranges = vec![];
            let mut left_right_leaf = vec![];
            for (unit_index, partition) in config.partitions.iter().enumerate() {
                assert!(
                    partition.end() <= vertex_num,
                    "invalid vertex index {} in partitions",
                    partition.end()
                );
                whole_ranges.push(*partition);
                left_right_leaf.push((unit_index, unit_index));
            }
            // first cut into multiple regions
            let region_count = if config.partitions.len() <= self.maximum_tree_leaf_size {
                1
            } else {
                (config.partitions.len() + self.maximum_tree_leaf_size - 1) / self.maximum_tree_leaf_size
            };
            let mut last_sequential_unit: Option<usize> = None;
            for region_index in 0..region_count {
                let region_start = region_index * self.maximum_tree_leaf_size;
                let region_end = std::cmp::min((region_index + 1) * self.maximum_tree_leaf_size, config.partitions.len());
                // build the local tree
                let mut pending_fusion = VecDeque::new();
                for unit_index in region_start..region_end {
                    pending_fusion.push_back(unit_index);
                }
                let local_fusion_start_index = whole_ranges.len();
                for unit_index in local_fusion_start_index..(local_fusion_start_index + region_end - region_start - 1) {
                    let mut unit_index_1 = pending_fusion.pop_front().unwrap();
                    // iterate over all pending fusions to find a neighboring one
                    for i in 0..pending_fusion.len() {
                        let mut unit_index_2 = pending_fusion[i];
                        let is_neighbor = left_right_leaf[unit_index_1].0 == left_right_leaf[unit_index_2].1 + 1
                            || left_right_leaf[unit_index_2].0 == left_right_leaf[unit_index_1].1 + 1;
                        if is_neighbor {
                            pending_fusion.remove(i);
                            if whole_ranges[unit_index_1].start() > whole_ranges[unit_index_2].start() {
                                (unit_index_1, unit_index_2) = (unit_index_2, unit_index_1);
                                // only lower range can fuse higher range
                            }
                            config.fusions.push((unit_index_1, unit_index_2));
                            pending_fusion.push_back(unit_index);
                            // println!("unit_index_1: {unit_index_1} {:?}, unit_index_2: {unit_index_2} {:?}", whole_ranges[unit_index_1], whole_ranges[unit_index_2]);
                            let (whole_range, _) = whole_ranges[unit_index_1].fuse(&whole_ranges[unit_index_2]);
                            whole_ranges.push(whole_range);
                            left_right_leaf.push((left_right_leaf[unit_index_1].0, left_right_leaf[unit_index_2].1));
                            break;
                        }
                        assert!(i != pending_fusion.len() - 1, "unreachable: cannot find a neighbor");
                    }
                }
                assert!(pending_fusion.len() == 1, "only the final unit is left");
                let tree_root_unit_index = pending_fusion.pop_front().unwrap();
                if let Some(last_sequential_unit) = last_sequential_unit.as_mut() {
                    config.fusions.push((*last_sequential_unit, tree_root_unit_index));
                    let (whole_range, _) = whole_ranges[*last_sequential_unit].fuse(&whole_ranges[tree_root_unit_index]);
                    whole_ranges.push(whole_range);
                    left_right_leaf.push((
                        left_right_leaf[*last_sequential_unit].0,
                        left_right_leaf[tree_root_unit_index].1,
                    ));
                    *last_sequential_unit = tree_root_unit_index + 1;
                } else {
                    last_sequential_unit = Some(tree_root_unit_index);
                }
            }
        }
        config
    }
}

/// evenly partition along the time axis
#[derive(Clone)]
pub struct PhenomenologicalRotatedCodeTimePartition {
    /// code distance
    pub d: VertexNum,
    /// rounds of noisy measurement, valid only when multiple rounds
    pub noisy_measurements: VertexNum,
    /// the number of partition
    pub partition_num: usize,
    /// enable tree fusion (to minimize latency but incur log(partition_num) more memory copy)
    pub enable_tree_fusion: bool,
    /// maximum amount of tree leaf; if the total partition is greater than this, it will be cut into multiple regions and each region is a separate tree;
    /// those trees are then fused sequentially
    pub maximum_tree_leaf_size: usize,
}

impl PhenomenologicalRotatedCodeTimePartition {
    pub fn new_tree(
        d: VertexNum,
        noisy_measurements: VertexNum,
        partition_num: usize,
        enable_tree_fusion: bool,
        maximum_tree_leaf_size: usize,
    ) -> Self {
        Self {
            d,
            noisy_measurements,
            partition_num,
            enable_tree_fusion,
            maximum_tree_leaf_size,
        }
    }
    pub fn new(d: VertexNum, noisy_measurements: VertexNum, partition_num: usize) -> Self {
        Self::new_tree(d, noisy_measurements, partition_num, false, usize::MAX)
    }
}

impl ExamplePartition for PhenomenologicalRotatedCodeTimePartition {
    #[allow(clippy::unnecessary_cast)]
    fn build_partition(&mut self, code: &dyn ExampleCode) -> PartitionConfig {
        let (d, noisy_measurements, partition_num) = (self.d, self.noisy_measurements, self.partition_num);
        let row_vertex_num = (d - 1) / 2 + 1;
        let round_vertex_num = row_vertex_num * (d + 1);
        let vertex_num = round_vertex_num * (noisy_measurements + 1);
        assert_eq!(code.vertex_num(), vertex_num, "code size incompatible");
        assert!(partition_num >= 1 && partition_num <= noisy_measurements as usize + 1);
        // do not use fixed partition_length, because it would introduce super long partition; do it on the fly
        let mut config = PartitionConfig::new(vertex_num);
        config.partitions.clear();
        for partition_index in 0..partition_num as VertexIndex {
            let start_round_index = partition_index * (noisy_measurements + 1) / partition_num as VertexNum;
            let end_round_index = (partition_index + 1) * (noisy_measurements + 1) / partition_num as VertexNum;
            assert!(end_round_index > start_round_index, "empty partition occurs");
            if partition_index == 0 {
                config.partitions.push(VertexRange::new(
                    start_round_index * round_vertex_num,
                    end_round_index * round_vertex_num,
                ));
            } else {
                config.partitions.push(VertexRange::new(
                    (start_round_index + 1) * round_vertex_num,
                    end_round_index * round_vertex_num,
                ));
            }
        }
        config.fusions.clear();
        if !self.enable_tree_fusion || self.maximum_tree_leaf_size == 1 {
            for unit_index in partition_num..(2 * partition_num - 1) {
                if unit_index == partition_num {
                    config.fusions.push((0, 1));
                } else {
                    config.fusions.push((unit_index as usize - 1, unit_index - partition_num + 1));
                }
            }
        } else {
            let mut whole_ranges = vec![];
            let mut left_right_leaf = vec![];
            for (unit_index, partition) in config.partitions.iter().enumerate() {
                assert!(
                    partition.end() <= vertex_num,
                    "invalid vertex index {} in partitions",
                    partition.end()
                );
                whole_ranges.push(*partition);
                left_right_leaf.push((unit_index, unit_index));
            }
            // first cut into multiple regions
            let region_count = if config.partitions.len() <= self.maximum_tree_leaf_size {
                1
            } else {
                (config.partitions.len() + self.maximum_tree_leaf_size - 1) / self.maximum_tree_leaf_size
            };
            let mut last_sequential_unit: Option<usize> = None;
            for region_index in 0..region_count {
                let region_start = region_index * self.maximum_tree_leaf_size;
                let region_end = std::cmp::min((region_index + 1) * self.maximum_tree_leaf_size, config.partitions.len());
                // build the local tree
                let mut pending_fusion = VecDeque::new();
                for unit_index in region_start..region_end {
                    pending_fusion.push_back(unit_index);
                }
                let local_fusion_start_index = whole_ranges.len();
                for unit_index in local_fusion_start_index..(local_fusion_start_index + region_end - region_start - 1) {
                    let mut unit_index_1 = pending_fusion.pop_front().unwrap();
                    // iterate over all pending fusions to find a neighboring one
                    for i in 0..pending_fusion.len() {
                        let mut unit_index_2 = pending_fusion[i];
                        let is_neighbor = left_right_leaf[unit_index_1].0 == left_right_leaf[unit_index_2].1 + 1
                            || left_right_leaf[unit_index_2].0 == left_right_leaf[unit_index_1].1 + 1;
                        if is_neighbor {
                            pending_fusion.remove(i);
                            if whole_ranges[unit_index_1].start() > whole_ranges[unit_index_2].start() {
                                (unit_index_1, unit_index_2) = (unit_index_2, unit_index_1);
                                // only lower range can fuse higher range
                            }
                            config.fusions.push((unit_index_1, unit_index_2));
                            pending_fusion.push_back(unit_index);
                            // println!("unit_index_1: {unit_index_1} {:?}, unit_index_2: {unit_index_2} {:?}", whole_ranges[unit_index_1], whole_ranges[unit_index_2]);
                            let (whole_range, _) = whole_ranges[unit_index_1].fuse(&whole_ranges[unit_index_2]);
                            whole_ranges.push(whole_range);
                            left_right_leaf.push((left_right_leaf[unit_index_1].0, left_right_leaf[unit_index_2].1));
                            break;
                        }
                        assert!(i != pending_fusion.len() - 1, "unreachable: cannot find a neighbor");
                    }
                }
                assert!(pending_fusion.len() == 1, "only the final unit is left");
                let tree_root_unit_index = pending_fusion.pop_front().unwrap();
                if let Some(last_sequential_unit) = last_sequential_unit.as_mut() {
                    config.fusions.push((*last_sequential_unit, tree_root_unit_index));
                    let (whole_range, _) = whole_ranges[*last_sequential_unit].fuse(&whole_ranges[tree_root_unit_index]);
                    whole_ranges.push(whole_range);
                    left_right_leaf.push((
                        left_right_leaf[*last_sequential_unit].0,
                        left_right_leaf[tree_root_unit_index].1,
                    ));
                    *last_sequential_unit = tree_root_unit_index + 1;
                } else {
                    last_sequential_unit = Some(tree_root_unit_index);
                }
            }
        }
        config
    }
}

#[cfg(test)]
pub mod tests {
    use super::super::dual_module::*;
    use super::super::dual_module_parallel::*;
    use super::super::dual_module_serial::*;
    // (Fusion Blossom's `unsafe_pointer` feature imports UnsafePtr here; this port has no such feature)
    use super::super::primal_module::*;
    use super::super::primal_module_parallel::*;
    use super::super::visualize::*;
    use super::*;

    pub fn example_partition_basic_standard_syndrome_optional_viz(
        code: &mut dyn ExampleCode,
        visualize_filename: Option<String>,
        mut defect_vertices: Vec<VertexIndex>,
        re_index_syndrome: bool,
        final_dual: Weight,
        mut partition: impl ExamplePartition,
    ) -> (PrimalModuleParallel, DualModuleParallel<DualModuleSerial>) {
        println!("{defect_vertices:?}");
        if re_index_syndrome {
            defect_vertices = partition.re_index_defect_vertices(code, &defect_vertices);
        }
        let partition_config = partition.build_apply(code);
        let mut visualizer = match visualize_filename.as_ref() {
            Some(visualize_filename) => {
                let visualizer = Visualizer::new(
                    Some(visualize_data_folder() + visualize_filename.as_str()),
                    code.get_positions(),
                    true,
                )
                .unwrap();
                print_visualize_link(visualize_filename.clone());
                Some(visualizer)
            }
            None => None,
        };
        let initializer = code.get_initializer();
        let partition_info = partition_config.info();
        let mut dual_module =
            DualModuleParallel::new_config(&initializer, &partition_info, DualModuleParallelConfig::default());
        let primal_config = PrimalModuleParallelConfig {
            debug_sequential: true,
            ..Default::default()
        };
        let mut primal_module = PrimalModuleParallel::new_config(&initializer, &partition_info, primal_config);
        code.set_defect_vertices(&defect_vertices);
        primal_module.parallel_solve_visualizer(&code.get_syndrome(), &dual_module, visualizer.as_mut());
        let useless_interface_ptr = DualModuleInterfacePtr::new_empty(); // don't actually use it
        let perfect_matching = primal_module.perfect_matching(&useless_interface_ptr, &mut dual_module);
        let mut subgraph_builder = SubGraphBuilder::new(&initializer);
        subgraph_builder.load_perfect_matching(&perfect_matching);
        let subgraph = subgraph_builder.get_subgraph();
        if let Some(visualizer) = visualizer.as_mut() {
            let last_interface_ptr = &primal_module.units.last().unwrap().read_recursive().interface_ptr;
            visualizer
                .snapshot_combined(
                    "perfect matching and subgraph".to_string(),
                    vec![
                        last_interface_ptr,
                        &dual_module,
                        &perfect_matching,
                        &VisualizeSubgraph::new(&subgraph),
                    ],
                )
                .unwrap();
        }
        let sum_dual_variables = primal_module
            .units
            .last()
            .unwrap()
            .read_recursive()
            .interface_ptr
            .sum_dual_variables();
        assert_eq!(
            sum_dual_variables,
            subgraph_builder.total_weight(),
            "unmatched sum dual variables"
        );
        assert_eq!(sum_dual_variables, final_dual * 2, "unexpected final dual variable sum");
        (primal_module, dual_module)
    }

    pub fn example_partition_standard_syndrome(
        code: &mut dyn ExampleCode,
        visualize_filename: String,
        defect_vertices: Vec<VertexIndex>,
        re_index_syndrome: bool,
        final_dual: Weight,
        partition: impl ExamplePartition,
    ) -> (PrimalModuleParallel, DualModuleParallel<DualModuleSerial>) {
        example_partition_basic_standard_syndrome_optional_viz(
            code,
            Some(visualize_filename),
            defect_vertices,
            re_index_syndrome,
            final_dual,
            partition,
        )
    }

    /// test a simple case
    #[test]
    fn example_partition_basic_1() {
        // cargo test example_partition_basic_1 -- --nocapture
        let visualize_filename = "example_partition_basic_1.json".to_string();
        let defect_vertices = vec![39, 52, 63, 90, 100];
        let half_weight = 500;
        example_partition_standard_syndrome(
            &mut CodeCapacityPlanarCode::new(11, 0.1, half_weight),
            visualize_filename,
            defect_vertices,
            true,
            9 * half_weight,
            NoPartition::new(),
        );
    }

    /// split into 2
    #[test]
    fn example_partition_basic_2() {
        // cargo test example_partition_basic_2 -- --nocapture
        let visualize_filename = "example_partition_basic_2.json".to_string();
        let defect_vertices = vec![39, 52, 63, 90, 100];
        let half_weight = 500;
        example_partition_standard_syndrome(
            &mut CodeCapacityPlanarCode::new(11, 0.1, half_weight),
            visualize_filename,
            defect_vertices,
            true,
            9 * half_weight,
            CodeCapacityPlanarCodeVerticalPartitionHalf { d: 11, partition_row: 7 },
        );
    }

    /// split a repetition code into 2 parts
    #[test]
    fn example_partition_basic_3() {
        // cargo test example_partition_basic_3 -- --nocapture
        let visualize_filename = "example_partition_basic_3.json".to_string();
        // reorder vertices to enable the partition;
        let defect_vertices = vec![2, 3, 4, 5, 6, 7, 8]; // indices are before the reorder
        let half_weight = 500;
        example_partition_standard_syndrome(
            &mut CodeCapacityRepetitionCode::new(11, 0.1, half_weight),
            visualize_filename,
            defect_vertices,
            true,
            5 * half_weight,
            CodeCapacityRepetitionCodePartitionHalf {
                d: 11,
                partition_index: 6,
            },
        );
    }

    /// split into 4
    #[test]
    fn example_partition_basic_4() {
        // cargo test example_partition_basic_4 -- --nocapture
        let visualize_filename = "example_partition_basic_4.json".to_string();
        // reorder vertices to enable the partition;
        let defect_vertices = vec![39, 52, 63, 90, 100]; // indices are before the reorder
        let half_weight = 500;
        example_partition_standard_syndrome(
            &mut CodeCapacityPlanarCode::new(11, 0.1, half_weight),
            visualize_filename,
            defect_vertices,
            true,
            9 * half_weight,
            CodeCapacityPlanarCodeVerticalPartitionFour {
                d: 11,
                partition_row: 7,
                partition_column: 6,
            },
        );
    }

    /// phenomenological time axis split
    #[test]
    fn example_partition_basic_5() {
        // cargo test example_partition_basic_5 -- --nocapture
        let visualize_filename = "example_partition_basic_5.json".to_string();
        // reorder vertices to enable the partition;
        let defect_vertices = vec![352, 365]; // indices are before the reorder
        let half_weight = 500;
        let noisy_measurements = 10;
        example_partition_standard_syndrome(
            &mut PhenomenologicalPlanarCode::new(11, noisy_measurements, 0.1, half_weight),
            visualize_filename,
            defect_vertices,
            true,
            2 * half_weight,
            PhenomenologicalPlanarCodeTimePartition::new(11, noisy_measurements, 2),
        );
    }

    /// a demo to show how partition works in phenomenological planar code
    #[test]
    fn example_partition_demo_1() {
        // cargo test example_partition_demo_1 -- --nocapture
        let visualize_filename = "example_partition_demo_1.json".to_string();
        // reorder vertices to enable the partition;
        let defect_vertices = vec![
            57, 113, 289, 304, 305, 331, 345, 387, 485, 493, 528, 536, 569, 570, 587, 588, 696, 745, 801, 833, 834, 884,
            904, 940, 1152, 1184, 1208, 1258, 1266, 1344, 1413, 1421, 1481, 1489, 1490, 1546, 1690, 1733, 1740, 1746, 1796,
            1825, 1826, 1856, 1857, 1996, 2004, 2020, 2028, 2140, 2196, 2306, 2307, 2394, 2395, 2413, 2417, 2425, 2496,
            2497, 2731, 2739, 2818, 2874,
        ]; // indices are before the reorder
        let half_weight = 500;
        let noisy_measurements = 51;
        example_partition_standard_syndrome(
            &mut PhenomenologicalPlanarCode::new(7, noisy_measurements, 0.005, half_weight),
            visualize_filename,
            defect_vertices,
            true,
            35 * half_weight,
            PhenomenologicalPlanarCodeTimePartition::new(7, noisy_measurements, 3),
        );
    }

    /// a demo to show how partition works in circuit-level planar code
    #[test]
    fn example_partition_demo_2() {
        // cargo test example_partition_demo_2 -- --nocapture
        let visualize_filename = "example_partition_demo_2.json".to_string();
        // reorder vertices to enable the partition;
        let defect_vertices = vec![
            57, 113, 289, 304, 305, 331, 345, 387, 485, 493, 528, 536, 569, 570, 587, 588, 696, 745, 801, 833, 834, 884,
            904, 940, 1152, 1184, 1208, 1258, 1266, 1344, 1413, 1421, 1481, 1489, 1490, 1546, 1690, 1733, 1740, 1746, 1796,
            1825, 1826, 1856, 1857, 1996, 2004, 2020, 2028, 2140, 2196, 2306, 2307, 2394, 2395, 2413, 2417, 2425, 2496,
            2497, 2731, 2739, 2818, 2874,
        ]; // indices are before the reorder
        let half_weight = 500;
        let noisy_measurements = 51;
        example_partition_standard_syndrome(
            &mut CircuitLevelPlanarCode::new(7, noisy_measurements, 0.005, half_weight),
            visualize_filename,
            defect_vertices,
            true,
            28980 / 2,
            PhenomenologicalPlanarCodeTimePartition::new(7, noisy_measurements, 3),
        );
    }

    /// demo of tree fusion
    #[test]
    fn example_partition_demo_3() {
        // cargo test example_partition_demo_3 -- --nocapture
        let visualize_filename = "example_partition_demo_3.json".to_string();
        // reorder vertices to enable the partition;
        let defect_vertices = vec![
            57, 113, 289, 304, 305, 331, 345, 387, 485, 493, 528, 536, 569, 570, 587, 588, 696, 745, 801, 833, 834, 884,
            904, 940, 1152, 1184, 1208, 1258, 1266, 1344, 1413, 1421, 1481, 1489, 1490, 1546, 1690, 1733, 1740, 1746, 1796,
            1825, 1826, 1856, 1857, 1996, 2004, 2020, 2028, 2140, 2196, 2306, 2307, 2394, 2395, 2413, 2417, 2425, 2496,
            2497, 2731, 2739, 2818, 2874,
        ]; // indices are before the reorder
        let half_weight = 500;
        let noisy_measurements = 51;
        example_partition_standard_syndrome(
            &mut PhenomenologicalPlanarCode::new(7, noisy_measurements, 0.005, half_weight),
            visualize_filename,
            defect_vertices,
            true,
            35 * half_weight,
            PhenomenologicalPlanarCodeTimePartition::new_tree(7, noisy_measurements, 8, true, usize::MAX),
        );
    }

    /// demo of sequential fuse
    #[test]
    fn example_partition_demo_4() {
        // cargo test example_partition_demo_4 -- --nocapture
        let visualize_filename = "example_partition_demo_4.json".to_string();
        // reorder vertices to enable the partition;
        let defect_vertices = vec![
            57, 113, 289, 304, 305, 331, 345, 387, 485, 493, 528, 536, 569, 570, 587, 588, 696, 745, 801, 833, 834, 884,
            904, 940, 1152, 1184, 1208, 1258, 1266, 1344, 1413, 1421, 1481, 1489, 1490, 1546, 1690, 1733, 1740, 1746, 1796,
            1825, 1826, 1856, 1857, 1996, 2004, 2020, 2028, 2140, 2196, 2306, 2307, 2394, 2395, 2413, 2417, 2425, 2496,
            2497, 2731, 2739, 2818, 2874,
        ]; // indices are before the reorder
        let half_weight = 500;
        let noisy_measurements = 51;
        example_partition_standard_syndrome(
            &mut PhenomenologicalPlanarCode::new(7, noisy_measurements, 0.005, half_weight),
            visualize_filename,
            defect_vertices,
            true,
            35 * half_weight,
            PhenomenologicalPlanarCodeTimePartition::new(7, noisy_measurements, 8),
        );
    }

    /// demo of tree + sequential fuse
    #[test]
    fn example_partition_demo_5() {
        // cargo test example_partition_demo_5 -- --nocapture
        let visualize_filename = "example_partition_demo_5.json".to_string();
        // reorder vertices to enable the partition;
        let defect_vertices = vec![
            57, 113, 289, 304, 305, 331, 345, 387, 485, 493, 528, 536, 569, 570, 587, 588, 696, 745, 801, 833, 834, 884,
            904, 940, 1152, 1184, 1208, 1258, 1266, 1344, 1413, 1421, 1481, 1489, 1490, 1546, 1690, 1733, 1740, 1746, 1796,
            1825, 1826, 1856, 1857, 1996, 2004, 2020, 2028, 2140, 2196, 2306, 2307, 2394, 2395, 2413, 2417, 2425, 2496,
            2497, 2731, 2739, 2818, 2874,
        ]; // indices are before the reorder
        let half_weight = 500;
        let noisy_measurements = 51;
        example_partition_standard_syndrome(
            &mut PhenomenologicalPlanarCode::new(7, noisy_measurements, 0.005, half_weight),
            visualize_filename,
            defect_vertices,
            true,
            35 * half_weight,
            PhenomenologicalPlanarCodeTimePartition::new_tree(7, noisy_measurements, 8, true, 3),
        );
    }
}