wai-quantum 0.3.38

A deterministic quantum stack in pure Rust: byte-exact circuit simulation (statevector / stabilizer / tensor-network MPS / sparse-Pauli backends), sparse Pauli dynamics at utility scale (arbitrary angles, 1024 qubits), belief-propagation tensor networks on the hardware graph, error mitigation, qLDPC decoding, noise learning, circuit-equivalence proofs, a phasor interference-ML layer, information-theoretic limits, noisy channels and state tomography, and signed energy-accounted receipts. No QPU, no cloud, no system libraries — identical results native, in the browser, and as a WASI component at the edge.
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
//! Fault-tolerant RESOURCE ESTIMATION — `wai.quantum.resource`.
//!
//! Every serious claim about what a fault-tolerant quantum computer will do —
//! "this molecule in a month", "this key in a week", "a hundred thousand qubits
//! suffice" — is a resource estimate. It starts from a logical program (how
//! many qubits, how many T, Toffoli and rotation gates, in how many layers), then
//! adds an error-correcting code, a magic-state factory and a physical qubit.
//! It ends in two numbers: physical qubits and wall-clock time. Funders, auditors
//! and the people who build the machines all argue over those numbers. The
//! arithmetic between the inputs and the outputs is usually a spreadsheet or an
//! unpublished script, run once.
//!
//! This module makes that arithmetic a deterministic, re-runnable function. An
//! estimate is a pure function of its inputs, computed with `+ − × ÷` and
//! in-crate logarithms, so the same inputs give the same bytes on every machine.
//! It can be sealed into a signed receipt that anyone can re-run and check.
//!
//! # The model
//!
//! The planar-ISA model of arXiv:2211.07629 is implemented in full.
//!
//! **Logical layout and time.** The program is compiled by parallel-synthesis
//! sequential Pauli computation:
//! - `Q = 2·Q_alg + ⌈√(8·Q_alg)⌉ + 1` tiles;
//! - at least `C = M + R_U + R_T + T_U·D_U + 3·R_CCZ` logical steps;
//! - `R = T_U·R_U + 4·R_CCZ + R_T` T states, where a rotation costs
//!   `T_U = ⌈0.53·log₂(R_U/ε_syn) + 5.3⌉` T gates.
//!
//! **QEC code.** A code has logical error `P(d) = a·(p/p*)^((d+1)/2)` per tile per
//! step, `n(d)` physical qubits per tile and step time `τ(d)`. The distance is the
//! smallest odd `d` with `Q·C·P(d) ≤ ε_log`.
//!
//! **Factories.** A factory is a sequence of 15-to-1 distillation rounds. Each
//! round is either the space-efficient unit or the Reed–Muller-preparation unit,
//! run on physical qubits (first round only) or on a code patch of non-decreasing
//! distance. A round has acceptance `1 − 15·P_T − 356·P` and output error
//! `35·P_T³ + 7.1·P`. Each round gets the fewest copies such that, at the
//! `1%/rounds` binomial quantile, it still feeds the next round.
//!
//! The search is exhaustive. Among all factories meeting the per-state error
//! target `ε_dis/R`, it chooses the one with the smallest space-time volume
//! `n(D)·τ(D)`. It then provisions `⌈R·τ(D)/(M(D)·t)⌉` copies, where `t` is the
//! algorithm's runtime.
//!
//! **Budget.** The error budget is split evenly between logical failures,
//! distillation and synthesis. A part the program does not use (no rotations,
//! no T states) is not reserved; its share goes to the other parts.
//!
//! # It reproduces the published tables
//!
//! The model is held to the source's own worked examples.
//!
//! - **Factory and distance tables:** every distance and factory is reproduced,
//!   down to the copy counts.
//! - **Summary table, factoring and chemistry rows:** the code distance, factory
//!   count, physical-qubit count and runtime are reproduced to the printed
//!   precision. One example: 2048-bit factoring on the `(ns, 10⁻⁴)` qubit gives
//!   `d = 13`, 18 factories of 5,760 qubits, 8.72 M physical qubits and 17 h 43 min.
//!
//! The tests in this module assert each row. Doing so exposed three places where
//! the source's prose and its tables disagree; in each case the tables win.
//!
//! - **Factoring Toffoli count.** It is printed as `3.73·10¹⁰`, but every
//!   downstream number in the source (its `C`, `R`, runtime and factory count)
//!   requires `3.73·10⁹`.
//! - **Logical Reed–Muller unit.** It is described as taking 13 logical steps,
//!   but the source's factory durations (57.2 µs at `d = 13`, 128 µs on the
//!   `(ns, 10⁻³)` qubit) require 11.
//! - **Physical distillation units.** They are described as taking 46 and 23
//!   measurement times, but the source's factory counts on measurement-based
//!   qubits require 45 and 24.
//! - **Quantum-dynamics example.** Its algorithm-level counts as printed cannot
//!   yield its own `C ≈ 1.5·10⁵` and `R ≈ 2.4·10⁶`. Its rows are therefore
//!   reproduced from ISA-level counts ([`IsaCounts`]), which this module accepts
//!   directly. Its twelve factory counts pin the unprinted step count to
//!   `C ≈ 157,000`. At that count all twelve factory counts and code distances
//!   match.
//!
//! Two rows of the source cannot both be right. Factoring on the `(ns, 10⁻⁶)`
//! measurement-based qubit is one.
//! - **The per-qubit table** prints a 16,416-qubit, 23 µs factory.
//! - **The summary table** has factories taking 1.2% of 6.2 M qubits, about
//!   5,700 each.
//! - **The search here** finds a 2,640-qubit, 21.9 µs factory that meets the
//!   same target under the stated model, about a sixth of the printed volume.
//!   It matches the summary row's distance, factory count, qubits and runtime.
//!
//! The source's chemistry runtime on the `(ns, 10⁻⁴)` measurement-based qubit is
//! printed as "24 mins". Its own step count and step time give 24 *days*.
//!
//! # Honest boundaries
//!
//! - **The source's assumptions, stated as assumptions.** These include
//!   uniform, independent circuit noise; free transport of T states; and
//!   smooth T consumption.
//! - **Planar codes only.** Surface and Floquet-honeycomb patches with lattice
//!   surgery. Block (qLDPC) codes, magic-state cultivation and reaction-time-
//!   limited scheduling need models of their own.
//! - **Rounding.** The source prints its times truncated (`163.8 ms` as
//!   `163 ms`). This module reports exact values; the tests compare at the
//!   printed precision.

