polypus 0.8.0

Rust-core quantum variational optimization framework with a Python (PyO3) interface: circuit simulation, VQC/QML training and population-based optimizers (DE, PSO, QNG, CMA-ES). Python users: `pip install polypus-quantum` (the module imports as `polypus`).
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
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
//! PyO3 bindings for the native Rust circuit layer (`polypus-circuit`).
//!
//! Exposes `polypus.Circuit` and `polypus.Param` so Python users can build
//! GIL-free circuits and pass them to `polypus.run_quantum_circuit` /
//! `polypus.train` exactly like a Qiskit `QuantumCircuit`.

use numpy::{IntoPyArray, PyArray1};
use polypus_circuit::draw::TextOptions;
use polypus_circuit::{
    CircuitError, ConcreteCircuit, GateInstruction, GateParam, ParameterizedCircuit,
};
use polypus_sim::{SimError, Simulator, Statevector, StatevectorSimulator};
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::PyBytes;

use super::expr::{self, Operand, ParamExpr};
use crate::infrastructure::{attach_or, check_statevector_fits, InterpreterUnavailable};

/// Map a native [`CircuitError`] onto a Python `ValueError`.
fn to_py_err(e: CircuitError) -> PyErr {
    PyValueError::new_err(e.to_string())
}

/// Reference to the trainable parameter at a given index.
///
/// ```python
/// qc = polypus.Circuit(2).rx(0, polypus.Param(0)).rzz(0, 1, polypus.Param(1))
/// ```
#[pyclass(module = "polypus", frozen, skip_from_py_object)]
#[derive(Clone, Copy)]
pub struct Param {
    /// Index into the parameter vector bound at execution time.
    #[pyo3(get)]
    pub index: usize,
}

#[pymethods]
impl Param {
    #[new]
    fn new(index: usize) -> Self {
        Param { index }
    }

    fn __repr__(&self) -> String {
        format!("Param({})", self.index)
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.index == other.index
    }

    fn __add__(&self, rhs: Operand) -> ParamExpr {
        (self.expr() + rhs.0).into()
    }

    fn __radd__(&self, lhs: Operand) -> ParamExpr {
        (lhs.0 + self.expr()).into()
    }

    fn __sub__(&self, rhs: Operand) -> ParamExpr {
        (self.expr() - rhs.0).into()
    }

    fn __rsub__(&self, lhs: Operand) -> ParamExpr {
        (lhs.0 - self.expr()).into()
    }

    fn __mul__(&self, rhs: Operand) -> ParamExpr {
        (self.expr() * rhs.0).into()
    }

    fn __rmul__(&self, lhs: Operand) -> ParamExpr {
        (lhs.0 * self.expr()).into()
    }

    fn __truediv__(&self, rhs: Operand) -> ParamExpr {
        (self.expr() / rhs.0).into()
    }

    fn __rtruediv__(&self, lhs: Operand) -> ParamExpr {
        (lhs.0 / self.expr()).into()
    }

    fn __pow__(&self, exponent: Operand, modulo: Option<&Bound<'_, PyAny>>) -> PyResult<ParamExpr> {
        expr::pow(self.expr(), exponent.0, modulo)
    }

    fn __rpow__(&self, base: Operand, modulo: Option<&Bound<'_, PyAny>>) -> PyResult<ParamExpr> {
        expr::pow(base.0, self.expr(), modulo)
    }

    fn __neg__(&self) -> ParamExpr {
        (-self.expr()).into()
    }
}

impl Param {
    fn expr(&self) -> polypus_circuit::ParamExpr {
        polypus_circuit::ParamExpr::param(self.index)
    }
}

/// An angle argument: a number (fixed angle), a [`Param`] reference or a
/// [`ParamExpr`] expression.
pub(crate) enum AngleArg {
    Fixed(f64),
    Param(usize),
    Expr(polypus_circuit::ParamExpr),
}

impl<'a, 'py> FromPyObject<'a, 'py> for AngleArg {
    type Error = PyErr;

    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
        if let Ok(p) = ob.extract::<PyRef<'_, Param>>() {
            return Ok(AngleArg::Param(p.index));
        }
        if let Ok(e) = ob.extract::<PyRef<'_, ParamExpr>>() {
            return Ok(AngleArg::Expr(e.inner.clone()));
        }
        if let Ok(v) = ob.extract::<f64>() {
            return Ok(AngleArg::Fixed(v));
        }
        Err(PyTypeError::new_err(
            "angle must be a number, polypus.Param or polypus.ParamExpr",
        ))
    }
}

/// Native Rust quantum circuit with OpenQASM 2.0 and OpenQASM 3 import and
/// export.
///
/// Construction and parameter binding run in pure Rust (no GIL), which makes
/// per-candidate binding during training parallelisable in ways a Qiskit
/// circuit can never be. Methods return `self`, so calls can be chained:
///
/// ```python
/// qc = (polypus.Circuit(3)
///       .h(0).h(1).h(2)
///       .rzz(0, 1, polypus.Param(0))
///       .rx(0, polypus.Param(1))
///       .measure_all())
/// polypus.train(qc, polypus.DE(...), dimensions=2, ...)
/// ```
#[pyclass(module = "polypus")]
pub struct Circuit {
    pub(crate) inner: ParameterizedCircuit,
}

impl Circuit {
    /// Access the wrapped native circuit (used by the entry points to build
    /// `CircuitSource::Native` / `BoundCircuit::Qasm2`).
    pub(crate) fn native(&self) -> &ParameterizedCircuit {
        &self.inner
    }

