qsimulator 0.3.0

A noiseless state-vector quantum circuit simulator with OpenQASM 2.0 support
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
//! Circuit builder and executor.

use crate::gates;
use crate::rng::Rng;
use crate::state::State;
use num_complex::Complex64;
use std::collections::HashMap;
use std::fmt;

type Gate = [[Complex64; 2]; 2];

/// Reason a circuit could not be exported to the OpenQASM 2.0 subset by
/// [`Circuit::to_qasm`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExportError {
    /// An arbitrary single-qubit gate with no OpenQASM name. Built-in gates
    /// never produce this; it can only arise from a manually built `Op`.
    SingleGate {
        /// The gate's diagram label.
        label: &'static str,
    },
}

impl fmt::Display for ExportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ExportError::SingleGate { label } => {
                write!(f, "cannot export single-qubit gate `{label}` to OpenQASM 2")
            }
        }
    }
}

impl std::error::Error for ExportError {}

/// A single instruction in a circuit.
///
/// Each gate-bearing variant carries a short `label` (e.g. `"H"`, `"RX"`)
/// used for diagram rendering and QASM export; it never affects execution.
/// `Single` additionally records the gate's angle `params` (empty for
/// non-parametric gates, one for rotations/phase, up to three for `u3`) so
/// that export is lossless.
#[derive(Debug, Clone)]
enum Op {
    Single {
        gate: Gate,
        target: usize,
        label: &'static str,
        params: Vec<f64>,
    },
    Controlled {
        gate: Gate,
        control: usize,
        target: usize,
        label: &'static str,
        params: Vec<f64>,
    },
    Swap {
        a: usize,
        b: usize,
    },
    /// A mid-circuit measurement: collapses `qubit` onto the sampled outcome.
    /// The classical bit it would be written to is not modelled, since nothing
    /// in the supported subset can read one back.
    Measure {
        qubit: usize,
    },
    MultiControlled {
        gate: Gate,
        controls: Vec<usize>,
        target: usize,
        label: &'static str,
    },
}

/// A quantum circuit: an ordered list of gate operations on `n_qubits`.
#[derive(Debug, Clone)]
pub struct Circuit {
    n_qubits: usize,
    ops: Vec<Op>,
}

impl Circuit {
    /// Create an empty circuit over `n_qubits` qubits.
    pub fn new(n_qubits: usize) -> Self {
        Circuit {
            n_qubits,
            ops: Vec::new(),
        }
    }