use crate::repro::ln;

/// Which native entangling operations a physical qubit offers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InstructionSet {
    /// Unitary two-qubit gates (CNOT/CZ) plus single-qubit measurement.
    GateBased,
    /// Joint Pauli measurements as the native entangling operation.
    Measurement,
}

/// A physical qubit, at the level the estimate needs: operation times and the
/// worst-case Clifford and T error rates.
#[derive(Clone, Debug, PartialEq)]
pub struct PhysicalQubit {
    pub name: String,
    pub instruction_set: InstructionSet,
    /// Gate time in nanoseconds (for a measurement-based qubit, the physical
    /// T-gate time).
    pub gate_ns: f64,
    /// Measurement time in nanoseconds.
    pub meas_ns: f64,
    /// Error rate of every Clifford operation, including idling and
    /// measurement.
    pub clifford_error: f64,
    /// Error rate of a physical T state.
    pub t_error: f64,
}

impl PhysicalQubit {
    fn preset(name: &str, set: InstructionSet, gate_ns: f64, meas_ns: f64, p: f64, pt: f64) -> PhysicalQubit {
        PhysicalQubit { name: name.into(), instruction_set: set, gate_ns, meas_ns, clifford_error: p, t_error: pt }
    }
    /// Gate-based, 100 µs operations, Clifford error 10⁻³ (T 10⁻⁶).
    pub fn us_e3() -> PhysicalQubit {
        Self::preset("(us, 1e-3)", InstructionSet::GateBased, 100_000.0, 100_000.0, 1e-3, 1e-6)
    }
    /// Gate-based, 100 µs operations, Clifford error 10⁻⁴ (T 10⁻⁶).
    pub fn us_e4() -> PhysicalQubit {
        Self::preset("(us, 1e-4)", InstructionSet::GateBased, 100_000.0, 100_000.0, 1e-4, 1e-6)
    }
    /// Gate-based, 50 ns gates and 100 ns measurement, error 10⁻³.
    pub fn ns_e3() -> PhysicalQubit {
        Self::preset("(ns, 1e-3)", InstructionSet::GateBased, 50.0, 100.0, 1e-3, 1e-3)
    }
    /// Gate-based, 50 ns gates and 100 ns measurement, error 10⁻⁴.
    pub fn ns_e4() -> PhysicalQubit {
        Self::preset("(ns, 1e-4)", InstructionSet::GateBased, 50.0, 100.0, 1e-4, 1e-4)
    }
    /// Measurement-based, 100 ns operations, Clifford error 10⁻⁴, T error 5%.
    pub fn meas_ns_e4() -> PhysicalQubit {
        Self::preset("(ns, 1e-4)*", InstructionSet::Measurement, 100.0, 100.0, 1e-4, 0.05)
    }
    /// Measurement-based, 100 ns operations, Clifford error 10⁻⁶, T error 1%.
    pub fn meas_ns_e6() -> PhysicalQubit {
        Self::preset("(ns, 1e-6)*", InstructionSet::Measurement, 100.0, 100.0, 1e-6, 0.01)
    }
    /// The six reference qubits, in the source's table order.
    pub fn presets() -> Vec<PhysicalQubit> {
        vec![Self::us_e3(), Self::us_e4(), Self::ns_e3(), Self::ns_e4(), Self::meas_ns_e4(), Self::meas_ns_e6()]
    }
}

/// A planar QEC code model: `P(d) = a·(p/p*)^((d+1)/2)`,
/// `n(d) = q2·d² + q1·d + q0`, `τ(d) = (g·t_gate + m·t_meas)·d`.
#[derive(Clone, Debug, PartialEq)]
pub struct QecModel {
    pub name: String,
    pub instruction_set: InstructionSet,
    /// Crossing prefactor `a`.
    pub prefactor: f64,
    /// Threshold `p*`.
    pub threshold: f64,
    /// `(q2, q1, q0)`.
    pub qubits: (u64, u64, i64),
    /// `(g, m)`: gate and measurement times per unit of distance.
    pub cycle: (f64, f64),
}

impl QecModel {
    /// Rotated surface code on gate-based qubits.
    pub fn surface_gate() -> QecModel {
        QecModel {
            name: "surface code".into(),
            instruction_set: InstructionSet::GateBased,
            prefactor: 0.03,
            threshold: 0.01,
            qubits: (2, 0, 0),
            cycle: (4.0, 2.0),
        }
    }
    /// Surface code on measurement-based qubits.
    pub fn surface_measurement() -> QecModel {
        QecModel {
            name: "surface code".into(),
            instruction_set: InstructionSet::Measurement,
            prefactor: 0.08,
            threshold: 0.0015,
            qubits: (2, 0, 0),
            cycle: (0.0, 20.0),
        }
    }
    /// Floquet honeycomb code on measurement-based qubits (arXiv:2107.02194).
    pub fn floquet() -> QecModel {
        QecModel {
            name: "floquet code".into(),
            instruction_set: InstructionSet::Measurement,
            prefactor: 0.07,
            threshold: 0.01,
            qubits: (4, 8, -8),
            cycle: (0.0, 3.0),
        }
    }
    /// The codes the source considers for a given qubit.
    pub fn for_qubit(q: &PhysicalQubit) -> Vec<QecModel> {
        match q.instruction_set {
            InstructionSet::GateBased => vec![Self::surface_gate()],
            InstructionSet::Measurement => vec![Self::surface_measurement(), Self::floquet()],
        }
    }