    /// The gate angle for `arg`; an expression is stored in the circuit
    /// ([`ParameterizedCircuit::add_expr`]), which validates it.
    fn angle(&mut self, arg: AngleArg) -> PyResult<GateParam> {
        Ok(match arg {
            AngleArg::Fixed(v) => GateParam::Fixed(v),
            AngleArg::Param(i) => GateParam::Param(i),
            AngleArg::Expr(e) => self.inner.add_expr(e).map_err(to_py_err)?,
        })
    }
}

/// Push `gate` onto the builder, translating errors to Python exceptions and
/// returning `self` for chaining.
fn push(mut slf: PyRefMut<'_, Circuit>, gate: GateInstruction) -> PyResult<PyRefMut<'_, Circuit>> {
    slf.inner.try_push(gate).map_err(to_py_err)?;
    Ok(slf)
}

/// Compute the full statevector of a native `polypus.Circuit` with the pure-Rust
/// `polypus-sim` backend (no Qiskit, no OpenQASM round-trip).
///
/// `params` supplies one value per free parameter; omit it for a circuit that
/// has none. Returns the `2^n` complex amplitudes as a **`numpy.ndarray` of
/// `dtype=complex128`**, in Qiskit little-endian order (qubit 0 is the
/// least-significant bit), so it can be compared directly with
/// `qiskit.quantum_info.Statevector` (whose `.data` is the same dtype) and fed
/// straight into NumPy without a conversion step.
///
/// The simulation runs **GIL-free** — only the cheap parameter binding and the
/// conversion of the result hold the GIL — so other Python threads keep making
/// progress while it runs (see `docs/ENGINEERING.md` §3).
///
/// **Interruptible.** A `KeyboardInterrupt` takes effect *mid-simulation*
/// (issue #110): the gate loop calls back into this function at checkpoints at
/// least ~25ms apart, each of which reacquires the GIL just long enough to
/// check for a pending signal — and, if one is pending, abandons the run and
/// raises that original exception verbatim. The throttling lives inside
/// `polypus-sim` and is what keeps this cheap: a circuit that finishes inside
/// one interval never calls back at all, the frequency does not depend on how
/// expensive an individual gate is, and the interval stretches to keep the
/// callback under ~5% of the run (which matters when another Python thread
/// holds the GIL and reacquiring it costs milliseconds). What is *not*
/// interruptible is the `2^n` allocation below, which is a single `vec![]`.
///
/// **Qubit ceiling.** A dense statevector needs `2^n` complex amplitudes
/// (`16 · 2^n` bytes), so the backend refuses circuits with more than
/// [`polypus_sim::MAX_QUBITS`] qubits (30 ≈ 16 GiB) and raises a `ValueError`
/// naming the requested and the supported count **before** attempting any
/// allocation. `polypus.Circuit` itself is deliberately unbounded (see
/// `Circuit::new`): the ceiling belongs to this backend, not to the IR. Note
/// that what a call near the ceiling spends its time on is *allocating* that
/// buffer, not handing it to Python: even a gateless 30-qubit circuit costs ~5s
/// (measured), essentially all of it `Statevector::new`'s 16 GiB `vec![]`. The
/// ceiling bounds memory, not wall-clock time — cost scales with gates × `2^n`
/// and nothing bounds the gate count, which is why the run has to stay
/// interruptible (see above) rather than relying on being short.
///
/// **Memory budget.** Below the ceiling, the `16 · 2^n`-byte statevector is also
/// checked against the same memory budget the native backend applies (issue
/// #215): `POLYPUS_MEM_BUDGET` when set, else the detected RAM/cgroup limit minus
/// a safety reserve. One that does not fit raises
/// `polypus.InsufficientMemoryError` (a `polypus.PolypusError`) before anything
/// is allocated, instead of the process being killed by the out-of-memory killer.
/// With no limit detected (macOS, Windows) nothing is refused. The ceiling's
/// `ValueError` is checked first and is unchanged.
///
/// **`fusion`** (default `true`) controls [`polypus_sim::StatevectorSimulator::fusion`]:
/// whether consecutive gates may be fused into fewer buffer passes before
/// applying them. Fusion only changes performance, never the result (up to
/// floating-point rounding order); pass `fusion=False` for a strictly
/// gate-by-gate simulation of exactly the circuit as written.
///
/// ```python
/// import polypus
/// qc = polypus.Circuit(2).h(0).cx(0, 1)
/// amps = polypus.statevector(qc)          # array([0.707…+0j, 0j, 0j, 0.707…+0j])
/// ```
#[pyfunction(signature = (qc, params = None, fusion = true))]
pub fn statevector<'py>(
    qc: PyRef<'py, Circuit>,
    params: Option<Vec<f64>>,
    fusion: bool,
) -> PyResult<Bound<'py, PyArray1<polypus_sim::C64>>> {
    let params = params.unwrap_or_default();
    // This entry point is always the native statevector path: calibrate the
    // gate-parallel threshold lazily on the first call (#351), then surface the
    // one-time, default-visible warning if it fell back to the static default
    // (stale calibration).
    super::calibration::prepare_native_threshold(qc.py())?;
    // Binding stays on this side of the release: it is O(gates), allocates
    // nothing of size `2^n`, and reads the circuit through the `PyRef`.
    let concrete = qc.native().assign_parameters(&params).map_err(to_py_err)?;
    // Refuse a statevector the memory budget cannot hold before allocating it
    // (issue #215). Above the ceiling the simulator's `ValueError` stays the error.
    if concrete.num_qubits() <= polypus_sim::MAX_QUBITS {
        check_statevector_fits(concrete.num_qubits())
            .map_err(|e| crate::exceptions::insufficient_memory_to_pyerr(&e))?;
    }
    // The simulation is the expensive, pure-Rust part: release the GIL for it
    // so it cannot stall every other Python thread (docs/ENGINEERING.md §3).
    //
    // Cancellation hook: `polypus-sim`'s gate loop calls this closure
    // periodically (throttled on its side to ≥25ms apart *and* to a small
    // fraction of the run, so the frequency is decoupled from gate cost and a
    // fast circuit never pays for it). Reacquiring the GIL from inside
    // `detach` is a *fresh* attach, not a reuse: `detach` resets the thread's
    // attachment, so `Python::attach` here could panic, hang, or attach to a
    // finalizing interpreter, if the interpreter were shutting down (e.g. a
    // daemon thread at exit, on any Python version). The hook therefore
    // attaches with `attach_or` (§9, see `poll_for_cancellation`) and, when the
    // interpreter cannot be reached, reports a cancellation: the run's result
    // could never be handed back to Python anyway, so it stops at once.
    // `check_signals()` is what turns a pending SIGINT into a
    // `KeyboardInterrupt` *mid-run*, since releasing the GIL does not by itself
    // process signals (§3).
    //
    // The `PyErr` cannot travel back through `SimError` (`polypus-sim` is
    // Python-free by design, §2), so it is stashed here and recovered below —
    // the same problem `OracleErrorSlot` solves for the optimizer oracles, and
    // the same reason: a generic trait boundary must not downgrade the real
    // exception. No `Arc<Mutex<...>>` is needed, though: `statevector` is
    // single-shot, and the hook runs on this very thread (the simulation is
    // inline in `detach`, not on a worker), so a `&mut` local is enough.
    // That is also why `check_signals()` is effective at all: it is a no-op off
    // the main thread, and this closure runs on whichever thread called us.
    let mut pending: Option<PyErr> = None;
    let outcome = qc
        .py()
        .detach(|| simulate_cancellable(&concrete, fusion, &mut pending));
    let sv = match outcome {
        Ok(sv) => sv,
        // Propagate the *real* pending exception verbatim. Mapping this through
        // `PyValueError::new_err(e.to_string())` like the variants below would
        // silently downgrade a `KeyboardInterrupt` into a bogus `ValueError`
        // (and `check_signals()` cannot be re-run to recover it: raising it
        // cleared the pending flag).
        Err(SimError::Cancelled) => return Err(cancellation_error(pending)),
        Err(e) => return Err(PyValueError::new_err(e.to_string())),
    };
    // A signal that arrived after the last checkpoint (or during the `2^n`
    // allocation, which has no checkpoint) is still honored here, the moment
    // the GIL is reacquired and before the amplitudes are handed to NumPy.
    qc.py().check_signals()?;
    // `into_amplitudes` (not `amplitudes().to_vec()`) so the `2^n`-element
    // buffer moves into the array instead of being copied: `sv` is owned here
    // and dropped immediately after.
    Ok(sv.into_amplitudes().into_pyarray(qc.py()))
}