    /// Hadamard gate on `target`.
    pub fn h(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::h(),
            target,
            label: "H",
            params: Vec::new(),
        });
        self
    }

    /// Pauli-X (NOT) gate on `target`.
    pub fn x(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::x(),
            target,
            label: "X",
            params: Vec::new(),
        });
        self
    }

    /// Pauli-Z gate on `target`.
    pub fn z(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::z(),
            target,
            label: "Z",
            params: Vec::new(),
        });
        self
    }

    /// Identity gate on `target`: a no-op, kept so a circuit can record an
    /// explicit idle step (OpenQASM's `id`).
    pub fn id(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::id(),
            target,
            label: "I",
            params: Vec::new(),
        });
        self
    }

    /// Square root of X on `target` (OpenQASM `sx`): `sx` twice is X.
    pub fn sx(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::sx(),
            target,
            label: "SX",
            params: Vec::new(),
        });
        self
    }

    /// Inverse square root of X on `target` (OpenQASM `sxdg`).
    pub fn sxdg(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::sxdg(),
            target,
            label: "SXDG",
            params: Vec::new(),
        });
        self
    }

    /// Pauli-Y gate on `target`.
    pub fn y(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::y(),
            target,
            label: "Y",
            params: Vec::new(),
        });
        self
    }

    /// Phase gate S = diag(1, i).
    pub fn s(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::s(),
            target,
            label: "S",
            params: Vec::new(),
        });
        self
    }

    /// T gate = diag(1, e^{i pi/4}).
    pub fn t(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::t(),
            target,
            label: "T",
            params: Vec::new(),
        });
        self
    }

    /// S-dagger gate = S† = diag(1, -i).
    pub fn sdg(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::sdg(),
            target,
            label: "SDG",
            params: Vec::new(),
        });
        self
    }

    /// T-dagger gate = T† = diag(1, e^{-i pi/4}).
    pub fn tdg(&mut self, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::tdg(),
            target,
            label: "TDG",
            params: Vec::new(),
        });
        self
    }

    /// Phase gate P(lambda) = diag(1, e^{i·lambda}) on `target`.
    ///
    /// Generalizes Z/S/T (`p(π)` = Z, `p(π/2)` = S, `p(π/4)` = T) and maps to
    /// OpenQASM's `u1(lambda)`.
    pub fn p(&mut self, lambda: f64, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::p(lambda),
            target,
            label: "P",
            params: vec![lambda],
        });
        self
    }

    /// General single-qubit gate U3(theta, phi, lambda) on `target`
    /// (the OpenQASM `u3`).
    pub fn u3(&mut self, theta: f64, phi: f64, lambda: f64, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::u3(theta, phi, lambda),
            target,
            label: "U3",
            params: vec![theta, phi, lambda],
        });
        self
    }

    /// Single-qubit gate U2(phi, lambda) = U3(pi/2, phi, lambda) on `target`
    /// (the OpenQASM `u2`).
    pub fn u2(&mut self, phi: f64, lambda: f64, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::u2(phi, lambda),
            target,
            label: "U2",
            params: vec![phi, lambda],
        });
        self
    }

    /// Rotation about the X axis by `theta` on `target`.
    pub fn rx(&mut self, theta: f64, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::rx(theta),
            target,
            label: "RX",
            params: vec![theta],
        });
        self
    }

    /// Rotation about the Y axis by `theta` on `target`.
    pub fn ry(&mut self, theta: f64, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::ry(theta),
            target,
            label: "RY",
            params: vec![theta],
        });
        self
    }

    /// Rotation about the Z axis by `theta` on `target`.
    pub fn rz(&mut self, theta: f64, target: usize) -> &mut Self {
        self.ops.push(Op::Single {
            gate: gates::rz(theta),
            target,
            label: "RZ",
            params: vec![theta],
        });
        self
    }

    /// Controlled-NOT: flips `target` when `control` is |1>.
    pub fn cnot(&mut self, control: usize, target: usize) -> &mut Self {
        self.ops.push(Op::Controlled {
            gate: gates::x(),
            control,
            target,
            label: "X",
            params: Vec::new(),
        });
        self
    }

    /// Controlled-U: apply the arbitrary 2x2 unitary `gate` to `target` only
    /// on basis states where `control` is |1>.
    pub fn cu(&mut self, gate: Gate, control: usize, target: usize) -> &mut Self {
        self.ops.push(Op::Controlled {
            gate,
            control,
            target,
            label: "U",
            params: Vec::new(),
        });
        self
    }

    /// Controlled-Rz: apply `rz(theta)` to `target` when `control` is |1>
    /// (the OpenQASM `crz`).
    pub fn crz(&mut self, theta: f64, control: usize, target: usize) -> &mut Self {
        self.ops.push(Op::Controlled {
            gate: gates::rz(theta),
            control,
            target,
            label: "CRZ",
            params: vec![theta],
        });
        self
    }

    /// Controlled phase: apply a phase e^{i·lambda} to the |11> component of
    /// `control` and `target` (the OpenQASM `cu1`). Symmetric in its two
    /// arguments.
    pub fn cp(&mut self, lambda: f64, control: usize, target: usize) -> &mut Self {
        self.ops.push(Op::Controlled {
            gate: gates::p(lambda),
            control,
            target,
            label: "CP",
            params: vec![lambda],
        });
        self
    }

    /// Controlled-U3: apply `u3(theta, phi, lambda)` to `target` when `control`
    /// is |1> (the OpenQASM `cu3`).
    pub fn cu3(
        &mut self,
        theta: f64,
        phi: f64,
        lambda: f64,
        control: usize,
        target: usize,
    ) -> &mut Self {
        self.ops.push(Op::Controlled {
            gate: gates::u3(theta, phi, lambda),
            control,
            target,
            label: "CU3",
            params: vec![theta, phi, lambda],
        });
        self
    }

    /// Controlled-Z: apply a phase of -1 to the |11> component of `control`
    /// and `target`. Symmetric in its two arguments.
    pub fn cz(&mut self, control: usize, target: usize) -> &mut Self {
        self.ops.push(Op::Controlled {
            gate: gates::z(),
            control,
            target,
            label: "Z",
            params: Vec::new(),
        });
        self
    }

    /// Controlled-Y: apply Y to `target` when `control` is |1> (OpenQASM `cy`).
    pub fn cy(&mut self, control: usize, target: usize) -> &mut Self {
        self.ops.push(Op::Controlled {
            gate: gates::y(),
            control,
            target,
            label: "Y",
            params: Vec::new(),
        });
        self
    }

    /// Controlled-Hadamard: apply H to `target` when `control` is |1>
    /// (OpenQASM `ch`).
    pub fn ch(&mut self, control: usize, target: usize) -> &mut Self {
        self.ops.push(Op::Controlled {
            gate: gates::h(),
            control,
            target,
            label: "H",
            params: Vec::new(),
        });
        self
    }

    /// SWAP: exchange the states of qubits `a` and `b`.
    pub fn swap(&mut self, a: usize, b: usize) -> &mut Self {
        self.ops.push(Op::Swap { a, b });
        self
    }

    /// Controlled-SWAP (Fredkin): exchange qubits `a` and `b` when `control`
    /// is |1> (OpenQASM `cswap`). Implemented via the standard identity
    /// `CSWAP(c,a,b) = CNOT(b,a)·CCX(c,a,b)·CNOT(b,a)`.
    pub fn cswap(&mut self, control: usize, a: usize, b: usize) -> &mut Self {
        self.cnot(b, a);
        self.toffoli(control, a, b);
        self.cnot(b, a);
        self
    }

    /// Multi-controlled-U: apply the arbitrary 2x2 unitary `gate` to `target`
    /// only on basis states where *every* qubit in `controls` is |1>.
    ///
    /// Zero controls is an unconditional gate, one control matches [`cu`], and
    /// two controls with X is a Toffoli.
    ///
    /// [`cu`]: Circuit::cu
    pub fn mcu(&mut self, gate: Gate, controls: &[usize], target: usize) -> &mut Self {
        self.ops.push(Op::MultiControlled {
            gate,
            controls: controls.to_vec(),
            target,
            label: "U",
        });
        self
    }

    /// Multi-controlled-X: flip `target` only when every qubit in `controls`
    /// is |1>. The generalization of [`cnot`] and [`toffoli`] to any number of
    /// controls.
    ///
    /// [`cnot`]: Circuit::cnot
    /// [`toffoli`]: Circuit::toffoli
    pub fn mcx(&mut self, controls: &[usize], target: usize) -> &mut Self {
        self.ops.push(Op::MultiControlled {
            gate: gates::x(),
            controls: controls.to_vec(),
            target,
            label: "X",
        });
        self
    }

    /// Toffoli (CCNOT): flip `target` only when both `control1` and
    /// `control2` are |1>.
    pub fn toffoli(&mut self, control1: usize, control2: usize, target: usize) -> &mut Self {
        self.mcx(&[control1, control2], target)
    }

    /// Measure `qubit` in the computational basis, collapsing the register onto
    /// the observed outcome.
    ///
    /// This makes the circuit *stochastic*: everything after it depends on
    /// which outcome came up, so [`run`](Circuit::run) is no longer a pure
    /// function of the circuit alone and [`run_seeded`](Circuit::run_seeded)
    /// is how you choose the stream. The outcome itself is discarded — the
    /// supported subset has no classical control to read it back — but the
    /// collapse is what makes a later gate see a definite state rather than a
    /// superposition.
    pub fn measure(&mut self, qubit: usize) -> &mut Self {
        self.ops.push(Op::Measure { qubit });
        self
    }

    /// Whether the circuit measures at all.
    fn has_measurement(&self) -> bool {
        self.ops.iter().any(|op| matches!(op, Op::Measure { .. }))
    }

    /// How many of the final operations are measurements — the circuit's
    /// readout, as opposed to a measurement something else depends on.
    fn trailing_measurements(&self) -> usize {
        self.ops
            .iter()
            .rev()
            .take_while(|op| matches!(op, Op::Measure { .. }))
            .count()
    }

    /// Whether a collapse can affect anything that follows it.
    ///
    /// Only a measurement with an operation after it can: it changes what that
    /// operation sees. A measurement at the very end cannot, and it is that
    /// case alone that forces [`sample`](Circuit::sample) to re-run the circuit
    /// per shot.
    fn measures_mid_circuit(&self) -> bool {
        self.ops[..self.ops.len() - self.trailing_measurements()]
            .iter()
            .any(|op| matches!(op, Op::Measure { .. }))
    }

    /// Run the circuit starting from |0...0> and return the state it prepares.
    ///
    /// Measurements at the *end* of the circuit are readout and are not
    /// applied: collapsing them would discard the prepared state and report one
    /// arbitrary branch, and [`sample`](Circuit::sample) draws the same
    /// distribution either way. This keeps the result deterministic for the
    /// usual written-out program, which ends in a measurement.
    ///
    /// A measurement with gates *after* it does collapse, since those gates
    /// must see a definite state. That makes the result depend on the collapse
    /// outcomes, and this uses seed 0 — see
    /// [`run_seeded`](Circuit::run_seeded) to choose the stream.
    pub fn run(&self) -> State {
        self.run_seeded(0)
    }

    /// Run the circuit with an explicit seed for any mid-circuit measurement.
    ///
    /// Without a mid-circuit [`measure`](Circuit::measure) the seed changes
    /// nothing and this is exactly [`run`](Circuit::run).
    pub fn run_seeded(&self, seed: u64) -> State {
        let mut rng = Rng::new(seed);
        self.run_with(&mut rng)
    }

    /// Execute against a caller-supplied RNG, so repeated shots of a
    /// stochastic circuit draw from one stream rather than restarting it.
    fn run_with(&self, rng: &mut Rng) -> State {
        let mut state = State::new(self.n_qubits);
        // Trailing measurements are readout: nothing follows them, so
        // collapsing would only discard the prepared state and make the result
        // depend on the seed. `sample` draws the same distribution either way.
        let executable = self.ops.len() - self.trailing_measurements();
        for op in &self.ops[..executable] {
            match op {
                Op::Measure { qubit } => {
                    state.measure_qubit(*qubit, rng);
                }
                Op::Single { gate, target, .. } => state.apply_1q(gate, *target),
                Op::Controlled {
                    gate,
                    control,
                    target,
                    ..
                } => state.apply_controlled_1q(gate, *control, *target),
                Op::Swap { a, b } => state.swap_qubits(*a, *b),
                Op::MultiControlled {
                    gate,
                    controls,
                    target,
                    ..
                } => state.apply_multi_controlled_1q(gate, controls, *target),
            }
        }
        state
    }

    /// Run the circuit `shots` times and return a histogram of measured
    /// basis-state outcomes.
    ///
    /// The circuit is executed once, then each shot measures a fresh clone of
    /// the resulting state so the shots are independent. `seed` makes the
    /// whole sampling run deterministic and reproducible. Keys of the returned
    /// map are little-endian basis-state indices; values are counts.
    pub fn sample(&self, shots: usize, seed: u64) -> HashMap<usize, usize> {
        let mut rng = Rng::new(seed);
        let mut histogram = HashMap::new();

        // A mid-circuit measurement branches the state, so every shot has to
        // re-run the circuit; there is no single final state to draw from.
        // Otherwise — including when the circuit ends with measurements, as
        // most written-out programs do — running once and measuring clones
        // draws from the same distribution, and executes the circuit once
        // instead of `shots` times.
        if self.measures_mid_circuit() {
            for _ in 0..shots {
                let outcome = self.run_with(&mut rng).measure_all(&mut rng);
                *histogram.entry(outcome).or_insert(0) += 1;
            }
        } else {
            let final_state = self.run();
            for _ in 0..shots {
                let outcome = final_state.clone().measure_all(&mut rng);
                *histogram.entry(outcome).or_insert(0) += 1;
            }
        }
        histogram
    }

    /// Export the circuit as an OpenQASM 2.0 program string.
    ///
    /// Emits the standard header, a single `qreg q[n]`, and one gate per line.
    /// The output round-trips through [`qasm::parse`](crate::qasm::parse):
    /// re-importing it yields an equivalent circuit. Angles are written at full
    /// `f64` precision so the round trip is exact.
    ///
    /// Gates without a direct OpenQASM 2 equivalent are decomposed into ones
    /// that have one: an arbitrary controlled-U ([`cu`](Circuit::cu)) into a
    /// control phase (`u1`) plus a `cu3`, and a multi-controlled gate
    /// ([`mcx`](Circuit::mcx), [`mcu`](Circuit::mcu)) into Toffolis and
    /// single-qubit rotations. Only an unconditional [`mcu`](Circuit::mcu) —
    /// one with no controls at all — loses anything: its global phase, which
    /// OpenQASM 2 cannot express and no measurement can observe.
    ///
    /// Every built-in gate exports, so the error case is unreachable for
    /// circuits built through this API.
    ///
    /// # Example
    ///
    /// ```
    /// use qsimulator::Circuit;
    /// let mut c = Circuit::new(2);
    /// c.h(0).cnot(0, 1);
    /// let qasm = c.to_qasm().unwrap();
    /// assert!(qasm.starts_with("OPENQASM 2.0;"));
    /// assert!(qasm.contains("cx q[0],q[1];"));
    /// ```
    pub fn to_qasm(&self) -> Result<String, ExportError> {
        let mut out = String::from("OPENQASM 2.0;\ninclude \"qelib1.inc\";\n");
        out.push_str(&format!("qreg q[{}];\n", self.n_qubits));
        if self.has_measurement() {
            out.push_str(&format!("creg c[{}];\n", self.n_qubits));
        }

        for op in &self.ops {
            match op {
                Op::Single {
                    target,
                    label,
                    params,
                    ..
                } => {
                    let name = match *label {
                        "I" => "id",
                        "H" => "h",
                        "X" => "x",
                        "Y" => "y",
                        "Z" => "z",
                        "S" => "s",
                        "T" => "t",
                        "SDG" => "sdg",
                        "SX" => "sx",
                        "SXDG" => "sxdg",
                        "TDG" => "tdg",
                        "P" => "u1",
                        "U2" => "u2",
                        "U3" => "u3",
                        "RX" => "rx",
                        "RY" => "ry",
                        "RZ" => "rz",
                        other => return Err(ExportError::SingleGate { label: other }),
                    };
                    out.push_str(&format!("{name}{} q[{target}];\n", format_params(params)));
                }
                Op::Controlled {
                    gate,
                    control,
                    target,
                    label,
                    params,
                } => {
                    match *label {
                        "X" => out.push_str(&format!("cx q[{control}],q[{target}];\n")),
                        "Y" => out.push_str(&format!("cy q[{control}],q[{target}];\n")),
                        "Z" => out.push_str(&format!("cz q[{control}],q[{target}];\n")),
                        "H" => out.push_str(&format!("ch q[{control}],q[{target}];\n")),
                        "CRZ" | "CP" | "CU3" => {
                            let name = match *label {
                                "CRZ" => "crz",
                                "CP" => "cu1",
                                _ => "cu3",
                            };
                            out.push_str(&format!(
                                "{name}{} q[{control}],q[{target}];\n",
                                format_params(params)
                            ));
                        }
                        // Any other controlled single-qubit unitary (e.g. `cu`
                        // with an arbitrary matrix): decompose into a phase on
                        // the control followed by a controlled-U3.
                        _ => emit_controlled_u(&mut out, gate, *control, *target),
                    }
                }
                Op::Swap { a, b } => {
                    out.push_str(&format!("swap q[{a}],q[{b}];\n"));
                }
                // The classical bit is not modelled, so each measurement gets
                // its own bit, named after the qubit it came from.
                Op::Measure { qubit } => {
                    out.push_str(&format!("measure q[{qubit}] -> c[{qubit}];\n"));
                }
                Op::MultiControlled {
                    gate,
                    controls,
                    target,
                    label,
                } => {
                    if *label == "X" {
                        emit_mcx(&mut out, self.n_qubits, controls, *target);
                    } else {
                        emit_mcu(&mut out, self.n_qubits, gate, controls, *target);
                    }
                }
            }
        }
        Ok(out)
    }

    /// Render the circuit as an ASCII diagram.
    ///
    /// One column per operation, time flowing left to right, with qubit `q0`
    /// on the top row. Controls are drawn as `*`, targets as their gate label
    /// (CNOT/Toffoli targets as `X`), SWAP endpoints as `x`, and `|` connects
    /// the qubits an operation spans. The diagram is presentational only —
    /// each operation occupies its own column, so it shows program order, not
    /// a parallel-scheduled timeline.
    ///
    /// # Example
    ///
    /// ```
    /// use qsimulator::Circuit;
    /// let mut c = Circuit::new(2);
    /// c.h(0).cnot(0, 1);
    /// assert_eq!(c.diagram(), "q0: -H-*-\nq1: ---X-");
    /// ```
    pub fn diagram(&self) -> String {
        let n = self.n_qubits;

        // For each op build one column: per qubit, the token to place, or
        // `None` for a plain wire.
        let mut columns: Vec<Vec<Option<&'static str>>> = Vec::with_capacity(self.ops.len());
        for op in &self.ops {
            let mut col: Vec<Option<&'static str>> = vec![None; n];
            match op {
                Op::Single { target, label, .. } => {
                    col[*target] = Some(label);
                }
                Op::Controlled {
                    control,
                    target,
                    label,
                    ..
                } => {
                    col[*control] = Some("*");
                    col[*target] = Some(label);
                    fill_connector(&mut col, &[*control, *target]);
                }
                Op::Swap { a, b } => {
                    col[*a] = Some("x");
                    col[*b] = Some("x");
                    fill_connector(&mut col, &[*a, *b]);
                }
                Op::Measure { qubit } => {
                    col[*qubit] = Some("M");
                }
                Op::MultiControlled {
                    controls,
                    target,
                    label,
                    ..
                } => {
                    for &c in controls {
                        col[c] = Some("*");
                    }
                    col[*target] = Some(label);
                    let mut involved = controls.clone();
                    involved.push(*target);
                    fill_connector(&mut col, &involved);
                }
            }
            columns.push(col);
        }

        // Cell width = widest token present (at least 1).
        let cell_w = columns
            .iter()
            .flatten()
            .flatten()
            .map(|s| s.len())
            .max()
            .unwrap_or(1)
            .max(1);

        // Width of the "qN:" label gutter, sized for the largest qubit index.
        let gutter = format!("q{}:", n.saturating_sub(1)).len();

        let mut lines = Vec::with_capacity(n);
        for r in 0..n {
            let mut line = format!("{:<width$} -", format!("q{r}:"), width = gutter);
            if columns.is_empty() {
                line.push_str(&"-".repeat(cell_w));
            }
            for col in &columns {
                line.push_str(&center(col[r].unwrap_or(""), cell_w));
                line.push('-');
            }
            lines.push(line);
        }
        lines.join("\n")
    }
}