    /// Physical qubits per tile at distance `d`.
    pub fn tile_qubits(&self, d: u32) -> u64 {
        let d = d as i64;
        let (a, b, c) = self.qubits;
        (a as i64 * d * d + b as i64 * d + c) as u64
    }

    /// Duration of one logical step at distance `d`, in nanoseconds.
    pub fn step_ns(&self, q: &PhysicalQubit, d: u32) -> f64 {
        (self.cycle.0 * q.gate_ns + self.cycle.1 * q.meas_ns) * d as f64
    }

    /// Probability that one tile fails during one logical step.
    pub fn logical_error(&self, p: f64, d: u32) -> f64 {
        self.prefactor * powu(p / self.threshold, d.div_ceil(2))
    }
}

/// `x^k` by repeated squaring in a fixed order: the same bits everywhere.
fn powu(x: f64, mut k: u32) -> f64 {
    let (mut base, mut acc) = (x, 1.0);
    while k > 0 {
        if k & 1 == 1 {
            acc *= base;
        }
        base *= base;
        k >>= 1;
    }
    acc
}

fn log2(x: f64) -> f64 {
    ln(x) / core::f64::consts::LN_2
}

/// `⌈√x⌉` in integers.
fn ceil_sqrt(x: u64) -> u64 {
    if x == 0 {
        return 0;
    }
    // Newton from above, then fix up: exact for every u64 this module meets.
    let mut r = (x as f64).sqrt() as u64;
    while r.saturating_mul(r) < x {
        r += 1;
    }
    while r > 0 && (r - 1).saturating_mul(r - 1) >= x {
        r -= 1;
    }
    r
}

/// What a logical program needs, before layout.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LogicalCounts {
    /// Algorithm qubits.
    pub qubits: u64,
    /// Pauli measurements.
    pub measurements: u64,
    /// Arbitrary-angle single-qubit rotations.
    pub rotations: u64,
    /// Non-Clifford layers containing at least one arbitrary-angle rotation.
    pub rotation_depth: u64,
    /// T gates.
    pub t_gates: u64,
    /// Toffoli or CCZ gates.
    pub ccz: u64,
}

/// What the logical layout needs: tiles, minimum steps, T states.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct IsaCounts {
    /// Tiles `Q` (algorithm patches plus routing ancillas).
    pub tiles: u64,
    /// The fewest logical steps the program can run in, `C_min`.
    pub min_steps: u64,
    /// T states consumed, `R`.
    pub t_states: u64,
    /// T gates per synthesized rotation (0 when there are no rotations).
    pub t_per_rotation: u64,
    /// Whether rotations are synthesized (and so share the error budget).
    pub synthesizes: bool,
}

/// How the error budget is shared out.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Budget {
    pub logical: f64,
    pub distillation: f64,
    pub synthesis: f64,
}

impl Budget {
    /// Even split over the parts the program uses.
    pub fn split(total: f64, uses_t_states: bool, synthesizes: bool) -> Budget {
        let parts = 1.0 + uses_t_states as u8 as f64 + synthesizes as u8 as f64;
        let share = total / parts;
        Budget {
            logical: share,
            distillation: if uses_t_states { share } else { 0.0 },
            synthesis: if synthesizes { share } else { 0.0 },
        }
    }
}

/// Lay a logical program out (parallel-synthesis sequential Pauli computation).
pub fn layout(c: &LogicalCounts, total_budget: f64) -> IsaCounts {
    let tiles = 2 * c.qubits + ceil_sqrt(8 * c.qubits) + 1;
    let synthesizes = c.rotations > 0;
    let uses_t = synthesizes || c.t_gates > 0 || c.ccz > 0;
    let b = Budget::split(total_budget, uses_t, synthesizes);
    let t_per_rotation = if synthesizes {
        let x = 0.53 * log2(c.rotations as f64 / b.synthesis) + 5.3;
        ceil_pos(x)
    } else {
        0
    };
    let min_steps = c.measurements + c.rotations + c.t_gates + t_per_rotation * c.rotation_depth + 3 * c.ccz;
    let t_states = t_per_rotation * c.rotations + 4 * c.ccz + c.t_gates;
    IsaCounts { tiles, min_steps, t_states, t_per_rotation, synthesizes }
}

fn ceil_pos(x: f64) -> u64 {
    let t = x as u64;
    if (t as f64) < x { t + 1 } else { t }
}

/// The two 15-to-1 distillation units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnitKind {
    /// 20 tiles (12 physical qubits), 13 steps (45 measurement times).
    SpaceEfficient,
    /// 31 tiles (31 physical qubits), 11 steps (24 measurement times).
    ReedMuller,
}

impl UnitKind {
    const ALL: [UnitKind; 2] = [UnitKind::SpaceEfficient, UnitKind::ReedMuller];
    fn physical(self) -> (u64, f64) {
        match self {
            UnitKind::SpaceEfficient => (12, 45.0),
            UnitKind::ReedMuller => (31, 24.0),
        }
    }
    fn logical(self) -> (u64, u64) {
        match self {
            UnitKind::SpaceEfficient => (20, 13),
            UnitKind::ReedMuller => (31, 11),
        }
    }
}