/// The part of `statevector` that runs detached: simulate `circuit`, polling
/// [`poll_for_cancellation`] at the simulator's checkpoints. A pending signal
/// is stashed in `pending`. Pure Rust apart from that hook, so it can be tested
/// without an interpreter.
pub(super) fn simulate_cancellable(
    circuit: &ConcreteCircuit,
    fusion: bool,
    pending: &mut Option<PyErr>,
) -> Result<Statevector, SimError> {
    let mut cancelled = || poll_for_cancellation(pending);
    StatevectorSimulator {
        fusion,
        ..StatevectorSimulator::new()
    }
    .run_cancellable(circuit, Some(&mut cancelled))
}

/// The exception a cancelled `statevector` raises: the pending signal's own
/// (a Ctrl+C stays a `KeyboardInterrupt`), or, when the hook cancelled because
/// the interpreter became unreachable (shutdown), the `KeyboardInterrupt` every
/// other site reached while detached ends in for the same event
/// ([`InterpreterUnavailable`]): it is an abort, not an invalid input.
pub(super) fn cancellation_error(pending: Option<PyErr>) -> PyErr {
    pending.unwrap_or_else(|| {
        crate::exceptions::interpreter_unavailable_to_pyerr(InterpreterUnavailable)
    })
}

/// Body of the `statevector` cancellation hook, run while detached: `true`
/// cancels the simulation. A pending signal is stashed in `pending` so the real
/// exception can be re-raised; an interpreter that cannot be attached to
/// (shutting down) cancels too, without a pending exception.
pub(super) fn poll_for_cancellation(pending: &mut Option<PyErr>) -> bool {
    attach_or(
        || true,
        |py| match py.check_signals() {
            Ok(()) => false,
            Err(err) => {
                *pending = Some(err);
                true
            }
        },
    )
}

#[pymethods]
impl Circuit {
    /// Build an empty circuit on `num_qubits` qubits.
    ///
    /// **Intentionally unbounded.** A `Circuit` is backend-agnostic IR: the same
    /// object is routed by `polypus.run_quantum_circuit` to the native
    /// statevector simulator, CUNQA, QMIO or Aer, and those capacities differ.
    /// [`polypus_sim::MAX_QUBITS`] is the dense-statevector limit and is
    /// enforced where it applies — when a circuit is *simulated* (see
    /// [`statevector`]) — so checking it here would reject circuits that are
    /// perfectly valid for the other backends.
    #[new]
    fn new(num_qubits: usize) -> Self {
        Circuit {
            inner: ParameterizedCircuit::new(num_qubits),
        }
    }