/// Angles smaller than this are treated as zero, and their gate is left out of
/// the exported program.
const ANGLE_EPS: f64 = 1e-12;

/// Emit `name(angle) q[target];`, unless `angle` is negligible.
fn emit_rotation(out: &mut String, name: &str, angle: f64, target: usize) {
    if angle.abs() > ANGLE_EPS {
        out.push_str(&format!("{name}({angle}) q[{target}];\n"));
    }
}

/// Emit a controlled arbitrary 2x2 unitary as a phase on the control followed
/// by a `cu3`, using the Euler decomposition `gate == e^{iγ}·u3(θ, φ, λ)`.
fn emit_controlled_u(out: &mut String, gate: &Gate, control: usize, target: usize) {
    let (gamma, theta, phi, lambda) = gates::u3_decompose(gate);
    emit_rotation(out, "u1", gamma, control);
    out.push_str(&format!(
        "cu3({theta},{phi},{lambda}) q[{control}],q[{target}];\n"
    ));
}

/// The lowest-numbered qubit of the register that an operation on
/// `controls`/`target` leaves untouched, if any.
fn free_qubit(n_qubits: usize, controls: &[usize], target: usize) -> Option<usize> {
    (0..n_qubits).find(|q| *q != target && !controls.contains(q))
}

/// Emit a multi-controlled X (`target ^= AND(controls)`) as OpenQASM 2 gates.
///
/// Up to two controls this is `x`/`cx`/`ccx` directly. Beyond that it is a
/// Barenco-style decomposition into Toffolis, in one of two ways:
///
/// - **With a spare qubit** — any register qubit the operation does not touch
///   can be *borrowed* even though its state is unknown ("dirty"). The
///   controls are split into two halves; the borrowed qubit is toggled by the
///   first half and used as an extra control for the second, and the whole
///   pair is run twice so the qubit's unknown initial value cancels out of the
///   target and the qubit itself is left as it was found. Each half is a
///   strictly smaller multi-controlled X, so this recurses to Toffolis in
///   `O(controls²)` gates.
/// - **With no spare qubit** (the controls plus the target are the whole
///   register) — the square-root recursion, with `V·V = X`:
///   `C^m(X) = C(V)[c_m,t] · C^{m-1}(X)[c_<m→c_m] · C(V†)[c_m,t] ·
///   C^{m-1}(X)[c_<m→c_m] · C^{m-1}(V)[c_<m→t]`. Every inner operation leaves
///   a qubit untouched, so the recursion lands in the borrowed-qubit case.
fn emit_mcx(out: &mut String, n_qubits: usize, controls: &[usize], target: usize) {
    match controls {
        [] => out.push_str(&format!("x q[{target}];\n")),
        [c] => out.push_str(&format!("cx q[{c}],q[{target}];\n")),
        [a, b] => out.push_str(&format!("ccx q[{a}],q[{b}],q[{target}];\n")),
        _ => match free_qubit(n_qubits, controls, target) {
            Some(borrowed) => {
                // Both halves are shorter than `controls` (the split point is
                // between 2 and controls.len() - 1), so this terminates.
                let (lo, hi) = controls.split_at(controls.len().div_ceil(2));
                let mut hi_borrowed = hi.to_vec();
                hi_borrowed.push(borrowed);
                for _ in 0..2 {
                    emit_mcx(out, n_qubits, lo, borrowed);
                    emit_mcx(out, n_qubits, &hi_borrowed, target);
                }
            }
            None => {
                let (&last, rest) = controls.split_last().expect("at least three controls");
                emit_controlled_u(out, &gates::sx(), last, target);
                emit_mcx(out, n_qubits, rest, last);
                emit_controlled_u(out, &gates::sxdg(), last, target);
                emit_mcx(out, n_qubits, rest, last);
                emit_mcu(out, n_qubits, &gates::sx(), rest, target);
            }
        },
    }
}