/// One distillation round of a factory.
#[derive(Clone, Debug, PartialEq)]
pub struct Round {
    pub kind: UnitKind,
    /// Code distance; `1` means the round runs on bare physical qubits.
    pub distance: u32,
    /// Copies of the unit run in parallel.
    pub copies: u64,
    /// Physical qubits of one copy.
    pub unit_qubits: u64,
    /// Duration of the round, nanoseconds.
    pub duration_ns: f64,
    /// Probability that one copy is rejected.
    pub failure: f64,
    /// Error rate of the T states this round outputs.
    pub output_error: f64,
}

/// A T-state factory.
#[derive(Clone, Debug, PartialEq)]
pub struct Factory {
    pub rounds: Vec<Round>,
    /// Physical qubits: the largest round (rounds run one after another).
    pub qubits: u64,
    pub duration_ns: f64,
    pub output_error: f64,
    /// T states output in at least 99% of runs.
    pub outputs: u64,
}

/// Smallest `k` with `P(X ≤ k) ≥ alpha`, `X ~ Binomial(n, s)`. Weights are
/// grown outward from the mode in a fixed order, so the answer is the same
/// bits everywhere, and no factorial or power overflows.
fn binomial_quantile(n: u64, s: f64, alpha: f64) -> u64 {
    if s >= 1.0 {
        return n;
    }
    if s <= 0.0 {
        return 0;
    }
    let q = 1.0 - s;
    let mode = (((n + 1) as f64) * s) as u64;
    let mode = mode.min(n);
    // w[i - lo] ∝ P(X = i) for i in lo..=hi.
    let mut down = Vec::new();
    let mut w = 1.0;
    let mut i = mode;
    while i > 0 {
        w *= (i as f64) / ((n - i + 1) as f64) * (q / s);
        if w < 1e-40 {
            break;
        }
        i -= 1;
        down.push(w);
    }
    let lo = mode - down.len() as u64;
    let mut up = Vec::new();
    let mut w = 1.0;
    let mut i = mode;
    while i < n {
        w *= ((n - i) as f64) / ((i + 1) as f64) * (s / q);
        if w < 1e-40 {
            break;
        }
        i += 1;
        up.push(w);
    }
    let weights: Vec<f64> = down.iter().rev().copied().chain(core::iter::once(1.0)).chain(up.iter().copied()).collect();
    let total: f64 = weights.iter().sum();
    let mut cum = 0.0;
    for (j, w) in weights.iter().enumerate() {
        cum += w;
        if cum >= alpha * total {
            return lo + j as u64;
        }
    }
    lo + weights.len() as u64 - 1
}

/// Fewest copies of a unit (one output, success `s`) such that at the
/// `alpha` quantile at least `needed` outputs survive.
fn copies_for(needed: u64, s: f64, alpha: f64) -> Option<u64> {
    let ok = |n: u64| binomial_quantile(n, s, alpha) >= needed;
    let mut n = needed.max(1);
    while !ok(n) {
        n *= 2;
        if n >= 1_000_000_000 {
            return None;
        }
    }
    let (mut lo, mut hi) = (n / 2, n);
    while lo < hi {
        let mid = lo + (hi - lo) / 2;
        if ok(mid) { hi = mid } else { lo = mid + 1 }
    }
    Some(hi)
}

/// Limits for the exhaustive factory search.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SearchLimits {
    pub max_distance: u32,
    pub max_rounds: usize,
}

impl Default for SearchLimits {
    fn default() -> Self {
        SearchLimits { max_distance: 51, max_rounds: 3 }
    }
}

/// Build the factory for a fixed sequence of `(unit, distance)` rounds:
/// propagate error rates forward, then size copies backward. Returns `None`
/// for an invalid sequence, one that misses `target`, or one that cannot beat
/// `bound` in space-time volume even with a single copy per round.
fn build_factory(
    seq: &[(UnitKind, u32)],
    qubit: &PhysicalQubit,
    qec: &QecModel,
    target: f64,
    bound: f64,
) -> Option<Factory> {
    let alpha = 0.01 / seq.len() as f64;
    let mut input = qubit.t_error;
    let mut rounds = Vec::with_capacity(seq.len());
    for &(kind, d) in seq {
        let (clifford, unit_qubits, duration_ns) = if d == 1 {
            let (nq, steps) = kind.physical();
            (qubit.clifford_error, nq, steps * qubit.meas_ns)
        } else {
            let (tiles, steps) = kind.logical();
            (
                qec.logical_error(qubit.clifford_error, d),
                tiles * qec.tile_qubits(d),
                steps as f64 * qec.step_ns(qubit, d),
            )
        };
        let failure = 15.0 * input + 356.0 * clifford;
        if failure <= 0.0 || failure >= 1.0 {
            return None;
        }
        let output_error = 35.0 * input * input * input + 7.1 * clifford;
        if output_error > input {
            return None;
        }
        rounds.push(Round { kind, distance: d, copies: 1, unit_qubits, duration_ns, failure, output_error });
        input = output_error;
    }
    if input > target {
        return None;
    }
    let floor_qubits = rounds.iter().map(|r| r.unit_qubits).max().unwrap_or(0);
    let duration_ns: f64 = rounds.iter().map(|r| r.duration_ns).sum();
    if floor_qubits as f64 * duration_ns > bound {
        return None;
    }
    let mut needed = 1;
    for r in rounds.iter_mut().rev() {
        r.copies = copies_for(needed, 1.0 - r.failure, alpha)?;
        needed = 15 * r.copies;
    }
    let qubits = rounds.iter().map(|r| r.copies * r.unit_qubits).max().unwrap_or(0);
    Some(Factory { rounds, qubits, duration_ns, output_error: input, outputs: 1 })
}