    /// Import an OpenQASM 2.0 program (inverse of [`to_qasm2`](Circuit::to_qasm2)).
    ///
    /// Accepts the QASM this class exports plus Qiskit's `qasm2.dumps` output,
    /// `gate` declarations included (every instruction — `p`, `u1`, `u2`, `u`,
    /// `id` and calls of declared gates included — is kept one-to-one under its
    /// own spelling; only the builtins `U`/`CX` become `u`/`cx`; multiple
    /// registers are flattened in declaration order). The
    /// result is fully concrete (`num_params == 0`); builder methods can keep
    /// extending it.
    ///
    /// ```python
    /// qc = polypus.Circuit.from_qasm2(qiskit.qasm2.dumps(qiskit_circuit))
    /// ```
    #[staticmethod]
    fn from_qasm2(source: &str) -> PyResult<Self> {
        Ok(Circuit {
            inner: ParameterizedCircuit::from_qasm2(source).map_err(to_py_err)?,
        })
    }

    /// Import a program in the **OpenQASM 3 profile with Qiskit phase
    /// conventions** (inverse of [`to_qasm3`](Circuit::to_qasm3)).
    ///
    /// The profile is the straight-line part of OpenQASM 3 that carries a
    /// parameterised, terminal-measurement circuit: `include "stdgates.inc";`
    /// (provided internally; no file is ever read), `qubit` and `bit`
    /// registers, `input float[64]` parameters, calls of `U`, of the
    /// `stdgates.inc` gates and of gates declared with `gate` blocks,
    /// `barrier`, and measurements assigned to bits. Angles are expressions of
    /// the inputs and the constants `pi`, `tau` and `euler`, evaluated in
    /// binary64 exactly as written. Anything else — control flow, `reset`,
    /// classical computation, subroutines, gate modifiers, `gphase`, timing,
    /// arrays, physical qubits — raises `ValueError` naming the construct and
    /// its line, as does a division of two integers (`1/2`, integer division
    /// in OpenQASM 3: write `1.0/2`).
    ///
    /// Each `input` is a free parameter, in declaration order (unused ones
    /// included) and under its name ([`param_names`](Circuit::param_names)):
    /// bind values in that order. `U` becomes `u`, `CX` becomes `cx`, `phase`
    /// becomes `p` and `cphase` becomes `cp`; every other gate keeps its name,
    /// and a declared gate stays a declared gate whatever its name.
    ///
    /// **Phase convention.** `U`, `u2` and `u3` are read with Qiskit's
    /// matrices, which differ from the OpenQASM 3 specification's by the
    /// global phases e^{-iθ/2} (`U`) and e^{i(φ+λ)/2} (`u2`, `u3`).
    /// Statevector amplitudes may therefore differ from those of a reader that
    /// follows the specification by these factors; probabilities, counts and
    /// expectation values do not. Every other `stdgates.inc` gate follows the
    /// specification. That Polypus reads Qiskit's `qasm3.dumps` output as
    /// Qiskit does is tested for the Qiskit versions the test suite pins, not
    /// guaranteed in general.
    ///
    /// ```python
    /// qc = polypus.Circuit.from_qasm3(qiskit.qasm3.dumps(qiskit_circuit))
    /// qc.param_names          # Qiskit's (mangled) input names, in order
    /// ```
    #[staticmethod]
    fn from_qasm3(py: Python<'_>, source: &str) -> PyResult<Self> {
        // Pure Rust, bounded by the importer's budgets but not instant on a
        // large program: do not hold the GIL (docs/ENGINEERING.md §3).
        let inner = py
            .detach(|| ParameterizedCircuit::from_qasm3(source))
            .map_err(to_py_err)?;
        Ok(Circuit { inner })
    }

    /// The name of each free parameter, in index order (`num_params` names).
    ///
    /// Parameters imported from OpenQASM 3 keep their `input` names; every
    /// other one is `theta_<index>` (or, if that is taken, the first free
    /// `theta_<index>_<k>`), including indices no gate uses. The names belong
    /// to the circuit: they survive copies and the OpenQASM 3 round trip, and
    /// `to_qasm3` writes them as the program's inputs.
    #[getter]
    fn param_names(&self) -> Vec<String> {
        self.inner.param_names()
    }

    /// Number of qubits in the quantum register.
    #[getter]
    fn num_qubits(&self) -> usize {
        self.inner.num_qubits()
    }

    /// Number of free (trainable) parameters.
    #[getter]
    fn num_params(&self) -> usize {
        self.inner.num_params()
    }

    /// Size of the implicit classical register: the bits the measurements
    /// need (`max(cbit) + 1`, `num_qubits` with `measure_all`, 0 without
    /// measurements).
    #[getter]
    fn num_clbits(&self) -> usize {
        self.inner.num_clbits()
    }

    /// Width of the classical register the exports write and a measured
    /// circuit's counts are keyed at: the bits an imported program declares,
    /// or `num_clbits` if that is wider or nothing was declared (contract C-3).
    #[getter]
    fn clbits_width(&self) -> usize {
        self.inner.clbits_width()
    }

    // ── Single-qubit gates ───────────────────────────────────────────────