/// Emit a multi-controlled arbitrary 2x2 unitary as OpenQASM 2 gates.
///
/// Writes `gate` as `e^{iγ''}·A·X·B·X·C` with `A·B·C = I`, where `A`, `B` and
/// `C` are products of `rz`/`ry` built from the Euler angles of
/// `gates::u3_decompose`. Conditioning only the two `X`s (on the full control
/// set, via [`emit_mcx`]) and the phase `γ''` (via [`emit_mcphase`]) then gives
/// the controlled gate: when the controls are not all set, `A·B·C` collapses to
/// the identity and no phase is applied.
///
/// A diagonal `gate` — a multi-controlled Z, S, T or phase — skips the `X`s
/// entirely and exports as two phase terms.
///
/// With no controls the gate is unconditional, so its global phase is
/// unobservable and is dropped (OpenQASM 2 cannot express one).
fn emit_mcu(out: &mut String, n_qubits: usize, gate: &Gate, controls: &[usize], target: usize) {
    let (gamma, theta, phi, lambda) = gates::u3_decompose(gate);

    if controls.is_empty() {
        out.push_str(&format!("u3({theta},{phi},{lambda}) q[{target}];\n"));
        return;
    }

    // Diagonal gate: diag(e^{iγ}, e^{i(γ+λ)}). The first factor is a phase on
    // the controls alone, the second a phase on the controls and the target.
    // Cheaper than the general path at every width, so it comes first.
    if theta.abs() < ANGLE_EPS {
        emit_mcphase(out, n_qubits, gamma, controls);
        let mut controls_and_target = controls.to_vec();
        controls_and_target.push(target);
        emit_mcphase(out, n_qubits, lambda, &controls_and_target);
        return;
    }

    if controls.len() == 1 {
        emit_controlled_u(out, gate, controls[0], target);
        return;
    }

    // C = Rz((λ-φ)/2), B = Ry(-θ/2)·Rz(-(λ+φ)/2), A = Rz(φ)·Ry(θ/2). Then
    // A·B·C = I and A·X·B·X·C = Rz(φ)·Ry(θ)·Rz(λ), which is u3(θ,φ,λ) up to
    // the phase e^{i(φ+λ)/2} — folded into γ'' below. Gates are emitted in
    // time order, so each matrix product is written back to front.
    emit_rotation(out, "rz", (lambda - phi) / 2.0, target);
    emit_mcx(out, n_qubits, controls, target);
    emit_rotation(out, "rz", -(lambda + phi) / 2.0, target);
    emit_rotation(out, "ry", -theta / 2.0, target);
    emit_mcx(out, n_qubits, controls, target);
    emit_rotation(out, "ry", theta / 2.0, target);
    emit_rotation(out, "rz", phi, target);
    emit_mcphase(out, n_qubits, gamma + (phi + lambda) / 2.0, controls);
}