/// The factory with the smallest space-time volume whose T states meet
/// `target`, or `None` if no factory within `limits` does.
pub fn find_factory(qubit: &PhysicalQubit, qec: &QecModel, target: f64, limits: SearchLimits) -> Option<Factory> {
    let mut distances: Vec<u32> = vec![1];
    distances.extend((3..=limits.max_distance).step_by(2));
    let mut best: Option<(f64, Factory)> = None;
    let mut seq: Vec<(UnitKind, u32)> = Vec::with_capacity(limits.max_rounds);
    for rounds in 1..=limits.max_rounds {
        search(&mut seq, rounds, &distances, qubit, qec, target, &mut best);
    }
    best.map(|(_, f)| f)
}

fn search(
    seq: &mut Vec<(UnitKind, u32)>,
    rounds: usize,
    distances: &[u32],
    qubit: &PhysicalQubit,
    qec: &QecModel,
    target: f64,
    best: &mut Option<(f64, Factory)>,
) {
    if seq.len() == rounds {
        let bound = best.as_ref().map_or(f64::INFINITY, |(v, _)| *v);
        let Some(f) = build_factory(seq, qubit, qec, target, bound) else { return };
        let volume = f.qubits as f64 * f.duration_ns;
        let better = match best {
            None => true,
            Some((v, b)) => volume < *v || (volume == *v && f.qubits < b.qubits),
        };
        if better {
            *best = Some((volume, f));
        }
        return;
    }
    let floor = seq.last().map_or(1, |&(_, d)| d.max(3));
    for &d in distances {
        // Physical rounds only first; distances never shrink.
        if (d == 1 && !seq.is_empty()) || (d != 1 && d < floor) {
            continue;
        }
        for kind in UnitKind::ALL {
            seq.push((kind, d));
            search(seq, rounds, distances, qubit, qec, target, best);
            seq.pop();
        }
    }
}

/// How fast to run: at the minimum step count, or slowed by a factor to
/// trade factories for time.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EstimateConfig {
    pub error_budget: f64,
    /// Run in `slowdown × C_min` logical steps (`1` = as fast as possible).
    pub slowdown: u64,
    pub limits: SearchLimits,
}

impl EstimateConfig {
    pub fn new(error_budget: f64) -> EstimateConfig {
        EstimateConfig { error_budget, slowdown: 1, limits: SearchLimits::default() }
    }
}

/// A complete physical estimate.
#[derive(Clone, Debug, PartialEq)]
pub struct Estimate {
    pub qubit: String,
    pub code: String,
    pub isa: IsaCounts,
    pub budget: Budget,
    /// Code distance of the algorithm's tiles.
    pub distance: u32,
    pub tile_qubits: u64,
    pub step_ns: f64,
    /// Logical steps actually run.
    pub steps: u64,
    pub runtime_ns: f64,
    /// Per-tile, per-step logical error at the chosen distance.
    pub logical_error: f64,
    /// Per-state error the T states must meet.
    pub t_target: f64,
    pub factory: Option<Factory>,
    pub factories: u64,
    pub algorithm_qubits: u64,
    pub factory_qubits: u64,
    pub physical_qubits: u64,
}

impl Estimate {
    /// Share of physical qubits spent on T factories.
    pub fn factory_fraction(&self) -> f64 {
        self.factory_qubits as f64 / self.physical_qubits as f64
    }