    fn h(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::H(qubit))
    }

    fn x(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::X(qubit))
    }

    fn y(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Y(qubit))
    }

    fn z(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Z(qubit))
    }

    fn s(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::S(qubit))
    }

    fn t(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::T(qubit))
    }

    fn sdg(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Sdg(qubit))
    }

    fn tdg(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Tdg(qubit))
    }

    /// Identity gate `id`: no effect on the state, but kept as an instruction
    /// (it counts towards gate count and depth, as in Qiskit).
    fn id(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Id(qubit))
    }

    fn rx(
        mut slf: PyRefMut<'_, Self>,
        qubit: usize,
        theta: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        push(slf, GateInstruction::Rx { qubit, theta })
    }

    fn ry(
        mut slf: PyRefMut<'_, Self>,
        qubit: usize,
        theta: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        push(slf, GateInstruction::Ry { qubit, theta })
    }

    fn rz(
        mut slf: PyRefMut<'_, Self>,
        qubit: usize,
        theta: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        push(slf, GateInstruction::Rz { qubit, theta })
    }

    /// Generic single-qubit gate `u3(theta, phi, lam)`.
    fn u(
        mut slf: PyRefMut<'_, Self>,
        qubit: usize,
        theta: AngleArg,
        phi: AngleArg,
        lam: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        let phi = slf.angle(phi)?;
        let lam = slf.angle(lam)?;
        push(
            slf,
            GateInstruction::U {
                qubit,
                theta,
                phi,
                lam,
            },
        )
    }

    // ── Two-qubit gates ──────────────────────────────────────────────────

    fn cx(slf: PyRefMut<'_, Self>, control: usize, target: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Cx(control, target))
    }

    fn cz(slf: PyRefMut<'_, Self>, control: usize, target: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Cz(control, target))
    }

    /// SWAP: exchange the states of qubits `q0` and `q1`.
    fn swap(slf: PyRefMut<'_, Self>, q0: usize, q1: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Swap(q0, q1))
    }

    fn rzz(
        mut slf: PyRefMut<'_, Self>,
        q0: usize,
        q1: usize,
        theta: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        push(slf, GateInstruction::Rzz { q0, q1, theta })
    }

    fn rxx(
        mut slf: PyRefMut<'_, Self>,
        q0: usize,
        q1: usize,
        theta: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        push(slf, GateInstruction::Rxx { q0, q1, theta })
    }

    /// Controlled phase gate `cp(theta)` on `(q0, q1)`.
    fn cp(
        mut slf: PyRefMut<'_, Self>,
        q0: usize,
        q1: usize,
        theta: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        push(slf, GateInstruction::Cp { q0, q1, theta })
    }

    // ── The rest of qelib1.inc ───────────────────────────────────────────

    /// √X gate `sx`.
    fn sx(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Sx(qubit))
    }

    /// √X† gate `sxdg`.
    fn sxdg(slf: PyRefMut<'_, Self>, qubit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Sxdg(qubit))
    }

    /// Controlled-Y `cy(control, target)`.
    fn cy(slf: PyRefMut<'_, Self>, control: usize, target: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Cy(control, target))
    }

    /// Controlled-Hadamard `ch(control, target)`.
    fn ch(slf: PyRefMut<'_, Self>, control: usize, target: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Ch(control, target))
    }

    /// Controlled-√X `csx(control, target)`.
    fn csx(slf: PyRefMut<'_, Self>, control: usize, target: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Csx(control, target))
    }

    /// Toffoli `ccx(control0, control1, target)`.
    fn ccx(
        slf: PyRefMut<'_, Self>,
        control0: usize,
        control1: usize,
        target: usize,
    ) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Ccx(control0, control1, target))
    }

    /// Fredkin `cswap(control, target0, target1)`.
    fn cswap(
        slf: PyRefMut<'_, Self>,
        control: usize,
        target0: usize,
        target1: usize,
    ) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Cswap(control, target0, target1))
    }

    /// Controlled X-rotation `crx(control, target, theta)`.
    fn crx(
        mut slf: PyRefMut<'_, Self>,
        control: usize,
        target: usize,
        theta: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        push(
            slf,
            GateInstruction::Crx {
                control,
                target,
                theta,
            },
        )
    }

    /// Controlled Y-rotation `cry(control, target, theta)`.
    fn cry(
        mut slf: PyRefMut<'_, Self>,
        control: usize,
        target: usize,
        theta: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        push(
            slf,
            GateInstruction::Cry {
                control,
                target,
                theta,
            },
        )
    }

    /// Controlled Z-rotation `crz(control, target, theta)`.
    fn crz(
        mut slf: PyRefMut<'_, Self>,
        control: usize,
        target: usize,
        theta: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        push(
            slf,
            GateInstruction::Crz {
                control,
                target,
                theta,
            },
        )
    }

    /// Controlled phase in its `cu1` spelling, `cu1(q0, q1, theta)`: the same
    /// operator as `cp`, exported as `cu1`.
    fn cu1(
        mut slf: PyRefMut<'_, Self>,
        q0: usize,
        q1: usize,
        theta: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        push(slf, GateInstruction::Cu1 { q0, q1, theta })
    }

    /// Controlled `u3`: `cu3(control, target, theta, phi, lam)`.
    fn cu3(
        mut slf: PyRefMut<'_, Self>,
        control: usize,
        target: usize,
        theta: AngleArg,
        phi: AngleArg,
        lam: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        let phi = slf.angle(phi)?;
        let lam = slf.angle(lam)?;
        push(
            slf,
            GateInstruction::Cu3 {
                control,
                target,
                theta,
                phi,
                lam,
            },
        )
    }

    /// Controlled `u` with phase `gamma` on the controlled branch (Qiskit's
    /// `cu`): `cu(control, target, theta, phi, lam, gamma)`.
    fn cu(
        mut slf: PyRefMut<'_, Self>,
        control: usize,
        target: usize,
        theta: AngleArg,
        phi: AngleArg,
        lam: AngleArg,
        gamma: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let theta = slf.angle(theta)?;
        let phi = slf.angle(phi)?;
        let lam = slf.angle(lam)?;
        let gamma = slf.angle(gamma)?;
        push(
            slf,
            GateInstruction::Cu {
                control,
                target,
                theta,
                phi,
                lam,
                gamma,
            },
        )
    }

    /// Phase gate `p(qubit, lam)`.
    fn p(mut slf: PyRefMut<'_, Self>, qubit: usize, lam: AngleArg) -> PyResult<PyRefMut<'_, Self>> {
        let lam = slf.angle(lam)?;
        push(slf, GateInstruction::P { qubit, lam })
    }

    /// `u1(qubit, lam)`: the phase gate in its `u1` spelling.
    fn u1(
        mut slf: PyRefMut<'_, Self>,
        qubit: usize,
        lam: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let lam = slf.angle(lam)?;
        push(slf, GateInstruction::U1 { qubit, lam })
    }

    /// `u2(qubit, phi, lam)` (= `u3(π/2, phi, lam)`).
    fn u2(
        mut slf: PyRefMut<'_, Self>,
        qubit: usize,
        phi: AngleArg,
        lam: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let phi = slf.angle(phi)?;
        let lam = slf.angle(lam)?;
        push(slf, GateInstruction::U2 { qubit, phi, lam })
    }

    /// `u0(gamma)`: the identity ("idle for `gamma` units"), kept as an
    /// instruction like `id`.
    fn u0(
        mut slf: PyRefMut<'_, Self>,
        qubit: usize,
        gamma: AngleArg,
    ) -> PyResult<PyRefMut<'_, Self>> {
        let gamma = slf.angle(gamma)?;
        push(slf, GateInstruction::U0 { qubit, gamma })
    }

    /// Simplified Toffoli `rccx(control0, control1, target)`, up to relative
    /// phases.
    fn rccx(
        slf: PyRefMut<'_, Self>,
        control0: usize,
        control1: usize,
        target: usize,
    ) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Rccx(control0, control1, target))
    }

    /// Simplified 3-controlled Toffoli `rc3x(c0, c1, c2, target)`, up to
    /// relative phases.
    fn rc3x(
        slf: PyRefMut<'_, Self>,
        c0: usize,
        c1: usize,
        c2: usize,
        target: usize,
    ) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Rc3x(c0, c1, c2, target))
    }

    /// 3-controlled X `c3x(c0, c1, c2, target)`.
    fn c3x(
        slf: PyRefMut<'_, Self>,
        c0: usize,
        c1: usize,
        c2: usize,
        target: usize,
    ) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::C3x(c0, c1, c2, target))
    }

    /// 3-controlled √X `c3sqrtx(c0, c1, c2, target)`.
    fn c3sqrtx(
        slf: PyRefMut<'_, Self>,
        c0: usize,
        c1: usize,
        c2: usize,
        target: usize,
    ) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::C3sqrtx(c0, c1, c2, target))
    }

    /// 4-controlled X `c4x(c0, c1, c2, c3, target)`.
    fn c4x(
        slf: PyRefMut<'_, Self>,
        c0: usize,
        c1: usize,
        c2: usize,
        c3: usize,
        target: usize,
    ) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::C4x(c0, c1, c2, c3, target))
    }

    // ── Non-unitary instructions ─────────────────────────────────────────

    /// Barrier on all qubits, or on `qubits` when given.
    #[pyo3(signature = (qubits=None))]
    fn barrier(
        slf: PyRefMut<'_, Self>,
        qubits: Option<Vec<usize>>,
    ) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Barrier(qubits.unwrap_or_default()))
    }

    /// Measure `qubit` into classical bit `cbit`.
    fn measure(slf: PyRefMut<'_, Self>, qubit: usize, cbit: usize) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::Measure { qubit, cbit })
    }

    /// Measure every qubit `i` into classical bit `i`.
    fn measure_all(slf: PyRefMut<'_, Self>) -> PyResult<PyRefMut<'_, Self>> {
        push(slf, GateInstruction::MeasureAll)
    }

    // ── Composition ──────────────────────────────────────────────────────

    /// Append the instructions of `other`, placing its qubit `i` on
    /// `qubits[i]` (by default its qubit `i` on qubit `i`), and return `self`.
    ///
    /// Use it to put a template on a subregister or to run one circuit after
    /// another. Free parameters are shared by index: `Param(0)` of `other` is
    /// `Param(0)` here, so a parameter both circuits use is bound once, and the
    /// result takes the names `other` gives to parameters this circuit does not
    /// name. Classical bits are not renumbered: a measurement keeps its bit,
    /// and `measure_all` placed on a subregister measures `qubits[i]` into bit
    /// `i`. `qc.compose(qc)` appends a copy of `qc`.
    ///
    /// ```python
    /// import polypus
    /// from polypus.circuits.templates import qft
    ///
    /// qc = polypus.Circuit(3).x(0).compose(qft(2), qubits=[1, 2])
    /// assert repr(qc) == "Circuit(num_qubits=3, num_params=0, gates=5)"
    /// ```
    ///
    /// Raises `ValueError`, leaving the circuit unchanged, when `qubits` does
    /// not give one distinct qubit of this circuit per qubit of `other`, when
    /// an instruction acts on a qubit this circuit has measured, or when
    /// `other` names a parameter differently; `TypeError` when `other` is not
    /// a `Circuit`.
    #[pyo3(signature = (other, qubits = None))]
    fn compose<'py>(
        slf: &Bound<'py, Self>,
        other: &Bound<'py, Circuit>,
        qubits: Option<Vec<usize>>,
    ) -> PyResult<Bound<'py, Self>> {
        // `qc.compose(qc)` would borrow the same object twice: copy it first.
        // A circuit a call in progress holds (an argument's `__index__` that
        // composes it) raises `RuntimeError` instead of panicking.
        let copy;
        let borrowed;
        let other = if other.is(slf) {
            copy = other.try_borrow()?.inner.clone();
            &copy
        } else {
            borrowed = other.try_borrow()?;
            &borrowed.inner
        };
        let qubits = qubits.unwrap_or_else(|| (0..other.num_qubits()).collect());
        let mut this = slf.try_borrow_mut()?;
        let target = &mut this.inner;
        slf.py()
            .detach(|| target.try_compose(other, &qubits))
            .map_err(to_py_err)?;
        drop(this);
        Ok(slf.clone())
    }

    // ── Export ───────────────────────────────────────────────────────────

    /// Serialize to OpenQASM 2.0.
    ///
    /// For a parameterised circuit, pass `params` (one value per free
    /// parameter). For a fully fixed circuit, call with no arguments. A gate
    /// declared in OpenQASM 3 is written from its definition, renamed where
    /// OpenQASM 2.0 cannot take its name; one whose body uses `arcsin`,
    /// `arccos` or `arctan`, which OpenQASM 2.0 lacks, raises `ValueError`.
    #[pyo3(signature = (params=None))]
    fn to_qasm2(&self, params: Option<Vec<f64>>) -> PyResult<String> {
        self.inner
            .to_qasm2_with_params(&params.unwrap_or_default())
            .map_err(to_py_err)
    }

    /// Serialize to the **OpenQASM 3 profile with Qiskit phase conventions**
    /// (see [`from_qasm3`](Circuit::from_qasm3)).
    ///
    /// Without `params`, each free parameter is an `input float[64]` under its
    /// name ([`param_names`](Circuit::param_names)) and angles are written as
    /// the expressions they are. With `params` (one value per free parameter),
    /// the circuit is bound first and the program has no inputs.
    ///
    /// The output is canonical: importing it and exporting again gives the
    /// same text. `u` is written as the builtin `U` (with Qiskit's matrix, see
    /// the phase convention of `from_qasm3`); instructions `stdgates.inc`
    /// lacks (`rzz`, `rxx`, `sxdg`, `csx`, `cu1`, `cu3`, `u0`, `rccx`,
    /// `rc3x`, `c3x`, `c3sqrtx`, `c4x`) are calls of gates the output defines
    /// with the same matrices. Raises `ValueError` for a declared gate
    /// OpenQASM 3 cannot express (an OpenQASM 2.0 body with a barrier) or a
    /// program beyond what `from_qasm3` reads back (its size limits).
    ///
    /// ```python
    /// text = polypus.Circuit(1).rx(0, polypus.Param(0)).to_qasm3()
    /// qiskit.qasm3.loads(text)   # needs qiskit-qasm3-import
    /// ```
    #[pyo3(signature = (params=None))]
    fn to_qasm3(&self, py: Python<'_>, params: Option<Vec<f64>>) -> PyResult<String> {
        let circuit = &self.inner;
        py.detach(|| match &params {
            None => circuit.to_qasm3(),
            Some(values) => circuit.to_qasm3_with_params(values),
        })
        .map_err(to_py_err)
    }

    /// Serialize to a QIR Base Profile LLVM IR module (text `.ll`).
    ///
    /// For a parameterised circuit, pass `params` (one value per free
    /// parameter); for a fully fixed circuit, call with no arguments. Most
    /// gates map to a standard QIS intrinsic; `rzz`/`rxx`/`u3` are decomposed
    /// to the standard set and `barrier` is dropped. The output targets QIR
    /// Alliance consumers (e.g. Azure Quantum, Quantinuum).
    ///
    /// ```python
    /// qc = polypus.Circuit(2).h(0).cx(0, 1).measure_all()
    /// qir = qc.to_qir()                       # complete LLVM IR module
    /// ```
    #[pyo3(signature = (params=None))]
    fn to_qir(&self, params: Option<Vec<f64>>) -> PyResult<String> {
        self.inner
            .to_qir_with_params(&params.unwrap_or_default())
            .map_err(to_py_err)
    }

    /// Serialize to QIR LLVM bitcode (`.bc`) as Python `bytes`.
    ///
    /// Requires `llvm-as` to be available on `PATH`.
    #[pyo3(signature = (params=None))]
    fn to_qir_bitcode<'py>(
        &self,
        py: Python<'py>,
        params: Option<Vec<f64>>,
    ) -> PyResult<Bound<'py, PyBytes>> {
        let bitcode = self
            .inner
            .to_qir_bitcode_with_params(&params.unwrap_or_default())
            .map_err(to_py_err)?;
        Ok(PyBytes::new(py, &bitcode))
    }

    /// Draw the circuit, natively (no Qiskit, no plotting library).
    ///
    /// * `output` — `"text"` (default): one wire per qubit drawn with Unicode
    ///   box characters, and a bundled classical wire `c` when the circuit
    ///   measures; `"svg"`: a standalone SVG document.
    /// * `ascii` — text only: draw with plain ASCII (`-`, `|`, `+`, `*`, `pi`)
    ///   for terminals and logs without Unicode.
    /// * `fold` — text only: wrap into pages at most this many characters wide
    ///   (default 80); `None` never wraps.
    ///
    /// Angles show as the circuit holds them: a free parameter by its name
    /// ([`param_names`](Circuit::param_names)), an expression as written, a
    /// fixed value as a multiple of π when it is one. `print(qc)` shows the
    /// text drawing, and Jupyter displays the SVG one.
    ///
    /// ```python
    /// qc = polypus.Circuit(2).h(0).cx(0, 1).measure_all()
    /// print(qc.draw())
    /// open("bell.svg", "w").write(qc.draw("svg"))
    /// ```
    #[pyo3(
        signature = (output="text", *, ascii=false, fold=Some(80)),
        text_signature = "($self, output='text', *, ascii=False, fold=80)"
    )]
    fn draw(&self, output: &str, ascii: bool, fold: Option<usize>) -> PyResult<String> {
        match output {
            "text" => Ok(self.inner.draw_text(TextOptions { ascii, fold })),
            "svg" => Ok(self.inner.draw_svg()),
            other => Err(PyValueError::new_err(format!(
                "output must be \"text\" or \"svg\", got {other:?}"
            ))),
        }
    }

    fn __str__(&self) -> String {
        self.inner.draw_text(TextOptions::default())
    }

    /// The SVG drawing, which IPython/Jupyter displays for a circuit.
    fn _repr_svg_(&self) -> String {
        self.inner.draw_svg()
    }

    fn __len__(&self) -> usize {
        self.inner.gates().len()
    }

    fn __repr__(&self) -> String {
        format!(
            "Circuit(num_qubits={}, num_params={}, gates={})",
            self.inner.num_qubits(),
            self.inner.num_params(),
            self.inner.gates().len()
        )
    }
}