/// Emit a phase of `e^{i·lambda}` applied only when every qubit in `qubits` is
/// |1>, as OpenQASM 2 gates.
///
/// One qubit is `u1` and two are `cu1`. Beyond that it uses the same identity
/// that decomposes `cu1` — half the phase on the leading qubits, then the
/// remaining qubit conjugated by a multi-controlled X — which peels off one
/// qubit per step. Since a phase is diagonal, the emitted gates commute and the
/// order among them does not matter.
fn emit_mcphase(out: &mut String, n_qubits: usize, lambda: f64, qubits: &[usize]) {
    if lambda.abs() < ANGLE_EPS {
        return;
    }
    match qubits {
        // A global phase, which OpenQASM 2 cannot express and no measurement
        // can see.
        [] => {}
        [q] => out.push_str(&format!("u1({lambda}) q[{q}];\n")),
        [a, b] => out.push_str(&format!("cu1({lambda}) q[{a}],q[{b}];\n")),
        _ => {
            let (&last, rest) = qubits.split_last().expect("at least three qubits");
            let half = lambda / 2.0;
            emit_mcphase(out, n_qubits, half, rest);
            emit_mcx(out, n_qubits, rest, last);
            emit_rotation(out, "u1", -half, last);
            emit_mcx(out, n_qubits, rest, last);
            emit_rotation(out, "u1", half, last);
        }
    }
}