    /// Space-time volume: physical qubits × runtime (qubit-nanoseconds).
    pub fn volume(&self) -> f64 {
        self.physical_qubits as f64 * self.runtime_ns
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EstimateError {
    /// The physical error rate is at or above the code's threshold.
    AboveThreshold,
    /// No odd distance up to the limit meets the logical budget.
    DistanceExceeded,
    /// No factory within the search limits meets the T-state target.
    NoFactory,
    /// An empty program, a zero budget or a zero slowdown.
    Invalid,
    /// The code and the qubit use different instruction sets.
    Mismatch,
    /// A sealing meter returned without running the estimate.
    NotRun,
}

/// Estimate a logical program on a qubit and code.
pub fn estimate(c: &LogicalCounts, qubit: &PhysicalQubit, qec: &QecModel, cfg: &EstimateConfig) -> Result<Estimate, EstimateError> {
    if c.qubits == 0 || cfg.error_budget.is_nan() || cfg.error_budget <= 0.0 {
        return Err(EstimateError::Invalid);
    }
    estimate_isa(&layout(c, cfg.error_budget), qubit, qec, cfg)
}

/// Estimate from ISA-level counts directly.
pub fn estimate_isa(isa: &IsaCounts, qubit: &PhysicalQubit, qec: &QecModel, cfg: &EstimateConfig) -> Result<Estimate, EstimateError> {
    if isa.tiles == 0 || isa.min_steps == 0 || cfg.slowdown == 0 || !(cfg.error_budget > 0.0 && cfg.error_budget < 1.0) {
        return Err(EstimateError::Invalid);
    }
    if qec.instruction_set != qubit.instruction_set {
        return Err(EstimateError::Mismatch);
    }
    if qubit.clifford_error >= qec.threshold {
        return Err(EstimateError::AboveThreshold);
    }
    let budget = Budget::split(cfg.error_budget, isa.t_states > 0, isa.synthesizes);
    let t_target = if isa.t_states > 0 { budget.distillation / isa.t_states as f64 } else { 0.0 };
    let factory = if isa.t_states == 0 {
        None
    } else if t_target >= qubit.t_error {
        // Raw T states already meet the target: no distillation.
        None
    } else {
        Some(find_factory(qubit, qec, t_target, cfg.limits).ok_or(EstimateError::NoFactory)?)
    };
    let mut steps = isa.min_steps.saturating_mul(cfg.slowdown);
    loop {
        let distance = distance_for(qec, qubit, isa.tiles, steps, budget.logical, cfg.limits.max_distance)?;
        let step_ns = qec.step_ns(qubit, distance);
        let runtime_ns = step_ns * steps as f64;
        // The program must outlast one factory run.
        if let Some(f) = &factory
            && runtime_ns < f.duration_ns
        {
            let need = ceil_pos(f.duration_ns / step_ns);
            if need > steps {
                steps = need;
                continue;
            }
        }
        let (factories, factory_qubits) = match &factory {
            Some(f) => {
                let n = ceil_pos(isa.t_states as f64 * f.duration_ns / (f.outputs as f64 * runtime_ns));
                (n, n * f.qubits)
            }
            None => (0, 0),
        };
        let tile_qubits = qec.tile_qubits(distance);
        let algorithm_qubits = isa.tiles * tile_qubits;
        return Ok(Estimate {
            qubit: qubit.name.clone(),
            code: qec.name.clone(),
            isa: *isa,
            budget,
            distance,
            tile_qubits,
            step_ns,
            steps,
            runtime_ns,
            logical_error: qec.logical_error(qubit.clifford_error, distance),
            t_target,
            factory,
            factories,
            algorithm_qubits,
            factory_qubits,
            physical_qubits: algorithm_qubits + factory_qubits,
        });
    }
}

/// Smallest odd distance with `tiles · steps · P(d) ≤ budget`.
fn distance_for(qec: &QecModel, qubit: &PhysicalQubit, tiles: u64, steps: u64, budget: f64, max: u32) -> Result<u32, EstimateError> {
    let volume = tiles as f64 * steps as f64;
    let mut d = 1;
    while d <= max {
        if volume * qec.logical_error(qubit.clifford_error, d) <= budget {
            return Ok(d);
        }
        d += 2;
    }
    Err(EstimateError::DistanceExceeded)
}

/// The cheapest estimate over every code the qubit supports, by space-time
/// volume (physical qubits × runtime).
pub fn estimate_best(c: &LogicalCounts, qubit: &PhysicalQubit, cfg: &EstimateConfig) -> Result<Estimate, EstimateError> {
    let isa = layout(c, cfg.error_budget);
    estimate_best_isa(&isa, qubit, cfg)
}

/// [`estimate_best`] from ISA-level counts.
pub fn estimate_best_isa(isa: &IsaCounts, qubit: &PhysicalQubit, cfg: &EstimateConfig) -> Result<Estimate, EstimateError> {
    let mut best: Option<Estimate> = None;
    let mut last_err = EstimateError::Mismatch;
    for qec in QecModel::for_qubit(qubit) {
        match estimate_isa(isa, qubit, &qec, cfg) {
            Ok(e) => {
                if best.as_ref().is_none_or(|b| e.volume() < b.volume()) {
                    best = Some(e);
                }
            }
            Err(e) => last_err = e,
        }
    }
    best.ok_or(last_err)
}

/// The space-time frontier: estimates at slowdowns `1, 2, 4, …` up to
/// `max_slowdown`, keeping only those that use fewer qubits than every faster
/// one.
pub fn frontier(isa: &IsaCounts, qubit: &PhysicalQubit, qec: &QecModel, cfg: &EstimateConfig, max_slowdown: u64) -> Vec<Estimate> {
    let mut out: Vec<Estimate> = Vec::new();
    let mut s = 1;
    while s <= max_slowdown {
        let c = EstimateConfig { slowdown: s, ..*cfg };
        if let Ok(e) = estimate_isa(isa, qubit, qec, &c)
            && out.last().is_none_or(|p| e.physical_qubits < p.physical_qubits)
        {
            out.push(e);
        }
        s *= 2;
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    const US: f64 = 1e3;
    const MS: f64 = 1e6;
    const S: f64 = 1e9;
    const HOUR: f64 = 3600.0 * S;
    const DAY: f64 = 24.0 * HOUR;

    /// The chemistry program (double-factorized qubitization), ε = 0.01.
    fn chemistry() -> LogicalCounts {
        LogicalCounts {
            qubits: 1318,
            measurements: 1_370_000_000,
            rotations: 206_000_000,
            rotation_depth: 205_000_000,
            t_gates: 55_300_000,
            ccz: 135_000_000_000,
        }
    }

    /// 2048-bit factoring, ε = 1/3, with the Toffoli count every downstream
    /// number of the source requires (3.73·10⁹; it prints 3.73·10¹⁰).
    fn factoring() -> LogicalCounts {
        LogicalCounts {
            qubits: 12_581,
            measurements: 1_080_000_000,
            rotations: 12,
            rotation_depth: 12,
            t_gates: 12,
            ccz: 3_730_000_000,
        }
    }

    /// Whether `x` matches a value printed to `figures` significant figures.
    /// The source rounds some figures and truncates others, so anything within
    /// one unit of the last printed digit matches.
    fn printed(x: f64, shown: f64, figures: i32) -> bool {
        let unit = 10f64.powi(shown.abs().log10().floor() as i32 - figures + 1);
        (x - shown).abs() < unit
    }

    #[test]
    fn integer_helpers_are_exact() {
        for x in [1u64, 2, 3, 4, 8, 9, 10, 100_648, 10_544, u32::MAX as u64] {
            let r = ceil_sqrt(x);
            assert!(r * r >= x && (r - 1) * (r - 1) < x, "{x}");
        }
        assert_eq!(powu(0.1, 0), 1.0);
        assert_eq!(powu(2.0, 10), 1024.0);
        assert!((powu(0.01, 5) - 1e-10).abs() < 1e-24);
        // A Binomial(16, 1 − 0.002568) has its 0.5% quantile at 15, and a
        // Binomial(15, ·) does not reach 15.
        assert_eq!(binomial_quantile(16, 1.0 - 0.002568, 0.005), 15);
        assert_eq!(binomial_quantile(15, 1.0 - 0.002568, 0.005), 14);
        assert_eq!(copies_for(15, 1.0 - 0.002568, 0.005), Some(16));
    }

    #[test]
    fn the_layout_reproduces_the_isa_counts() {
        let c = layout(&chemistry(), 0.01);
        assert_eq!(c.tiles, 2740);
        assert_eq!(c.t_per_rotation, 25);
        assert!(printed(c.min_steps as f64, 4.12e11, 3)); // printed 4.10e11, from unrounded inputs
        assert!((c.t_states as f64 / 5.44e11 - 1.0).abs() < 0.005); // inputs printed to 3 s.f.
        let f = layout(&factoring(), 1.0 / 3.0);
        assert_eq!(f.tiles, 25_481);
        assert_eq!(f.t_per_rotation, 9);
        assert!(printed(f.min_steps as f64, 1.23e10, 3));
        assert!(printed(f.t_states as f64, 1.49e10, 3));
    }

    #[test]
    fn the_worked_factories_are_reproduced_exactly() {
        let q = PhysicalQubit::ns_e4();
        let s = QecModel::surface_gate();
        // One round, d = 9: 3240 qubits, 46.8 µs, 5.6·10⁻¹¹.
        let f = build_factory(&[(UnitKind::SpaceEfficient, 9)], &q, &s, 1.0, f64::INFINITY).unwrap();
        assert_eq!((f.qubits, f.rounds[0].copies), (3240, 1));
        assert!((f.duration_ns - 46.8 * US).abs() < 1e-6);
        assert!(printed(f.output_error, 5.6e-11, 2));
        // 16 × (d = 3) → 1 × (d = 11): 5760 qubits, 72.8 µs, 5.51·10⁻¹³.
        let f = build_factory(&[(UnitKind::SpaceEfficient, 3), (UnitKind::SpaceEfficient, 11)], &q, &s, 1.0, f64::INFINITY).unwrap();
        assert_eq!(f.rounds.iter().map(|r| r.copies).collect::<Vec<_>>(), vec![16, 1]);
        assert_eq!(f.qubits, 5760);
        assert!((f.duration_ns - 72.8 * US).abs() < 1e-6);
        assert!(printed(f.output_error, 5.51e-13, 3));
        // 16 × (d = 5) → Reed–Muller (d = 13): 16000 qubits, 83.2 µs, 2.13·10⁻¹⁵.
        let f = build_factory(&[(UnitKind::SpaceEfficient, 5), (UnitKind::ReedMuller, 13)], &q, &s, 1.0, f64::INFINITY).unwrap();
        assert_eq!(f.qubits, 16_000);
        assert_eq!(f.rounds[1].unit_qubits, 10_478);
        assert!((f.duration_ns - 83.2 * US).abs() < 1e-6);
        assert!(printed(f.output_error, 2.13e-15, 3));
    }

    /// Distance and factory for factoring on all six qubits (the source's
    /// per-qubit table): `P(d) ≤ 3.5·10⁻¹⁶`, `P_T ≤ 7.4·10⁻¹²`.
    #[test]
    fn the_per_qubit_factoring_table_is_reproduced() {
        let isa = layout(&factoring(), 1.0 / 3.0);
        let cfg = EstimateConfig::new(1.0 / 3.0);
        // (code, d, n(d), τ(d) truncated, n(D), τ(D) truncated)
        let rows: [(&str, u32, u64, f64, u64, f64); 6] = [
            ("surface code", 27, 1458, 16.0 * MS, 17_640, 163.0 * MS),
            ("surface code", 13, 338, 7.0 * MS, 4840, 85.0 * MS),
            ("surface code", 27, 1458, 10.0 * US, 33_320, 128.0 * US),
            ("surface code", 13, 338, 5.0 * US, 5760, 72.0 * US),
            ("floquet code", 15, 1012, 4.0 * US, 21_840, 52.0 * US),
            ("floquet code", 7, 244, 2.0 * US, 16_416, 23.0 * US),
        ];
        let unit = |x: f64| if x >= MS { MS } else { US };
        for (i, (q, row)) in PhysicalQubit::presets().iter().zip(rows).enumerate() {
            let e = estimate_best_isa(&isa, q, &cfg).unwrap();
            let f = e.factory.as_ref().unwrap();
            if i == 5 {
                // The printed factory is not the minimum of the stated model:
                // the one found here meets the same target in a sixth of the
                // space-time volume (see the module docs).
                assert_eq!((e.code.as_str(), e.distance, e.tile_qubits), (row.0, row.1, row.2));
                assert!(f.output_error <= e.t_target);
                assert!(f.qubits as f64 * f.duration_ns < row.4 as f64 * row.5 / 5.0);
                continue;
            }
            let got = (
                e.code.as_str(),
                e.distance,
                e.tile_qubits,
                (e.step_ns / unit(row.3)).floor() * unit(row.3),
                f.qubits,
                (f.duration_ns / unit(row.5)).floor() * unit(row.5),
            );
            assert_eq!(got, row, "{}: {:?}", q.name, f.rounds);
        }
    }

    /// The summary rows for factoring and chemistry: distance and factory
    /// count exactly; physical qubits and runtime to the printed figures.
    #[test]
    fn the_summary_rows_are_reproduced() {
        const YEAR: f64 = 365.25 * DAY;
        const MONTH: f64 = YEAR / 12.0;
        // (d, factories, qubits in millions, runtime as printed, its unit)
        let factoring_rows: [(u32, u64, f64, f64, f64); 6] = [
            (27, 13, 37.0, 6.2, YEAR),
            (13, 14, 8.6, 3.0, YEAR),
            (27, 15, 37.0, 1.5, DAY),
            (13, 18, 8.7, 18.0, HOUR),
            (15, 15, 26.0, 15.0, HOUR),
            (7, 13, 6.2, 7.1, HOUR),
        ];
        let chemistry_rows: [(u32, u64, f64, f64, f64); 6] = [
            (33, 15, 6.4, 260.0, YEAR),
            (17, 14, 1.6, 130.0, YEAR),
            (33, 17, 6.9, 2.0, MONTH),
            (17, 17, 1.9, 1.0, MONTH),
            (17, 19, 4.5, 24.0, DAY), // printed "24 mins"; its own C and τ(d) give days
            (9, 19, 1.3, 12.0, DAY),
        ];
        for (prog, eps, rows) in [(factoring(), 1.0 / 3.0, factoring_rows), (chemistry(), 0.01, chemistry_rows)] {
            let cfg = EstimateConfig::new(eps);
            for (q, (d, nf, mq, t, unit)) in PhysicalQubit::presets().iter().zip(rows) {
                let e = estimate_best(&prog, q, &cfg).unwrap();
                assert_eq!((e.distance, e.factories), (d, nf), "{} {:?}", q.name, e.factory);
                assert!(printed(e.physical_qubits as f64 / 1e6, mq, 2), "{}: {}", q.name, e.physical_qubits);
                assert!(printed(e.runtime_ns / unit, t, 2), "{}: {} vs {t}", q.name, e.runtime_ns / unit);
            }
        }
    }

    #[test]
    fn the_factoring_example_matches_to_the_minute() {
        let e = estimate(&factoring(), &PhysicalQubit::ns_e4(), &QecModel::surface_gate(), &EstimateConfig::new(1.0 / 3.0)).unwrap();
        assert_eq!(e.distance, 13);
        assert_eq!(e.factories, 18);
        assert_eq!(e.physical_qubits, 18 * 5760 + 25_481 * 338);
        let minutes = (e.runtime_ns / (60.0 * S)) as u64;
        assert_eq!((minutes / 60, minutes % 60), (17, 43));
        let f = e.factory.unwrap();
        assert_eq!(f.rounds.iter().map(|r| (r.kind, r.distance, r.copies)).collect::<Vec<_>>(),
            vec![(UnitKind::SpaceEfficient, 3, 16), (UnitKind::SpaceEfficient, 11, 1)]);
    }

    /// The dynamics rows, from ISA-level counts: `Q = 230` and `R = 2.4·10⁶` as
    /// printed, and `C = 157,000`, which the twelve printed factory counts pin
    /// down (the source prints `C` only as `1.5·10⁵`). Fast and ×10 slowed:
    /// distance, factory count and qubits.
    #[test]
    fn the_dynamics_rows_follow_from_the_isa_counts() {
        let isa = IsaCounts { tiles: 230, min_steps: 157_000, t_states: 2_400_000, t_per_rotation: 20, synthesizes: true };
        let fast: [(u32, u64, f64); 6] = [(19, 199, 3.0), (9, 199, 0.68), (19, 242, 8.2), (9, 199, 0.68), (9, 260, 5.8), (5, 224, 0.62)];
        let slow: [(u32, u64, f64); 6] = [(21, 18, 0.46), (11, 17, 0.11), (21, 22, 0.94), (11, 17, 0.11), (11, 22, 0.61), (5, 23, 0.09)];
        for (slowdown, rows) in [(1, fast), (10, slow)] {
            let cfg = EstimateConfig { slowdown, ..EstimateConfig::new(0.001) };
            for (q, (d, nf, mq)) in PhysicalQubit::presets().iter().zip(rows) {
                let e = estimate_best_isa(&isa, q, &cfg).unwrap();
                assert_eq!((e.distance, e.factories), (d, nf), "{} ×{slowdown}", q.name);
                // "0.09M" is printed to one figure, the rest to two.
                let figures = if mq < 0.1 { 1 } else { 2 };
                assert!(printed(e.physical_qubits as f64 / 1e6, mq, figures), "{} ×{slowdown}: {}", q.name, e.physical_qubits);
            }
        }
    }

    #[test]
    fn the_frontier_trades_qubits_for_time() {
        let isa = layout(&chemistry(), 0.01);
        let q = PhysicalQubit::ns_e4();
        let fr = frontier(&isa, &q, &QecModel::surface_gate(), &EstimateConfig::new(0.01), 64);
        assert!(fr.len() >= 2);
        for w in fr.windows(2) {
            assert!(w[1].physical_qubits < w[0].physical_qubits);
            assert!(w[1].runtime_ns > w[0].runtime_ns);
        }
    }

    #[test]
    fn bad_inputs_are_refused() {
        let isa = layout(&factoring(), 1.0 / 3.0);
        let mut bad = PhysicalQubit::ns_e3();
        bad.clifford_error = 0.02;
        let cfg = EstimateConfig::new(1.0 / 3.0);
        assert_eq!(estimate_isa(&isa, &bad, &QecModel::surface_gate(), &cfg), Err(EstimateError::AboveThreshold));
        assert_eq!(estimate_isa(&isa, &PhysicalQubit::ns_e3(), &QecModel::floquet(), &cfg), Err(EstimateError::Mismatch));
        assert_eq!(estimate_isa(&isa, &PhysicalQubit::ns_e3(), &QecModel::surface_gate(), &EstimateConfig { slowdown: 0, ..cfg }), Err(EstimateError::Invalid));
        assert_eq!(estimate(&LogicalCounts::default(), &PhysicalQubit::ns_e3(), &QecModel::surface_gate(), &cfg), Err(EstimateError::Invalid));
    }

    #[test]
    fn a_clifford_only_program_needs_no_factory() {
        let c = LogicalCounts { qubits: 100, measurements: 10_000, ..Default::default() };
        let e = estimate(&c, &PhysicalQubit::ns_e4(), &QecModel::surface_gate(), &EstimateConfig::new(0.01)).unwrap();
        assert!(e.factory.is_none());
        assert_eq!((e.factories, e.factory_qubits), (0, 0));
        assert_eq!(e.budget.logical, 0.01);
    }
}