/// Quantum Fourier Transform on `num_qubits` qubits, as a `polypus.Circuit`.
///
/// Follows the Qiskit `QFT` convention (big-endian, trailing qubit-reversal
/// swaps). The returned circuit has no free parameters and no measurements, so
/// it composes like any hand-built circuit — keep chaining gates, add
/// `measure_all()`, or run it directly.
///
/// * `inverse` — build the inverse transform (QFT†), the exact adjoint of the
///   forward circuit with the same arguments.
/// * `swaps` — include the qubit-reversal swaps (default `True`); set
///   `False` when the surrounding circuit already handles bit order.
///
/// Raises `ValueError` above 2827 qubits: the gate count grows quadratically,
/// and 2827 is the largest QFT the OpenQASM importers read back.
///
/// ```python
/// import polypus
/// qft = polypus.circuits.templates.qft(4)
/// result = polypus.run_quantum_circuit(qft.measure_all(), shots=1024,
///                                      infrastructure="local", backend="polypus")
/// counts = result.merged_counts
/// ```
#[pyfunction]
#[pyo3(signature = (num_qubits, inverse = false, swaps = true))]
pub fn qft(py: Python<'_>, num_qubits: usize, inverse: bool, swaps: bool) -> PyResult<Circuit> {
    let inner = py
        .detach(|| polypus_circuit::templates::qft_with_options(num_qubits, inverse, swaps))
        .map_err(to_py_err)?;
    Ok(Circuit { inner })
}