/// Format gate angle parameters as an OpenQASM parameter list: `""` for none,
/// `"(θ)"` for one, `"(θ,φ,λ)"` for several. Angles use full `f64` precision
/// so exported programs round-trip exactly.
fn format_params(params: &[f64]) -> String {
    if params.is_empty() {
        return String::new();
    }
    let joined = params
        .iter()
        .map(|p| p.to_string())
        .collect::<Vec<_>>()
        .join(",");
    format!("({joined})")
}

/// Mark the rows strictly between the outermost involved qubits (that are not
/// themselves involved) with a `|` connector.
fn fill_connector(col: &mut [Option<&'static str>], involved: &[usize]) {
    let min = *involved.iter().min().unwrap();
    let max = *involved.iter().max().unwrap();
    for (r, cell) in col.iter_mut().enumerate() {
        if r > min && r < max && cell.is_none() {
            *cell = Some("|");
        }
    }
}

/// Center `token` in a field of `width`, padded with `-` (the wire character).
fn center(token: &str, width: usize) -> String {
    if token.len() >= width {
        return token.to_string();
    }
    let pad = width - token.len();
    let left = pad / 2;
    let right = pad - left;
    format!("{}{}{}", "-".repeat(left), token, "-".repeat(right))
}

impl fmt::Display for Circuit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.diagram())
    }
}