/// The order-finding circuit of Shor's algorithm, as a `polypus.Circuit`:
/// measuring its counting register estimates the order `r` of `a` modulo
/// `modulus`, the smallest `r > 0` with `a**r % modulus == 1`.
///
/// With `n = modulus.bit_length()` and `t = counting_qubits` (`2n` by
/// default), the qubits are the counting register `0..t`, then `x` (`n`
/// qubits, set to 1), `b` (`n + 1` qubits) and one ancilla: `t + 2n + 2` in
/// all. The circuit is Beauregard's: Hadamards on the counting register, a
/// multiplication of `x` by `a**(2**k) % modulus` controlled by counting qubit
/// `k`, and the inverse QFT of the counting register. Read as an integer
/// (qubit 0 is the least-significant bit), the counting register concentrates
/// on the values closest to `s * 2**t / r` for `s` in `range(r)`.
///
/// The circuit has no free parameters and no measurements: measure the
/// counting register yourself. It is built without the GIL. Moduli go up to 24
/// bits (98 qubits and 3.7 million gates), the largest whose circuit the
/// OpenQASM importers read back; with the default counting register `to_qasm3`
/// exports up to 16 bits, beyond which the text passes 32 MiB. Raises
/// `ValueError` for a `modulus` below 3 or above 24 bits, an `a` that is not
/// between 1 and `modulus - 1` or shares a factor with `modulus` (that factor
/// already divides it), and a `counting_qubits` not between 1 and `2n`.
///
/// ```python
/// import polypus
/// from polypus.circuits.templates import shor_order_finding
///
/// qc = shor_order_finding(7, 15)  # 8 counting qubits, then x, b and the ancilla
/// for k in range(8):
///     qc.measure(k, k)
/// result = polypus.run_quantum_circuit(qc, shots=1024,
///                                      infrastructure="local", backend="polypus")
/// counts = result.merged_counts   # peaks at 0, 64, 128 and 192: s * 256 / 4
/// ```
#[pyfunction]
#[pyo3(signature = (a, modulus, counting_qubits = None))]
pub fn shor_order_finding(
    py: Python<'_>,
    a: u64,
    modulus: u64,
    counting_qubits: Option<usize>,
) -> PyResult<Circuit> {
    let inner = py
        .detach(|| polypus_circuit::templates::shor_order_finding(a, modulus, counting_qubits))
        .map_err(to_py_err)?;
    Ok(Circuit { inner })
}