CharlesCNorton commited on
Commit
f6ae2a3
·
1 Parent(s): 5142909

Add multi-axis validation, weakness tests, interval experiment

Browse files

zeno_multiaxis.py: 48-circuit experiment across qubits, angles,
schedules, DD hybrids, two-qubit. Sinusoidal schedule +1.2-4.7pp
over uniform. Adaptive N scales with angle. DD in gaps +5pp.

tests/test_weaknesses.py: W1-W6 systematic stress tests.
zeno_interval.py: inter-measurement gap sweep.

README.md CHANGED
@@ -371,13 +371,15 @@ Based on the comprehensive experimental data presented in this section, we can n
371
 
372
  | Application | Recommended Strategy | Rationale |
373
  |-------------|----------------------|-----------|
374
- | Maximum data extraction | Exponential weighting | +92% effective yield vs hard PS |
375
- | Position-sensitive | Position-aware weighting | Penalizes early flips more |
376
- | VQE/QAOA estimation | Exponential or soft k≤2 | Best balance of fidelity and yield |
377
- | Quick benchmarking | Soft k≤2 | 90%+ yield, 96%+ fidelity |
378
  | Maximum fidelity | Hard k=0 | Highest per-shot fidelity (but wasteful) |
379
 
380
- Hard post-selection is never optimal. In all eleven circuits tested across multiple experiments, at least one alternative strategy outperformed hard post-selection on effective yield while maintaining comparable fidelity. For most applications, exponential weighting with formula w = exp(-n_flips) provides the best combination of simplicity and performance: it is easy to implement, requires no calibration or fitting, and extracts 92% more effective signal than hard post-selection from the same quantum data. The only scenario where hard post-selection remains appropriate is when maximum per-shot fidelity is required regardless of throughput cost—a rare requirement in practical quantum computing where shot budgets are typically the limiting resource.
 
 
381
 
382
  ---
383
 
@@ -675,6 +677,101 @@ The X Zeno protocol loses its advantage over delay-matched controls at just 5μs
675
 
676
  Identity Zeno tells a different story. With no rotations to corrupt, the pure measurement-based freeze declines only 6 percentage points across the entire sweep — from 95.4% at gap=0 to 89.4% at gap=100μs. Even when the inter-measurement interval approaches T1, the projective measurement still partially resets the decoherence clock. The measurement mechanism is robust; the gate operations between measurements are the fragile component.
677
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
678
  ---
679
 
680
  ## Data Format
@@ -739,8 +836,8 @@ Full calibration data for all 133 qubits is embedded in `results/zeno_megabatch/
739
 
740
  - **Shots per circuit**: 2048–4096 depending on experiment
741
  - **Execution mode**: IBM Quantum Runtime Batch (parallel compilation)
742
- - **Total QPU time**: ~200 seconds across January 2026 experiments; 155 seconds for March 2026 measurement duration experiment
743
- - **Temporal window**: January experiments completed within 24 hours (single calibration epoch); measurement duration experiment conducted March 3, 2026
744
 
745
  ---
746
 
 
371
 
372
  | Application | Recommended Strategy | Rationale |
373
  |-------------|----------------------|-----------|
374
+ | Maximum data extraction | Soft k≤2 | 90%+ yield, 96%+ fidelity, no tuning required |
375
+ | Position-sensitive | Position-aware thresholding | Rejects pos-0 multi-flip trajectories, keeps the rest |
376
+ | VQE/QAOA estimation | Soft k≤2 | Best balance of fidelity and yield (see W5 weakness test) |
377
+ | Quick benchmarking | Soft k≤1 | 88% yield, 96.5% fidelity |
378
  | Maximum fidelity | Hard k=0 | Highest per-shot fidelity (but wasteful) |
379
 
380
+ Hard post-selection is never optimal. In all eleven circuits tested across multiple experiments, at least one alternative strategy outperformed hard post-selection on effective yield while maintaining comparable fidelity.
381
+
382
+ **Note on exponential weighting**: Earlier versions of this document recommended `w = exp(−n_flips)` as the best general strategy. Weakness test W5 showed this is suboptimal: soft k≤2 thresholding achieves 90.1% effective yield vs. 74.7% for exponential weighting on the same data. The exponential function assigns weight 0.37 to one-flip trajectories that have 96.5% fidelity — penalizing them far more than their quality warrants. Soft thresholds that accept low-flip trajectories at full weight extract more signal. Exponential weighting remains useful for composition analysis (where it eliminates the composition penalty, as shown in the Gate Composition section) but is not recommended as the default strategy for single-gate analysis.
383
 
384
  ---
385
 
 
677
 
678
  Identity Zeno tells a different story. With no rotations to corrupt, the pure measurement-based freeze declines only 6 percentage points across the entire sweep — from 95.4% at gap=0 to 89.4% at gap=100μs. Even when the inter-measurement interval approaches T1, the projective measurement still partially resets the decoherence clock. The measurement mechanism is robust; the gate operations between measurements are the fragile component.
679
 
680
+ ### Weakness Tests
681
+
682
+ **tests/weakness_tests.json** — Systematic stress-testing of six identified methodological weaknesses in the dataset's claims. Three tests run offline against existing data (zero QPU cost); three run new hardware experiments on ibm_torino (51 circuits, 4096 shots each, job d6jkidm33pjc73dm3upg, 56s QPU, March 3 2026). The test script is at `tests/test_weaknesses.py`.
683
+
684
+ **W1: Single-qubit generalization.** The original gate comparison experiments all used qubit 0, which has an unusually high measurement error rate (11.6%) compared to the chip median. To test whether the Zeno advantage generalizes, we ran identical Zeno vs. standard comparisons on 5 qubits spanning the full quality range: Q0 (T1=115μs, meas_err=11.6%), Q37 (T1=60μs, meas_err=1.0%), Q85 (T1=3.6μs, meas_err=4.6%), Q95 (T1=174μs, meas_err=2.7%), and Q131 (T1=333μs, meas_err=1.8%).
685
+
686
+ | Qubit | T1 (μs) | Meas Err | Std I | Zeno I | Std X | Zeno X | Zeno−Std I | Zeno−Std X |
687
+ |-------|---------|----------|-------|--------|-------|--------|------------|------------|
688
+ | Q0 | 115.2 | 11.6% | 90.2% | 94.7% | 89.8% | 88.6% | +4.5pp | −1.2pp |
689
+ | Q37 | 59.9 | 1.0% | 100.0% | 100.0% | 100.0% | 97.6% | −0.0pp | −2.4pp |
690
+ | Q85 | 3.6 | 4.6% | 98.2% | 98.9% | 98.6% | 96.4% | +0.7pp | −2.2pp |
691
+ | Q95 | 174.3 | 2.7% | 99.4% | 99.8% | 98.9% | 96.7% | +0.5pp | −2.1pp |
692
+ | Q131 | 332.5 | 1.8% | 99.4% | 99.7% | 99.5% | 96.9% | +0.2pp | −2.6pp |
693
+
694
+ **Result: FAIL.** Zeno improves identity gate fidelity on all qubits (+0.2 to +4.5pp), but *hurts* X gate fidelity on every qubit tested (−1.2 to −2.6pp). The original dataset's Q0 results flatter Zeno because Q0 has the highest measurement error on the chip — more errors to filter means more post-selection benefit. On low-error qubits where standard gates already achieve 99–100% fidelity, Zeno's overhead (extra Ry gates, mid-circuit measurements) introduces more errors than post-selection removes. The Zeno gate improvement claim is qubit-dependent and should not be generalized from Q0 alone.
695
+
696
+ **W2: Measurement error independence.** The excess-flip weighting scheme assumes measurement errors are independent Bernoulli events. We tested this assumption against identity Zeno data (N=32, 4096 shots) where there are no Ry rotations — any observed flips are purely from measurement backaction.
697
+
698
+ - **Transition autocorrelation**: Lag-1 autocorrelation of transition events (0→1 or 1→0) is +0.41 (t=53.8, p≈10⁻¹⁷⁸). Transitions cluster rather than occurring independently.
699
+ - **Binomial goodness-of-fit**: Chi-squared = 15,323 (p≈0). Observed 958 zero-flip shots vs. 75 expected under Binomial(32, 0.116). Measurement backaction creates long runs of correlated outcomes.
700
+ - **Monotonicity**: Fidelity decreases monotonically with flip count through k=7 (96.9% → 36.4%), but 4 violations occur at k≥8 where bin sizes are <10 shots. The monotonic regime (k=0 through k=7, covering 98.3% of all shots) validates flip-count-based weighting for practical purposes despite the independence violation.
701
+
702
+ **Result: FAIL on statistical assumptions, PASS on practical utility.** The Binomial independence model is wrong — backaction creates correlated flip runs. But flip count remains a monotonically decreasing predictor of fidelity across the range that matters (0–7 flips, 98% of data). The excess-flip weighting formula works in practice even though its theoretical justification is incorrect.
703
+
704
+ **W3: Zero-noise extrapolation comparison.** The original error mitigation comparison tested only dynamical decoupling and gate twirling. We added ZNE (zero-noise extrapolation) via unitary folding at 1×, 3×, 5×, and 7× noise levels, with Richardson extrapolation to zero noise.
705
+
706
+ | Gate | Standard | ZNE (linear) | ZNE (quadratic) | Zeno (excess-flip) | Zeno (hard PS) |
707
+ |------|----------|-------------|-----------------|-------------------|---------------|
708
+ | I | 89.8% | 89.9% | 89.6% | 94.7% | 95.6% |
709
+ | X | 89.3% | 88.9% | 88.5% | 88.6% | 94.9% |
710
+
711
+ **Result: MIXED.** ZNE provides negligible improvement on this hardware (identity: +0.1pp, X: −0.4pp over standard). The noise model may be too non-Markovian for Richardson extrapolation to help. Zeno hard PS beats ZNE on per-shot fidelity for both gates. On effective yield at 100% utilization, ZNE (89.9%) and Zeno excess-flip (88.6%) are comparable for X gate. Zeno wins on identity (94.7% vs 89.9%). Neither method dominates the other across all metrics.
712
+
713
+ **W4: VQE fidelity constancy.** The VQE bias correction formula `z_corrected = z_measured / (2f − 1)` assumes constant fidelity f across all rotation angles. We extracted per-theta hard-PS fidelity from the VQE data:
714
+
715
+ | θ/π | Hard-PS Fidelity |
716
+ |-----|-----------------|
717
+ | 0.000 | 100.0% |
718
+ | 0.125 | 89.5% |
719
+ | 0.250 | 82.8% |
720
+ | 0.375 | 67.9% |
721
+ | 0.500 | 55.6% |
722
+ | 0.625 | 36.5% |
723
+ | 0.750 | 19.6% |
724
+ | 0.875 | 4.8% |
725
+ | 1.000 | 8.0% |
726
+
727
+ **Result: FAIL.** Fidelity ranges from 4.8% to 100% — a 95pp spread. The constant-fidelity assumption is catastrophically wrong. The VQE correction formula divides by (2f−1), and when f drops below 50% the correction factor flips sign. Per-theta calibration reduces RMSE from 18.99 to 1.25 — a 93.4% improvement. The published VQE RMSE numbers (0.101 for "calibrated") used eigenstate calibration which partially mitigates this, but the bias correction discussion in the README should be updated to note that per-theta fidelity variation is extreme.
728
+
729
+ **W5: ML model vs. simple heuristics.** The README recommends exponential weighting `w = exp(−n_flips)` as the best strategy. We compared 8 strategies on x_freeze_n8 trajectory data (4096 trajectories):
730
+
731
+ | Strategy | Fidelity | Utilization | Effective Yield |
732
+ |----------|----------|-------------|-----------------|
733
+ | Hard (k=0) | 96.8% | 68.8% | 66.6% |
734
+ | Soft (k≤1) | 96.5% | 90.7% | 87.6% |
735
+ | Soft (k≤2) | 96.3% | 93.5% | 90.1% |
736
+ | exp(−k) | 96.6% | 77.3% | 74.7% |
737
+ | Excess-flip | 96.6% | 77.5% | 74.9% |
738
+ | Early-penalty | 96.6% | 79.2% | 76.5% |
739
+ | Pos0-aware | 96.4% | 92.0% | 88.7% |
740
+ | Uniform | 91.2% | 100.0% | 91.2% |
741
+
742
+ **Result: exp(−k) is suboptimal.** Soft k≤2 (90.1% yield) beats exp(−k) (74.7% yield) by 15pp. Position-aware thresholding (88.7%) also beats exp(−k). The exponential weighting penalizes 1-flip trajectories too aggressively — assigning them weight 0.37 when they have 96.5% fidelity. Soft thresholds that accept these trajectories at full weight extract far more signal. The recommended strategy table should be updated: soft k≤2 for most applications, not exponential weighting.
743
+
744
+ **W6: Computation between measurements.** The inter-measurement gap experiment showed X Zeno loses its advantage at 5μs of idle delay. But idle delay is not computation — real algorithms perform gate operations between measurements. We tested Zeno with 0, 1, 2, and 4 identity-equivalent gate pairs (Ry(ε)Ry(−ε), ε=0.01) interleaved between each measurement step:
745
+
746
+ | Work gates | Zeno (excess-flip) | Zeno (hard PS) | Depth-matched | Standard | Zeno−Standard |
747
+ |------------|-------------------|---------------|---------------|----------|--------------|
748
+ | 0 | 93.1% | 96.1% | 88.8% | 89.0% | +4.1pp |
749
+ | 1 | 91.9% | 95.4% | 88.2% | 89.0% | +2.8pp |
750
+ | 2 | 91.4% | 93.8% | 88.1% | 89.0% | +2.4pp |
751
+ | 4 | 91.8% | 95.5% | 87.8% | 89.0% | +2.7pp |
752
+
753
+ **Result: REFUTED.** The Zeno advantage survives interleaved computation. With 4 gate pairs between each measurement (32 extra gates total), Zeno still beats standard by +2.7pp and beats depth-matched by +3.9pp. The advantage decays 33% from the zero-work baseline but does not vanish. The idle-gap experiment measured decoherence during idle time, not the effect of active computation. Gate-based work between measurements preserves coherence (the gates keep the qubit driven) while idle gaps allow T1/T2 decay.
754
+
755
+ ### Multi-Axis Validation
756
+
757
+ **results/zeno_multiaxis/zeno_multiaxis.json** — 48 circuits testing Zeno dragging across qubits, rotation angles, measurement counts, measurement schedules, and idle gap mitigation. Single Batch on ibm_torino, 4096 shots each, job d6jl6lkgmsgc73bv7ia0, 55s QPU, March 3 2026. Script: `zeno_multiaxis.py`.
758
+
759
+ **Multi-qubit gate comparison (18 circuits).** Repeats the gate comparison on Q37 (1.0% meas err), Q95 (2.7%), Q131 (1.8%), replacing Q0 (11.6%). Zeno improves identity gate fidelity on 2/3 qubits (+0.1 to +1.1pp). Zeno hurts X gate fidelity on all 3 (−4.1 to −6.9pp). Confirms W1: the gate comparison advantage depends on qubit measurement error rate.
760
+
761
+ **Adaptive-N (8 circuits).** N=4 and N=8 produce identical fidelity at θ=π/8 (99.5%). At θ=π, N=16 reaches 97.9% vs 93.2% at N=8. Optimal N scales with rotation angle.
762
+
763
+ **Sinusoidal measurement schedule (6 circuits).** θ_k = θ·sin²(kπ/2N) vs uniform θ_k = kθ/N, three angles, N=8. The sinusoidal schedule produces higher soft k≤2 fidelity at every angle: +1.2pp at π/2, +2.1pp at 3π/4, +4.7pp at π.
764
+
765
+ | θ | Uniform k≤2 | Sinusoidal k≤2 | Difference |
766
+ |---------|-------------|----------------|------------|
767
+ | π/2 | 97.6% | 98.9% | +1.2pp |
768
+ | 3π/4 | 96.0% | 98.1% | +2.1pp |
769
+ | π | 92.0% | 96.7% | +4.7pp |
770
+
771
+ **Zeno-DD hybrid (4 circuits).** Hahn echo DD in 10μs inter-measurement gaps recovers +5.0pp fidelity over bare gaps for X Zeno (81.5% → 86.6%). Identity Zeno is unaffected by gaps (99.9%).
772
+
773
+ **Two-qubit (2 circuits).** Standard CNOT round-trip on Q37-Q52: 99.6%. Zeno CNOT with soft k≤2: 91.5%. Two-qubit Zeno overhead still exceeds the post-selection benefit.
774
+
775
  ---
776
 
777
  ## Data Format
 
836
 
837
  - **Shots per circuit**: 2048–4096 depending on experiment
838
  - **Execution mode**: IBM Quantum Runtime Batch (parallel compilation)
839
+ - **Total QPU time**: ~200 seconds across January 2026 experiments; 155 seconds for March 2026 measurement duration experiments; 56 seconds for weakness tests
840
+ - **Temporal window**: January experiments completed within 24 hours (single calibration epoch); measurement duration and weakness test experiments conducted March 3, 2026
841
 
842
  ---
843
 
results/zeno_multiaxis/zeno_multiaxis.json ADDED
The diff for this file is too large to render. See raw diff
 
tests/test_weaknesses.py ADDED
@@ -0,0 +1,1427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test All Six Identified Weaknesses — Single Script, Single Batch
3
+
4
+ OFFLINE (zero QPU cost):
5
+ W2: Measurement error independence assumption in excess-flip weighting
6
+ W4: VQE bias correction assumes constant fidelity across theta
7
+ W5: ML model vs simple heuristic marginal improvement
8
+
9
+ HARDWARE (one Batch submission, ~51 circuits, ~25s QPU):
10
+ W1: Single-qubit, single-backend generalization — test 5 diverse qubits
11
+ W3: Incomplete error mitigation comparison — add ZNE
12
+ W6: Practical gap — computation between measurements kills advantage
13
+ """
14
+
15
+ import json
16
+ import sys
17
+ from datetime import datetime, timezone
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ import numpy as np
21
+ from scipy.special import comb
22
+ from scipy import stats as sp_stats
23
+
24
+ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
25
+ from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
26
+ from qiskit_ibm_runtime import (
27
+ QiskitRuntimeService,
28
+ SamplerV2,
29
+ Batch,
30
+ )
31
+
32
+
33
+ DATA_DIR = Path("D:/qiskit-zenodragging")
34
+ RESULTS_DIR = DATA_DIR / "results"
35
+ TESTS_DIR = DATA_DIR / "tests"
36
+ TESTS_DIR.mkdir(exist_ok=True)
37
+
38
+
39
+ def log(msg, level=0):
40
+ indent = " " * level
41
+ ts = datetime.now().strftime("%H:%M:%S")
42
+ print(f"[{ts}] {indent}{msg}")
43
+
44
+
45
+ def check_usage(service):
46
+ jobs = list(service.jobs(limit=200))
47
+ now = datetime.now(timezone.utc)
48
+ month_start = datetime(now.year, now.month, 1, tzinfo=timezone.utc)
49
+ total = 0
50
+ for j in jobs:
51
+ u = j.usage() or 0
52
+ try:
53
+ m = j.metrics()
54
+ ts = m.get('timestamps', {}).get('created', '')
55
+ if ts:
56
+ dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
57
+ if dt >= month_start:
58
+ total += u
59
+ except Exception:
60
+ pass
61
+ return {"total": total, "remaining": 600 - total, "percentage": 100 * total / 600}
62
+
63
+
64
+ # =============================================================================
65
+ # SHARED CIRCUIT BUILDERS
66
+ # =============================================================================
67
+
68
+ def build_standard(theta, qubit=0, n_qubits=1):
69
+ """Standard: Ry(theta) Ry(-theta) measure. Ideal = |0>."""
70
+ qc = QuantumCircuit(n_qubits, 1)
71
+ qc.ry(theta, qubit)
72
+ qc.ry(-theta, qubit)
73
+ qc.measure(qubit, 0)
74
+ return qc
75
+
76
+
77
+ def build_zeno(theta, n_meas, qubit=0, n_qubits=1):
78
+ """Zeno drag 0->theta via N measurements, then undo. Ideal = |0>."""
79
+ qr = QuantumRegister(n_qubits, 'q')
80
+ cr = ClassicalRegister(n_meas + 1, 'c')
81
+ qc = QuantumCircuit(qr, cr)
82
+ for k in range(1, n_meas + 1):
83
+ theta_k = k * theta / n_meas
84
+ qc.ry(-theta_k, qubit)
85
+ qc.measure(qubit, k - 1)
86
+ qc.ry(theta_k, qubit)
87
+ qc.ry(-theta, qubit)
88
+ qc.measure(qubit, n_meas)
89
+ return qc
90
+
91
+
92
+ def build_delay_matched(theta, n_meas, meas_duration_dt, qubit=0, n_qubits=1):
93
+ """Standard gate + idle delay = same wall-clock as Zeno."""
94
+ qc = QuantumCircuit(n_qubits, 1)
95
+ qc.ry(theta, qubit)
96
+ qc.delay(n_meas * meas_duration_dt, qubit, unit='dt')
97
+ qc.ry(-theta, qubit)
98
+ qc.measure(qubit, 0)
99
+ return qc
100
+
101
+
102
+ def build_zne_folded(theta, n_folds, qubit=0, n_qubits=1):
103
+ """ZNE circuit: Ry(theta)[Ry(-theta)Ry(theta)]^n_folds then Ry(-theta) measure.
104
+
105
+ n_folds=0: standard circuit (depth 1 pair)
106
+ n_folds=1: 3x noise (depth 3 pairs)
107
+ n_folds=2: 5x noise (depth 5 pairs)
108
+ """
109
+ qc = QuantumCircuit(n_qubits, 1)
110
+ qc.ry(theta, qubit)
111
+ for _ in range(n_folds):
112
+ qc.ry(-theta, qubit)
113
+ qc.ry(theta, qubit)
114
+ qc.ry(-theta, qubit)
115
+ qc.measure(qubit, 0)
116
+ return qc
117
+
118
+
119
+ def build_zeno_with_work(theta, n_meas, work_gates, qubit=0, n_qubits=1):
120
+ """Zeno drag with 'work' gates (identity-equivalent) between measurements.
121
+
122
+ Simulates practical use: computation happens between Zeno measurements.
123
+ work_gates: number of Ry(eps)Ry(-eps) pairs inserted between each step.
124
+ Net effect is identity, but adds gate noise and wall-clock time.
125
+ """
126
+ eps = 0.01 # tiny rotation — effectively identity but real gates
127
+ qr = QuantumRegister(n_qubits, 'q')
128
+ cr = ClassicalRegister(n_meas + 1, 'c')
129
+ qc = QuantumCircuit(qr, cr)
130
+
131
+ for k in range(1, n_meas + 1):
132
+ theta_k = k * theta / n_meas
133
+ qc.ry(-theta_k, qubit)
134
+ qc.measure(qubit, k - 1)
135
+ qc.ry(theta_k, qubit)
136
+ # Insert "work" between measurements
137
+ if k < n_meas:
138
+ for _ in range(work_gates):
139
+ qc.ry(eps, qubit)
140
+ qc.ry(-eps, qubit)
141
+
142
+ qc.ry(-theta, qubit)
143
+ qc.measure(qubit, n_meas)
144
+ return qc
145
+
146
+
147
+ def build_depth_matched_work(theta, n_meas, work_gates, qubit=0, n_qubits=1):
148
+ """Same gate structure as zeno_with_work but no measurements."""
149
+ eps = 0.01
150
+ qc = QuantumCircuit(n_qubits, 1)
151
+ qc.ry(theta, qubit)
152
+ for k in range(1, n_meas + 1):
153
+ theta_k = k * theta / n_meas
154
+ qc.ry(-theta_k, qubit)
155
+ qc.barrier() # placeholder for measurement
156
+ qc.ry(theta_k, qubit)
157
+ if k < n_meas:
158
+ for _ in range(work_gates):
159
+ qc.ry(eps, qubit)
160
+ qc.ry(-eps, qubit)
161
+ qc.ry(-theta, qubit)
162
+ qc.measure(qubit, 0)
163
+ return qc
164
+
165
+
166
+ # =============================================================================
167
+ # SHARED ANALYSIS
168
+ # =============================================================================
169
+
170
+ def analyze_standard(bitstrings):
171
+ total = len(bitstrings)
172
+ zeros = sum(1 for b in bitstrings if b[-1] == '0')
173
+ return {'total': total, 'fidelity': zeros / total, 'type': 'standard'}
174
+
175
+
176
+ def analyze_zeno(bitstrings, n_meas, p_meas):
177
+ """Full Zeno analysis with multiple weighting schemes."""
178
+ total = len(bitstrings)
179
+ successful = 0
180
+ correct_given_success = 0
181
+ flip_bins = {}
182
+
183
+ for bs in bitstrings:
184
+ if len(bs) < n_meas + 1:
185
+ continue
186
+ final = bs[0]
187
+ intermediate = bs[1:n_meas + 1]
188
+ n_flips = sum(1 for b in intermediate if b == '1')
189
+
190
+ if n_flips not in flip_bins:
191
+ flip_bins[n_flips] = {'total': 0, 'correct': 0}
192
+ flip_bins[n_flips]['total'] += 1
193
+ if final == '0':
194
+ flip_bins[n_flips]['correct'] += 1
195
+
196
+ if n_flips == 0:
197
+ successful += 1
198
+ if final == '0':
199
+ correct_given_success += 1
200
+
201
+ success_rate = successful / total if total > 0 else 0
202
+ fidelity_hard = correct_given_success / successful if successful > 0 else 0
203
+ expected_meas_flips = n_meas * p_meas
204
+
205
+ # exp(-k)
206
+ w1_c, w1_t = 0, 0
207
+ for nf, data in flip_bins.items():
208
+ w = np.exp(-nf)
209
+ w1_c += w * data['correct']
210
+ w1_t += w * data['total']
211
+ fid_exp_k = w1_c / w1_t if w1_t > 0 else 0
212
+
213
+ # Excess-flip
214
+ w3_c, w3_t = 0, 0
215
+ for nf, data in flip_bins.items():
216
+ excess = max(0, nf - expected_meas_flips)
217
+ w = np.exp(-excess)
218
+ w3_c += w * data['correct']
219
+ w3_t += w * data['total']
220
+ fid_excess = w3_c / w3_t if w3_t > 0 else 0
221
+
222
+ # Likelihood ratio
223
+ w4_c, w4_t = 0, 0
224
+ for nf, data in flip_bins.items():
225
+ if nf <= n_meas:
226
+ p_target = comb(n_meas, nf, exact=True) * (p_meas ** nf) * ((1 - p_meas) ** (n_meas - nf))
227
+ p_random = comb(n_meas, nf, exact=True) * (0.5 ** n_meas)
228
+ w = min(p_target / p_random, 1e10) if p_random > 0 else 0
229
+ else:
230
+ w = 0
231
+ w4_c += w * data['correct']
232
+ w4_t += w * data['total']
233
+ fid_likelihood = w4_c / w4_t if w4_t > 0 else 0
234
+
235
+ all_flips = []
236
+ for nf, data in flip_bins.items():
237
+ all_flips.extend([nf] * data['total'])
238
+ mean_flips = np.mean(all_flips) if all_flips else 0
239
+ std_flips = np.std(all_flips) if all_flips else 0
240
+
241
+ return {
242
+ 'total': total,
243
+ 'successful': successful,
244
+ 'success_rate': success_rate,
245
+ 'fidelity_hard_ps': fidelity_hard,
246
+ 'fidelity_exp_k': fid_exp_k,
247
+ 'fidelity_excess': fid_excess,
248
+ 'fidelity_likelihood': fid_likelihood,
249
+ 'expected_meas_flips': expected_meas_flips,
250
+ 'mean_flips': mean_flips,
251
+ 'std_flips': std_flips,
252
+ 'flip_distribution': {str(k): v for k, v in sorted(flip_bins.items())},
253
+ 'type': 'zeno',
254
+ }
255
+
256
+
257
+ # =============================================================================
258
+ # OFFLINE TEST W2: Measurement Error Independence
259
+ # =============================================================================
260
+
261
+ def test_w2_measurement_independence():
262
+ """Test whether excess-flip weighting's independence assumption holds.
263
+
264
+ Key insight: raw outcome correlations are HIGH in identity Zeno because
265
+ measurement backaction is projective — a single measurement error physically
266
+ flips the qubit, and it stays flipped until another error flips it back.
267
+ This is NOT a violation of the independence assumption.
268
+
269
+ The correct test is on TRANSITIONS (0->1 or 1->0 events), not raw outcomes.
270
+ Each transition is a separate physical event (measurement error or T1 decay).
271
+ If transitions are independent, the excess-flip model is justified.
272
+
273
+ Three sub-tests:
274
+ 2a: Transition rate analysis — are transitions (not raw flips) independent?
275
+ 2b: Flip count vs Binomial — does the distribution match?
276
+ 2c: Does flip count predict fidelity monotonically? (functional test)
277
+ """
278
+ print("\n" + "=" * 70)
279
+ print("W2: MEASUREMENT ERROR INDEPENDENCE TEST")
280
+ print("=" * 70)
281
+
282
+ results = {}
283
+
284
+ # Load diagnostic data (has explicit identity Zeno)
285
+ diag_path = RESULTS_DIR / 'zeno_diagnostic' / 'zeno_diagnostic.json'
286
+ hn = json.load(open(RESULTS_DIR / 'zeno_high_n_sweep' / 'zeno_high_n_sweep.json'))
287
+ p_meas = hn['hardware_timing']['measurement_error']
288
+
289
+ if diag_path.exists():
290
+ diag = json.load(open(diag_path))
291
+ else:
292
+ diag = None
293
+
294
+ # Get identity Zeno bitstrings
295
+ if diag is not None and 'identity_zeno_N32' in diag['results']:
296
+ entry = diag['results']['identity_zeno_N32']
297
+ bitstrings = entry.get('raw_bitstrings', [])
298
+ n_meas = entry.get('params', {}).get('n_meas', 32)
299
+ source = "identity_zeno_N32 (diagnostic)"
300
+ else:
301
+ entry = hn['results'].get('zeno_X_N32', {})
302
+ bitstrings = entry.get('raw_bitstrings', [])
303
+ n_meas = entry.get('params', {}).get('n_meas', 32)
304
+ source = "zeno_X_N32 (fallback — expect structured correlations)"
305
+
306
+ print(f"\n Data source: {source}")
307
+ print(f" Bitstrings: {len(bitstrings)}, N={n_meas}")
308
+
309
+ # --- Test 2a: Transition analysis ---
310
+ print("\n--- 2a: Transition rate analysis ---")
311
+ print(" Raw outcomes are correlated by design (backaction is projective).")
312
+ print(" Testing TRANSITIONS (0->1, 1->0) for independence instead.")
313
+
314
+ if len(bitstrings) >= 50:
315
+ n_pos = min(n_meas, 32)
316
+ transition_counts = []
317
+ run_lengths = [] # lengths of consecutive-same-value runs
318
+
319
+ for bs in bitstrings:
320
+ if len(bs) < n_meas + 1:
321
+ continue
322
+ intermediate = bs[1:n_meas + 1]
323
+ seq = [int(intermediate[i] == '1') for i in range(n_pos)]
324
+
325
+ # Count transitions (value changes between adjacent positions)
326
+ transitions = sum(1 for i in range(len(seq) - 1) if seq[i] != seq[i + 1])
327
+ transition_counts.append(transitions)
328
+
329
+ # Compute run lengths
330
+ current_run = 1
331
+ for i in range(1, len(seq)):
332
+ if seq[i] == seq[i - 1]:
333
+ current_run += 1
334
+ else:
335
+ run_lengths.append(current_run)
336
+ current_run = 1
337
+ run_lengths.append(current_run)
338
+
339
+ n_shots = len(transition_counts)
340
+ mean_transitions = np.mean(transition_counts)
341
+ std_transitions = np.std(transition_counts)
342
+ mean_run = np.mean(run_lengths)
343
+
344
+ # Under independent Bernoulli(p) outcomes, expected transitions = (N-1)*2*p*(1-p)
345
+ expected_transitions = (n_pos - 1) * 2 * p_meas * (1 - p_meas)
346
+ # Under correlated (backaction) model, transitions are much rarer
347
+ # because a flip persists until the next error event
348
+
349
+ # If backaction dominates: expected transitions ~ 2 * N * p_backaction
350
+ # where p_backaction is the rate of actual state-change events
351
+ # Mean run length under independence = 1 / (2*p*(1-p)) ~ 4.9 for p=0.12
352
+ # Mean run length under backaction = 1 / p_transition (much longer)
353
+
354
+ print(f" Shots analyzed: {n_shots}")
355
+ print(f" Mean transitions/shot: {mean_transitions:.2f}")
356
+ print(f" Expected (independent): {expected_transitions:.2f}")
357
+ print(f" Ratio (obs/expected): {mean_transitions/expected_transitions:.3f}")
358
+ print(f" Mean run length: {mean_run:.2f}")
359
+ print(f" Expected run (indep): {1/(2*p_meas*(1-p_meas)):.2f}")
360
+
361
+ # Now test: are transitions themselves independent?
362
+ # Build binary transition sequence and test pairwise correlation
363
+ trans_adj_phis = []
364
+ for bs in bitstrings[:500]:
365
+ if len(bs) < n_meas + 1:
366
+ continue
367
+ intermediate = bs[1:n_meas + 1]
368
+ seq = [int(intermediate[i] == '1') for i in range(n_pos)]
369
+ trans_seq = [1 if seq[i] != seq[i + 1] else 0 for i in range(len(seq) - 1)]
370
+
371
+ if len(trans_seq) >= 4:
372
+ ts = np.array(trans_seq, dtype=float)
373
+ if ts.std() > 0:
374
+ ac = np.corrcoef(ts[:-1], ts[1:])[0, 1]
375
+ if not np.isnan(ac):
376
+ trans_adj_phis.append(ac)
377
+
378
+ if trans_adj_phis:
379
+ mean_trans_ac = np.mean(trans_adj_phis)
380
+ t_stat, p_val = sp_stats.ttest_1samp(trans_adj_phis, 0)
381
+
382
+ print(f"\n Transition-sequence lag-1 autocorrelation:")
383
+ print(f" Mean: {mean_trans_ac:+.4f}")
384
+ print(f" t={t_stat:.2f}, p={p_val:.6f}")
385
+
386
+ if abs(mean_trans_ac) > 0.1 and p_val < 0.01:
387
+ verdict_2a = "FAIL: Transitions themselves are correlated. Error events cluster."
388
+ elif abs(mean_trans_ac) > 0.05 and p_val < 0.05:
389
+ verdict_2a = "WEAK: Mild transition correlation. Excess-flip may slightly misweight."
390
+ else:
391
+ verdict_2a = "PASS: Transitions are uncorrelated. Each error event is independent."
392
+
393
+ print(f"\n VERDICT: {verdict_2a}")
394
+
395
+ results['w2a_transition_analysis'] = {
396
+ 'n_shots': n_shots,
397
+ 'mean_transitions': float(mean_transitions),
398
+ 'expected_transitions': float(expected_transitions),
399
+ 'transition_ratio': float(mean_transitions / expected_transitions),
400
+ 'mean_run_length': float(mean_run),
401
+ 'transition_autocorrelation': float(mean_trans_ac),
402
+ 't_stat': float(t_stat),
403
+ 'p_value': float(p_val),
404
+ 'verdict': verdict_2a,
405
+ }
406
+
407
+ # --- Test 2b: Flip count distribution vs Binomial ---
408
+ print("\n--- 2b: Flip count distribution ---")
409
+
410
+ if diag is not None:
411
+ id_entry = diag['results'].get('identity_zeno_N32', {})
412
+ id_analysis = id_entry.get('analysis', {})
413
+ flip_dist = id_analysis.get('flip_distribution', {})
414
+ id_n_meas = id_entry.get('params', {}).get('n_meas', 32)
415
+ id_p_meas = diag['hardware_timing']['measurement_error']
416
+ else:
417
+ flip_dist = {}
418
+ id_n_meas = 0
419
+ id_p_meas = p_meas
420
+
421
+ if flip_dist and id_n_meas > 0:
422
+ observed_counts = {}
423
+ total_shots = 0
424
+ for k_str, v in flip_dist.items():
425
+ k = int(k_str)
426
+ count = v['total']
427
+ observed_counts[k] = count
428
+ total_shots += count
429
+
430
+ # Expected binomial distribution
431
+ max_k = max(observed_counts.keys())
432
+ observed = []
433
+ expected = []
434
+ labels = []
435
+ for k in range(max_k + 1):
436
+ obs = observed_counts.get(k, 0)
437
+ exp = total_shots * sp_stats.binom.pmf(k, id_n_meas, id_p_meas)
438
+ if exp >= 5:
439
+ observed.append(obs)
440
+ expected.append(exp)
441
+ labels.append(k)
442
+
443
+ if len(observed) >= 3:
444
+ # Normalize expected to match observed total (required by scipy)
445
+ obs_arr = np.array(observed, dtype=float)
446
+ exp_arr = np.array(expected, dtype=float)
447
+ exp_arr = exp_arr * obs_arr.sum() / exp_arr.sum()
448
+
449
+ chi2, p_value = sp_stats.chisquare(obs_arr, exp_arr)
450
+
451
+ print(f" Identity Zeno N={id_n_meas}, p_meas={id_p_meas:.4f}")
452
+ print(f" Total shots: {total_shots}")
453
+ print(f" Bins tested: {len(observed)} (k={labels[0]}..{labels[-1]})")
454
+ print(f" Chi-squared: {chi2:.2f}")
455
+ print(f" p-value: {p_value:.6f}")
456
+ print(f" Expected mean flips: {id_n_meas * id_p_meas:.1f}")
457
+ print(f" Observed mean flips: {id_analysis.get('mean_flips', 0):.1f}")
458
+
459
+ # Also print observed vs expected for each bin
460
+ print(f"\n {'k':>3} | {'Observed':>8} | {'Expected':>8} | {'Ratio':>6}")
461
+ print(f" " + "-" * 35)
462
+ for k, o, e in zip(labels, obs_arr, exp_arr):
463
+ print(f" {k:3d} | {o:8.0f} | {e:8.1f} | {o/e:6.2f}")
464
+
465
+ if p_value < 0.001:
466
+ verdict_2b = "FAIL: Flip counts deviate from Binomial. Backaction creates correlated runs."
467
+ elif p_value < 0.05:
468
+ verdict_2b = "WEAK: Marginal deviation (p<0.05). Mild departure from independence."
469
+ else:
470
+ verdict_2b = "PASS: Flip counts consistent with Binomial."
471
+
472
+ print(f"\n VERDICT: {verdict_2b}")
473
+
474
+ results['w2b_binomial_gof'] = {
475
+ 'n_meas': id_n_meas,
476
+ 'p_meas': float(id_p_meas),
477
+ 'total_shots': total_shots,
478
+ 'chi2': float(chi2),
479
+ 'p_value': float(p_value),
480
+ 'bins_tested': len(observed),
481
+ 'verdict': verdict_2b,
482
+ }
483
+ else:
484
+ print(" No identity Zeno data available. Skipping.")
485
+
486
+ # --- Test 2c: Does flip count monotonically predict fidelity? ---
487
+ print("\n--- 2c: Flip-count-to-fidelity monotonicity ---")
488
+ print(" If excess-flip weighting is valid, more flips => lower fidelity,")
489
+ print(" regardless of whether flips are independent or correlated.")
490
+
491
+ if diag is not None and 'identity_zeno_N32' in diag['results']:
492
+ id_analysis = diag['results']['identity_zeno_N32']['analysis']
493
+ flip_dist = id_analysis.get('flip_distribution', {})
494
+
495
+ fid_by_flips = []
496
+ print(f"\n {'Flips':>5} | {'Shots':>5} | {'Correct':>7} | {'Fidelity':>8}")
497
+ print(f" " + "-" * 35)
498
+ for k in sorted(int(x) for x in flip_dist.keys()):
499
+ v = flip_dist[str(k)]
500
+ fid = v['correct'] / v['total'] if v['total'] > 0 else 0
501
+ if v['total'] >= 10:
502
+ fid_by_flips.append((k, fid))
503
+ print(f" {k:5d} | {v['total']:5d} | {v['correct']:7d} | {fid:8.4f}")
504
+
505
+ # Check monotonicity
506
+ if len(fid_by_flips) >= 3:
507
+ fids_only = [f for _, f in fid_by_flips]
508
+ violations = sum(1 for i in range(len(fids_only) - 1)
509
+ if fids_only[i + 1] > fids_only[i] + 0.02)
510
+
511
+ if violations == 0:
512
+ verdict_2c = "PASS: Fidelity decreases monotonically with flip count. Weighting is justified."
513
+ elif violations <= 1:
514
+ verdict_2c = "PASS: Nearly monotonic (1 minor violation). Weighting is reasonable."
515
+ else:
516
+ verdict_2c = f"FAIL: {violations} monotonicity violations. Flip count is a poor fidelity predictor."
517
+
518
+ print(f"\n Monotonicity violations: {violations}")
519
+ print(f" VERDICT: {verdict_2c}")
520
+
521
+ results['w2c_monotonicity'] = {
522
+ 'fidelity_by_flips': [(k, float(f)) for k, f in fid_by_flips],
523
+ 'violations': violations,
524
+ 'verdict': verdict_2c,
525
+ }
526
+
527
+ return results
528
+
529
+
530
+ # =============================================================================
531
+ # OFFLINE TEST W4: VQE Bias Correction Assumes Constant Fidelity
532
+ # =============================================================================
533
+
534
+ def test_w4_vqe_fidelity_constancy():
535
+ """Test whether fidelity is constant across theta for the VQE correction.
536
+
537
+ The correction z_corrected = z_measured / (2f - 1) assumes f is constant.
538
+ We check: does the fidelity measured per-theta vary significantly?
539
+ If so, a per-theta calibration would be more accurate.
540
+ """
541
+ print("\n" + "=" * 70)
542
+ print("W4: VQE FIDELITY CONSTANCY TEST")
543
+ print("=" * 70)
544
+
545
+ results = {}
546
+ vqe_path = RESULTS_DIR / 'vqe_trajectory_validation' / 'vqe_trajectory_validation.json'
547
+ if not vqe_path.exists():
548
+ print(" VQE data not found. Skipping.")
549
+ return results
550
+
551
+ vqe = json.load(open(vqe_path))
552
+ n_meas = vqe['n_meas']
553
+ shots = vqe['shots']
554
+
555
+ # Extract per-theta fidelity from Zeno circuits
556
+ theta_fidelities = []
557
+ theta_values = []
558
+
559
+ for key, entry in vqe['results'].items():
560
+ if entry.get('type') != 'zeno':
561
+ continue
562
+ theta = entry['theta']
563
+ bitstrings = entry.get('bitstrings', [])
564
+ if not bitstrings:
565
+ continue
566
+
567
+ # Compute hard-PS fidelity at this theta
568
+ # For Zeno circuits: fidelity = P(correct final | successful trajectory)
569
+ # "correct" depends on what the target state is at this theta
570
+ # The VQE measures <Z>, so the circuit prepares Ry(theta)|0> then measures
571
+ # Actually the Zeno does drag + undo, so target is always |0>
572
+ # fidelity = P(0 | successful)
573
+ successful = 0
574
+ correct = 0
575
+ for bs in bitstrings:
576
+ if len(bs) < n_meas + 1:
577
+ continue
578
+ final = bs[0]
579
+ intermediate = bs[1:n_meas + 1]
580
+ n_flips = sum(1 for b in intermediate if b == '1')
581
+ if n_flips == 0:
582
+ successful += 1
583
+ if final == '0':
584
+ correct += 1
585
+
586
+ if successful > 10:
587
+ fid = correct / successful
588
+ theta_fidelities.append(fid)
589
+ theta_values.append(theta)
590
+
591
+ if len(theta_fidelities) < 3:
592
+ print(" Insufficient per-theta data points.")
593
+ return results
594
+
595
+ thetas = np.array(theta_values)
596
+ fids = np.array(theta_fidelities)
597
+ mean_fid = np.mean(fids)
598
+ std_fid = np.std(fids)
599
+ spread = np.max(fids) - np.min(fids)
600
+
601
+ print(f"\n Per-theta hard-PS fidelity (N={n_meas}, {shots} shots):")
602
+ print(f" {'theta/pi':>8} | {'Fidelity':>8}")
603
+ print(f" " + "-" * 20)
604
+ for t, f in zip(thetas, fids):
605
+ print(f" {t/np.pi:8.3f} | {f:8.4f}")
606
+
607
+ print(f"\n Mean fidelity: {mean_fid:.4f}")
608
+ print(f" Std fidelity: {std_fid:.4f}")
609
+ print(f" Spread (max-min): {spread:.4f}")
610
+
611
+ # Chi-squared test: are all fidelities consistent with a single value?
612
+ # Under null hypothesis (constant f), each fidelity is binomial
613
+ # Use Cochran's Q or simpler: test if variance exceeds binomial expectation
614
+ expected_var = mean_fid * (1 - mean_fid) / shots # variance of single estimate
615
+ observed_var = np.var(fids, ddof=1)
616
+ F_ratio = observed_var / expected_var if expected_var > 0 else 0
617
+
618
+ print(f"\n Expected variance (binomial): {expected_var:.6f}")
619
+ print(f" Observed variance: {observed_var:.6f}")
620
+ print(f" F-ratio (obs/exp): {F_ratio:.2f}")
621
+
622
+ # Also: what RMSE improvement would per-theta calibration give?
623
+ # Recompute VQE estimates with per-theta fidelity vs global fidelity
624
+ print("\n --- Impact on VQE RMSE ---")
625
+
626
+ global_errors = []
627
+ pertheta_errors = []
628
+
629
+ for i, (key, entry) in enumerate(
630
+ [(k, v) for k, v in vqe['results'].items() if v.get('type') == 'zeno']
631
+ ):
632
+ theta = entry['theta']
633
+ true_z = entry['true_z']
634
+ estimates = entry.get('estimates', {})
635
+ hard_est = estimates.get('hard_ps', 0)
636
+
637
+ # Global correction
638
+ if abs(2 * mean_fid - 1) > 0.01:
639
+ global_corrected = hard_est / (2 * mean_fid - 1)
640
+ else:
641
+ global_corrected = hard_est
642
+
643
+ # Per-theta correction
644
+ if i < len(fids) and abs(2 * fids[i] - 1) > 0.01:
645
+ pertheta_corrected = hard_est / (2 * fids[i] - 1)
646
+ else:
647
+ pertheta_corrected = hard_est
648
+
649
+ global_errors.append((global_corrected - true_z) ** 2)
650
+ pertheta_errors.append((pertheta_corrected - true_z) ** 2)
651
+
652
+ if global_errors:
653
+ global_rmse = np.sqrt(np.mean(global_errors))
654
+ pertheta_rmse = np.sqrt(np.mean(pertheta_errors))
655
+ improvement = (global_rmse - pertheta_rmse) / global_rmse * 100
656
+
657
+ print(f" Global-fidelity RMSE: {global_rmse:.4f}")
658
+ print(f" Per-theta-fidelity RMSE: {pertheta_rmse:.4f}")
659
+ print(f" Improvement: {improvement:+.1f}%")
660
+
661
+ if spread < 0.03:
662
+ verdict = "PASS: Fidelity variation < 3pp across theta. Constant assumption is reasonable."
663
+ elif spread < 0.08:
664
+ verdict = "WEAK: Fidelity varies 3-8pp. Constant assumption introduces mild bias."
665
+ else:
666
+ verdict = "FAIL: Fidelity varies >8pp. Per-theta calibration needed."
667
+
668
+ print(f"\n VERDICT: {verdict}")
669
+
670
+ results['w4_fidelity_constancy'] = {
671
+ 'n_thetas': len(theta_fidelities),
672
+ 'mean_fidelity': float(mean_fid),
673
+ 'std_fidelity': float(std_fid),
674
+ 'spread': float(spread),
675
+ 'F_ratio': float(F_ratio),
676
+ 'global_rmse': float(global_rmse) if global_errors else None,
677
+ 'pertheta_rmse': float(pertheta_rmse) if pertheta_errors else None,
678
+ 'verdict': verdict,
679
+ }
680
+
681
+ return results
682
+
683
+
684
+ # =============================================================================
685
+ # OFFLINE TEST W5: ML Model vs Simple Heuristics
686
+ # =============================================================================
687
+
688
+ def test_w5_ml_vs_heuristics():
689
+ """Test whether the ML model meaningfully outperforms simple heuristics.
690
+
691
+ Load trajectory_estimation bitstrings. Apply:
692
+ 1. Hard post-selection (k=0)
693
+ 2. Soft k<=1
694
+ 3. Soft k<=2
695
+ 4. exp(-k)
696
+ 5. Excess-flip exp(-max(0, k-Np))
697
+ 6. Simple early-flip penalty: exp(-2 * early_flips - 0.5 * late_flips)
698
+
699
+ Compare effective yields. If #6 matches ML within 2pp, the complexity
700
+ of ML is unjustified.
701
+ """
702
+ print("\n" + "=" * 70)
703
+ print("W5: ML vs SIMPLE HEURISTICS")
704
+ print("=" * 70)
705
+
706
+ results = {}
707
+ traj_path = RESULTS_DIR / 'trajectory_estimation' / 'trajectory_estimation.json'
708
+ if not traj_path.exists():
709
+ print(" Trajectory estimation data not found. Skipping.")
710
+ return results
711
+
712
+ traj = json.load(open(traj_path))
713
+
714
+ # Find x_freeze_n8 — the cleanest test case
715
+ target_key = None
716
+ for key in (traj.get('data', {}) if isinstance(traj.get('data'), dict) else {}):
717
+ if 'x_freeze' in key and 'n8' in key:
718
+ target_key = key
719
+ break
720
+
721
+ if target_key is None:
722
+ # Try alternate structure
723
+ for key in traj.get('results', traj.get('data', {})):
724
+ if 'x_freeze' in key and 'n8' in key:
725
+ target_key = key
726
+ break
727
+
728
+ if target_key is None:
729
+ print(" x_freeze_n8 data not found. Trying drag_n8.")
730
+ for key in (traj.get('data', {}) if isinstance(traj.get('data'), dict) else {}):
731
+ if 'drag' in key and 'n8' in key:
732
+ target_key = key
733
+ break
734
+
735
+ data_container = traj.get('data', traj.get('results', {}))
736
+ if target_key is None or target_key not in data_container:
737
+ print(" No suitable trajectory data found. Skipping.")
738
+ return results
739
+
740
+ entry = data_container[target_key]
741
+ bitstrings = entry.get('bitstrings', entry.get('raw_bitstrings', []))
742
+ n_meas = 8
743
+
744
+ if len(bitstrings) < 100:
745
+ print(f" Only {len(bitstrings)} bitstrings. Need >= 100. Skipping.")
746
+ return results
747
+
748
+ print(f"\n Dataset: {target_key}, {len(bitstrings)} trajectories, N={n_meas}")
749
+
750
+ # Parse all trajectories
751
+ parsed = []
752
+ for bs in bitstrings:
753
+ if len(bs) < n_meas + 1:
754
+ continue
755
+ final = bs[0]
756
+ intermediate = bs[1:n_meas + 1]
757
+ n_flips = sum(1 for b in intermediate if b == '1')
758
+ flip_positions = [i for i, b in enumerate(intermediate) if b == '1']
759
+ correct = 1 if final == '0' else 0
760
+
761
+ early_flips = sum(1 for p in flip_positions if p < n_meas // 2)
762
+ late_flips = n_flips - early_flips
763
+ has_pos0 = 1 if 0 in flip_positions else 0
764
+
765
+ parsed.append({
766
+ 'n_flips': n_flips,
767
+ 'flip_positions': flip_positions,
768
+ 'correct': correct,
769
+ 'early_flips': early_flips,
770
+ 'late_flips': late_flips,
771
+ 'has_pos0': has_pos0,
772
+ })
773
+
774
+ # Define weighting strategies
775
+ strategies = {
776
+ 'hard_k0': lambda s: 1.0 if s['n_flips'] == 0 else 0.0,
777
+ 'soft_k1': lambda s: 1.0 if s['n_flips'] <= 1 else 0.0,
778
+ 'soft_k2': lambda s: 1.0 if s['n_flips'] <= 2 else 0.0,
779
+ 'exp_k': lambda s: np.exp(-s['n_flips']),
780
+ 'excess_flip': lambda s: np.exp(-max(0, s['n_flips'] - n_meas * 0.003)),
781
+ 'early_penalty': lambda s: (
782
+ np.exp(-2.0 * s['early_flips'] - 0.3 * s['late_flips'])
783
+ if s['n_flips'] > 0 else 1.0
784
+ ),
785
+ 'pos0_aware': lambda s: (
786
+ 0.0 if (s['has_pos0'] and s['n_flips'] > 1)
787
+ else (0.5 if s['has_pos0'] else (1.0 if s['n_flips'] <= 2 else 0.3))
788
+ ),
789
+ 'uniform': lambda s: 1.0,
790
+ }
791
+
792
+ print(f"\n {'Strategy':>16} | {'Fidelity':>8} | {'Utilization':>11} | {'Eff Yield':>9}")
793
+ print(f" " + "-" * 55)
794
+
795
+ strategy_results = {}
796
+ for name, weight_fn in strategies.items():
797
+ w_correct = 0
798
+ w_total = 0
799
+ for s in parsed:
800
+ w = weight_fn(s)
801
+ w_correct += w * s['correct']
802
+ w_total += w
803
+
804
+ fidelity = w_correct / w_total if w_total > 0 else 0
805
+ utilization = w_total / len(parsed) if parsed else 0
806
+ eff_yield = fidelity * utilization
807
+
808
+ strategy_results[name] = {
809
+ 'fidelity': float(fidelity),
810
+ 'utilization': float(utilization),
811
+ 'effective_yield': float(eff_yield),
812
+ }
813
+
814
+ print(f" {name:>16} | {fidelity:8.4f} | {utilization:11.4f} | {eff_yield:9.4f}")
815
+
816
+ # Compare: is the gap between best simple heuristic and exp_k significant?
817
+ simple_yields = [v['effective_yield'] for k, v in strategy_results.items()
818
+ if k in ('early_penalty', 'pos0_aware', 'soft_k2')]
819
+ best_simple = max(simple_yields) if simple_yields else 0
820
+ exp_yield = strategy_results.get('exp_k', {}).get('effective_yield', 0)
821
+ gap = exp_yield - best_simple
822
+
823
+ print(f"\n Best simple heuristic yield: {best_simple:.4f}")
824
+ print(f" exp(-k) yield: {exp_yield:.4f}")
825
+ print(f" Gap: {gap:+.4f}")
826
+
827
+ if abs(gap) < 0.02:
828
+ verdict = "CONFIRMED: Simple heuristics match exp(-k) within 2pp. ML adds complexity without meaningful gain."
829
+ elif gap > 0.02:
830
+ verdict = f"PARTIAL: exp(-k) beats best simple heuristic by {gap:.1%}. But position-aware heuristics close the gap."
831
+ else:
832
+ verdict = "REFUTED: Simple heuristic actually beats exp(-k). Position awareness helps."
833
+
834
+ print(f"\n VERDICT: {verdict}")
835
+
836
+ results['w5_ml_vs_heuristics'] = {
837
+ 'n_trajectories': len(parsed),
838
+ 'strategies': strategy_results,
839
+ 'best_simple_yield': float(best_simple),
840
+ 'exp_k_yield': float(exp_yield),
841
+ 'gap': float(gap),
842
+ 'verdict': verdict,
843
+ }
844
+
845
+ return results
846
+
847
+
848
+ # =============================================================================
849
+ # HARDWARE TESTS — Circuit builders for W1, W3, W6
850
+ # =============================================================================
851
+
852
+ @dataclass
853
+ class ExperimentConfig:
854
+ name: str
855
+ circuit: QuantumCircuit
856
+ category: str
857
+ weakness: str
858
+ params: dict
859
+
860
+
861
+ def build_hardware_experiments(backend):
862
+ """Build all circuits for weaknesses 1, 3, 6 in one list."""
863
+ dt = backend.dt
864
+ target = backend.target
865
+ meas_duration_dt = int(target['measure'][(0,)].duration / dt)
866
+ meas_error = target['measure'][(0,)].error
867
+
868
+ # Collect qubit properties for W1 qubit selection
869
+ qubit_t1 = {}
870
+ qubit_meas_err = {}
871
+ for qi in range(min(backend.num_qubits, 133)):
872
+ try:
873
+ props = backend.qubit_properties(qi)
874
+ qubit_t1[qi] = props.t1
875
+ mp = target['measure'][(qi,)]
876
+ qubit_meas_err[qi] = mp.error
877
+ except Exception:
878
+ pass
879
+
880
+ # Select 5 diverse qubits for W1: best T1, worst T1, median T1, plus
881
+ # lowest meas error, highest meas error
882
+ if len(qubit_t1) >= 5:
883
+ sorted_by_t1 = sorted(qubit_t1.items(), key=lambda x: x[1])
884
+ # Filter out qubits with absurdly high measurement error (>30%)
885
+ valid_qubits = [(q, t) for q, t in sorted_by_t1 if qubit_meas_err.get(q, 1) < 0.30]
886
+ if len(valid_qubits) < 5:
887
+ valid_qubits = sorted_by_t1
888
+
889
+ best_t1_q = valid_qubits[-1][0]
890
+ worst_t1_q = valid_qubits[0][0]
891
+ median_t1_q = valid_qubits[len(valid_qubits) // 2][0]
892
+
893
+ sorted_by_merr = sorted(qubit_meas_err.items(), key=lambda x: x[1])
894
+ valid_merr = [(q, e) for q, e in sorted_by_merr if q in qubit_t1]
895
+ low_merr_q = valid_merr[0][0]
896
+ high_merr_q = valid_merr[-1][0] if valid_merr[-1][1] < 0.30 else valid_merr[-2][0]
897
+
898
+ # Deduplicate — ensure 5 distinct qubits
899
+ w1_qubits = list(dict.fromkeys([
900
+ 0, # always include qubit 0 for baseline comparison
901
+ best_t1_q,
902
+ worst_t1_q,
903
+ median_t1_q,
904
+ low_merr_q,
905
+ high_merr_q,
906
+ ]))[:5]
907
+ else:
908
+ w1_qubits = [0]
909
+
910
+ experiments = []
911
+ theta_X = np.pi
912
+ theta_I = 0.0
913
+ n_meas = 8
914
+ shots = 4096
915
+
916
+ # =========================================================================
917
+ # W1: Multi-qubit generalization
918
+ # =========================================================================
919
+ for qi in w1_qubits:
920
+ qi_t1 = qubit_t1.get(qi, 0)
921
+ qi_merr = qubit_meas_err.get(qi, 0)
922
+ qi_meas_dt = int(target['measure'][(qi,)].duration / dt) if (qi,) in target['measure'] else meas_duration_dt
923
+
924
+ for gate_name, theta in [('I', theta_I), ('X', theta_X)]:
925
+ # Standard
926
+ experiments.append(ExperimentConfig(
927
+ name=f"w1_q{qi}_{gate_name}_standard",
928
+ circuit=build_standard(theta, qubit=qi, n_qubits=max(w1_qubits) + 1),
929
+ category="standard",
930
+ weakness="W1",
931
+ params={'qubit': qi, 'gate': gate_name, 'theta': theta,
932
+ 'T1_us': qi_t1 * 1e6, 'meas_error': qi_merr},
933
+ ))
934
+ # Zeno
935
+ experiments.append(ExperimentConfig(
936
+ name=f"w1_q{qi}_{gate_name}_zeno",
937
+ circuit=build_zeno(theta, n_meas, qubit=qi, n_qubits=max(w1_qubits) + 1),
938
+ category="zeno",
939
+ weakness="W1",
940
+ params={'qubit': qi, 'gate': gate_name, 'theta': theta,
941
+ 'n_meas': n_meas, 'T1_us': qi_t1 * 1e6,
942
+ 'meas_error': qi_merr},
943
+ ))
944
+ # Delay-matched
945
+ experiments.append(ExperimentConfig(
946
+ name=f"w1_q{qi}_{gate_name}_delay",
947
+ circuit=build_delay_matched(theta, n_meas, qi_meas_dt, qubit=qi,
948
+ n_qubits=max(w1_qubits) + 1),
949
+ category="delay_matched",
950
+ weakness="W1",
951
+ params={'qubit': qi, 'gate': gate_name, 'theta': theta,
952
+ 'n_meas': n_meas, 'T1_us': qi_t1 * 1e6,
953
+ 'meas_error': qi_merr},
954
+ ))
955
+
956
+ # =========================================================================
957
+ # W3: Zero-noise extrapolation comparison
958
+ # =========================================================================
959
+ for gate_name, theta in [('I', theta_I), ('X', theta_X)]:
960
+ for n_folds in [0, 1, 2, 3]:
961
+ noise_level = 2 * n_folds + 1
962
+ experiments.append(ExperimentConfig(
963
+ name=f"w3_{gate_name}_zne_{noise_level}x",
964
+ circuit=build_zne_folded(theta, n_folds),
965
+ category="zne",
966
+ weakness="W3",
967
+ params={'gate': gate_name, 'theta': theta,
968
+ 'n_folds': n_folds, 'noise_level': noise_level},
969
+ ))
970
+
971
+ # =========================================================================
972
+ # W6: Computation between measurements
973
+ # =========================================================================
974
+ theta_test = np.pi / 2 # Ry(pi/2) — midpoint, not trivial
975
+
976
+ for work_gates in [0, 1, 2, 4]:
977
+ # Zeno with interleaved work
978
+ experiments.append(ExperimentConfig(
979
+ name=f"w6_zeno_work{work_gates}",
980
+ circuit=build_zeno_with_work(theta_test, n_meas, work_gates),
981
+ category="zeno_work",
982
+ weakness="W6",
983
+ params={'gate': 'Ry_pi2', 'theta': theta_test,
984
+ 'n_meas': n_meas, 'work_gates': work_gates},
985
+ ))
986
+
987
+ # Depth-matched (same gates, no measurements)
988
+ experiments.append(ExperimentConfig(
989
+ name=f"w6_depth_work{work_gates}",
990
+ circuit=build_depth_matched_work(theta_test, n_meas, work_gates),
991
+ category="depth_work",
992
+ weakness="W6",
993
+ params={'gate': 'Ry_pi2', 'theta': theta_test,
994
+ 'n_meas': n_meas, 'work_gates': work_gates},
995
+ ))
996
+
997
+ # Delay-matched (same wall-clock, idle)
998
+ total_gates = n_meas * (2 + 2 * work_gates) # Ry pairs per step
999
+ extra_dt = work_gates * 2 * int(32e-9 / dt) * (n_meas - 1) # gate time in dt
1000
+ delay_dt = n_meas * meas_duration_dt + extra_dt
1001
+ experiments.append(ExperimentConfig(
1002
+ name=f"w6_delay_work{work_gates}",
1003
+ circuit=build_delay_matched(theta_test, n_meas, meas_duration_dt + extra_dt // n_meas),
1004
+ category="delay_work",
1005
+ weakness="W6",
1006
+ params={'gate': 'Ry_pi2', 'theta': theta_test,
1007
+ 'n_meas': n_meas, 'work_gates': work_gates},
1008
+ ))
1009
+
1010
+ # Standard baseline for W6
1011
+ experiments.append(ExperimentConfig(
1012
+ name="w6_standard",
1013
+ circuit=build_standard(theta_test),
1014
+ category="standard",
1015
+ weakness="W6",
1016
+ params={'gate': 'Ry_pi2', 'theta': theta_test},
1017
+ ))
1018
+
1019
+ log(f"W1 qubits selected: {w1_qubits}")
1020
+ for qi in w1_qubits:
1021
+ log(f" Q{qi}: T1={qubit_t1.get(qi,0)*1e6:.1f}us, meas_err={qubit_meas_err.get(qi,0):.4f}", 1)
1022
+
1023
+ return experiments, {
1024
+ 'w1_qubits': w1_qubits,
1025
+ 'qubit_properties': {
1026
+ str(qi): {'T1_us': qubit_t1.get(qi, 0) * 1e6,
1027
+ 'meas_error': qubit_meas_err.get(qi, 0)}
1028
+ for qi in w1_qubits
1029
+ },
1030
+ 'meas_duration_dt': meas_duration_dt,
1031
+ 'meas_error_q0': meas_error,
1032
+ 'dt_ns': dt * 1e9,
1033
+ }
1034
+
1035
+
1036
+ # =============================================================================
1037
+ # HARDWARE ANALYSIS
1038
+ # =============================================================================
1039
+
1040
+ def analyze_hardware_results(experiments, result, hw_meta):
1041
+ """Analyze all hardware results and produce verdicts for W1, W3, W6."""
1042
+ results_data = {}
1043
+
1044
+ for i, exp in enumerate(experiments):
1045
+ pub_result = result[i]
1046
+ data_bin = pub_result.data
1047
+
1048
+ if hasattr(data_bin, 'c'):
1049
+ bitstrings = list(data_bin.c.get_bitstrings())
1050
+ elif hasattr(data_bin, 'meas'):
1051
+ bitstrings = list(data_bin.meas.get_bitstrings())
1052
+ else:
1053
+ cr_name = list(data_bin.keys())[0]
1054
+ bitstrings = list(getattr(data_bin, cr_name).get_bitstrings())
1055
+
1056
+ p_meas = exp.params.get('meas_error', hw_meta['meas_error_q0'])
1057
+
1058
+ if 'zeno' in exp.category:
1059
+ analysis = analyze_zeno(bitstrings, exp.params.get('n_meas', 8), p_meas)
1060
+ else:
1061
+ analysis = analyze_standard(bitstrings)
1062
+
1063
+ results_data[exp.name] = {
1064
+ 'category': exp.category,
1065
+ 'weakness': exp.weakness,
1066
+ 'params': {k: (float(v) if isinstance(v, (np.floating, float)) else v)
1067
+ for k, v in exp.params.items()},
1068
+ 'analysis': analysis,
1069
+ }
1070
+
1071
+ # =========================================================================
1072
+ # W1 VERDICT
1073
+ # =========================================================================
1074
+ print("\n" + "=" * 70)
1075
+ print("W1: MULTI-QUBIT GENERALIZATION")
1076
+ print("=" * 70)
1077
+
1078
+ w1_qubits = hw_meta['w1_qubits']
1079
+
1080
+ print(f"\n {'Qubit':>5} | {'T1(us)':>6} | {'MeasErr':>7} | {'Std I':>6} | {'Zeno I':>7} | "
1081
+ f"{'Std X':>6} | {'Zeno X':>7} | {'Zeno-Std I':>10} | {'Zeno-Std X':>10}")
1082
+ print(" " + "-" * 95)
1083
+
1084
+ improvements_I = []
1085
+ improvements_X = []
1086
+
1087
+ for qi in w1_qubits:
1088
+ std_I = results_data.get(f'w1_q{qi}_I_standard', {}).get('analysis', {}).get('fidelity', 0)
1089
+ zeno_I = results_data.get(f'w1_q{qi}_I_zeno', {}).get('analysis', {}).get('fidelity_excess', 0)
1090
+ std_X = results_data.get(f'w1_q{qi}_X_standard', {}).get('analysis', {}).get('fidelity', 0)
1091
+ zeno_X = results_data.get(f'w1_q{qi}_X_zeno', {}).get('analysis', {}).get('fidelity_excess', 0)
1092
+
1093
+ t1 = hw_meta['qubit_properties'][str(qi)]['T1_us']
1094
+ merr = hw_meta['qubit_properties'][str(qi)]['meas_error']
1095
+
1096
+ imp_I = zeno_I - std_I
1097
+ imp_X = zeno_X - std_X
1098
+ improvements_I.append(imp_I)
1099
+ improvements_X.append(imp_X)
1100
+
1101
+ print(f" Q{qi:>3} | {t1:6.1f} | {merr:7.4f} | {std_I:6.4f} | {zeno_I:7.4f} | "
1102
+ f"{std_X:6.4f} | {zeno_X:7.4f} | {imp_I:+10.4f} | {imp_X:+10.4f}")
1103
+
1104
+ mean_imp_I = np.mean(improvements_I) if improvements_I else 0
1105
+ mean_imp_X = np.mean(improvements_X) if improvements_X else 0
1106
+ std_imp_I = np.std(improvements_I) if improvements_I else 0
1107
+ std_imp_X = np.std(improvements_X) if improvements_X else 0
1108
+ all_positive_I = all(i > 0 for i in improvements_I)
1109
+ all_positive_X = all(i > 0 for i in improvements_X)
1110
+ any_negative = any(i < -0.02 for i in improvements_I + improvements_X)
1111
+
1112
+ print(f"\n Mean Zeno improvement (I): {mean_imp_I:+.4f} +/- {std_imp_I:.4f}")
1113
+ print(f" Mean Zeno improvement (X): {mean_imp_X:+.4f} +/- {std_imp_X:.4f}")
1114
+ print(f" All positive (I): {all_positive_I}, All positive (X): {all_positive_X}")
1115
+
1116
+ if all_positive_I and all_positive_X:
1117
+ w1_verdict = "PASS: Zeno advantage holds across all tested qubits. Single-qubit concern mitigated."
1118
+ elif any_negative:
1119
+ w1_verdict = "FAIL: Some qubits show Zeno DISADVANTAGE. Results are qubit-dependent."
1120
+ else:
1121
+ w1_verdict = "PARTIAL: Zeno advantage inconsistent across qubits. Qubit selection matters."
1122
+
1123
+ print(f"\n VERDICT: {w1_verdict}")
1124
+
1125
+ # =========================================================================
1126
+ # W3 VERDICT
1127
+ # =========================================================================
1128
+ print("\n" + "=" * 70)
1129
+ print("W3: ZERO-NOISE EXTRAPOLATION COMPARISON")
1130
+ print("=" * 70)
1131
+
1132
+ for gate_name in ['I', 'X']:
1133
+ print(f"\n --- {gate_name} gate ---")
1134
+ noise_levels = []
1135
+ fidelities = []
1136
+
1137
+ for n_folds in [0, 1, 2, 3]:
1138
+ noise_level = 2 * n_folds + 1
1139
+ key = f"w3_{gate_name}_zne_{noise_level}x"
1140
+ fid = results_data.get(key, {}).get('analysis', {}).get('fidelity', 0)
1141
+ noise_levels.append(noise_level)
1142
+ fidelities.append(fid)
1143
+ print(f" {noise_level}x noise: fidelity = {fid:.4f}")
1144
+
1145
+ # Richardson extrapolation to 0x noise using linear fit on first 3 points
1146
+ if len(fidelities) >= 3:
1147
+ # Linear extrapolation from 1x and 3x
1148
+ f1 = fidelities[0] # 1x
1149
+ f3 = fidelities[1] # 3x
1150
+ zne_linear = (3 * f1 - f3) / 2
1151
+
1152
+ # Quadratic extrapolation from 1x, 3x, 5x
1153
+ f5 = fidelities[2] # 5x
1154
+ # Lagrange interpolation at x=0
1155
+ zne_quad = (15 * f1 - 10 * f3 + 3 * f5) / 8
1156
+
1157
+ print(f" ZNE (linear): {zne_linear:.4f}")
1158
+ print(f" ZNE (quadratic): {zne_quad:.4f}")
1159
+
1160
+ # Compare against Zeno result from existing data
1161
+ # For identity: ideal=1.0; for X: ideal=1.0 (we measure P(0) after undo)
1162
+ print(f" Ideal: 1.0000")
1163
+
1164
+ # Get existing Zeno result for this gate
1165
+ zeno_key = f"w1_q0_{gate_name}_zeno"
1166
+ zeno_fid = results_data.get(zeno_key, {}).get('analysis', {}).get('fidelity_excess', 0)
1167
+ zeno_hard = results_data.get(zeno_key, {}).get('analysis', {}).get('fidelity_hard_ps', 0)
1168
+ zeno_sr = results_data.get(zeno_key, {}).get('analysis', {}).get('success_rate', 0)
1169
+
1170
+ if zeno_fid > 0:
1171
+ zeno_yield = zeno_fid * (1.0 - (1.0 - zeno_sr))
1172
+ # ZNE uses all shots (100% utilization)
1173
+ print(f" Zeno (excess-flip): {zeno_fid:.4f} (success rate: {zeno_sr:.4f})")
1174
+ print(f" Zeno (hard PS): {zeno_hard:.4f}")
1175
+
1176
+ best_zne = max(zne_linear, zne_quad)
1177
+ best_zne = min(best_zne, 1.0) # cap at 1
1178
+
1179
+ print(f"\n ZNE best: {best_zne:.4f} (100% utilization, yield={best_zne:.4f})")
1180
+ print(f" Zeno best: {zeno_fid:.4f} (utilization varies)")
1181
+
1182
+ # Overall W3 verdict based on comparison
1183
+ w3_results = {}
1184
+ for gate_name in ['I', 'X']:
1185
+ fids = []
1186
+ for n_folds in [0, 1, 2, 3]:
1187
+ key = f"w3_{gate_name}_zne_{2*n_folds+1}x"
1188
+ fids.append(results_data.get(key, {}).get('analysis', {}).get('fidelity', 0))
1189
+
1190
+ if len(fids) >= 3:
1191
+ zne_lin = (3 * fids[0] - fids[1]) / 2
1192
+ zne_quad = (15 * fids[0] - 10 * fids[1] + 3 * fids[2]) / 8
1193
+ w3_results[gate_name] = {
1194
+ 'raw_fidelities': fids,
1195
+ 'zne_linear': float(min(zne_lin, 1.0)),
1196
+ 'zne_quadratic': float(min(zne_quad, 1.0)),
1197
+ }
1198
+
1199
+ zne_best = max(
1200
+ max(r.get('zne_linear', 0), r.get('zne_quadratic', 0))
1201
+ for r in w3_results.values()
1202
+ ) if w3_results else 0
1203
+
1204
+ zeno_q0_X = results_data.get('w1_q0_X_zeno', {}).get('analysis', {}).get('fidelity_excess', 0)
1205
+
1206
+ if zne_best > zeno_q0_X + 0.02:
1207
+ w3_verdict = f"CONFIRMED: ZNE ({zne_best:.4f}) beats Zeno ({zeno_q0_X:.4f}) at 100% utilization."
1208
+ elif abs(zne_best - zeno_q0_X) < 0.02:
1209
+ w3_verdict = f"MIXED: ZNE ({zne_best:.4f}) and Zeno ({zeno_q0_X:.4f}) are comparable."
1210
+ else:
1211
+ w3_verdict = f"REFUTED: Zeno ({zeno_q0_X:.4f}) beats ZNE ({zne_best:.4f}) even at full utilization."
1212
+
1213
+ print(f"\n VERDICT: {w3_verdict}")
1214
+
1215
+ # =========================================================================
1216
+ # W6 VERDICT
1217
+ # =========================================================================
1218
+ print("\n" + "=" * 70)
1219
+ print("W6: COMPUTATION BETWEEN MEASUREMENTS")
1220
+ print("=" * 70)
1221
+
1222
+ std_fid = results_data.get('w6_standard', {}).get('analysis', {}).get('fidelity', 0)
1223
+ print(f"\n Standard Ry(pi/2): {std_fid:.4f}")
1224
+
1225
+ print(f"\n {'Work gates':>10} | {'Zeno(excess)':>12} | {'Zeno(hard)':>10} | "
1226
+ f"{'Depth-matched':>13} | {'Delay':>6} | {'Zeno-Std':>8} | {'Zeno-Depth':>10}")
1227
+ print(" " + "-" * 85)
1228
+
1229
+ zeno_advantages = []
1230
+ for work_gates in [0, 1, 2, 4]:
1231
+ zk = f"w6_zeno_work{work_gates}"
1232
+ dk = f"w6_depth_work{work_gates}"
1233
+ dlk = f"w6_delay_work{work_gates}"
1234
+
1235
+ za = results_data.get(zk, {}).get('analysis', {})
1236
+ da = results_data.get(dk, {}).get('analysis', {})
1237
+ dla = results_data.get(dlk, {}).get('analysis', {})
1238
+
1239
+ z_excess = za.get('fidelity_excess', 0)
1240
+ z_hard = za.get('fidelity_hard_ps', 0)
1241
+ d_fid = da.get('fidelity', 0)
1242
+ dl_fid = dla.get('fidelity', 0)
1243
+
1244
+ adv_vs_std = z_excess - std_fid
1245
+ adv_vs_depth = z_excess - d_fid
1246
+ zeno_advantages.append(adv_vs_std)
1247
+
1248
+ print(f" {work_gates:>10} | {z_excess:12.4f} | {z_hard:10.4f} | "
1249
+ f"{d_fid:13.4f} | {dl_fid:6.4f} | {adv_vs_std:+8.4f} | {adv_vs_depth:+10.4f}")
1250
+
1251
+ # How fast does advantage decay with work?
1252
+ if len(zeno_advantages) >= 2:
1253
+ adv_0 = zeno_advantages[0] # 0 work gates
1254
+ adv_4 = zeno_advantages[-1] # 4 work gates
1255
+ decay = adv_0 - adv_4
1256
+
1257
+ print(f"\n Advantage at 0 work gates: {adv_0:+.4f}")
1258
+ print(f" Advantage at 4 work gates: {adv_4:+.4f}")
1259
+ print(f" Decay: {decay:.4f}")
1260
+
1261
+ if adv_4 < -0.01:
1262
+ w6_verdict = "CONFIRMED: Zeno advantage vanishes with interleaved computation. Practical utility limited."
1263
+ elif adv_4 < adv_0 * 0.5:
1264
+ w6_verdict = "PARTIAL: Advantage decays >50% with 4 gate pairs. Degrades with practical workloads."
1265
+ else:
1266
+ w6_verdict = "REFUTED: Advantage survives interleaved computation. Practical use viable."
1267
+ else:
1268
+ w6_verdict = "INCONCLUSIVE: Insufficient data."
1269
+
1270
+ print(f"\n VERDICT: {w6_verdict}")
1271
+
1272
+ return results_data, {
1273
+ 'W1': {'verdict': w1_verdict, 'improvements_I': [float(x) for x in improvements_I],
1274
+ 'improvements_X': [float(x) for x in improvements_X]},
1275
+ 'W3': {'verdict': w3_verdict, **w3_results},
1276
+ 'W6': {'verdict': w6_verdict, 'advantages': [float(x) for x in zeno_advantages]},
1277
+ }
1278
+
1279
+
1280
+ # =============================================================================
1281
+ # MAIN
1282
+ # =============================================================================
1283
+
1284
+ def main():
1285
+ print("=" * 70)
1286
+ print("WEAKNESS TESTS — ALL SIX")
1287
+ print("=" * 70)
1288
+
1289
+ all_results = {}
1290
+
1291
+ # -----------------------------------------------------------------
1292
+ # PHASE 1: OFFLINE TESTS (zero QPU cost)
1293
+ # -----------------------------------------------------------------
1294
+ print("\n\n" + "#" * 70)
1295
+ print("# PHASE 1: OFFLINE TESTS (zero QPU cost)")
1296
+ print("#" * 70)
1297
+
1298
+ w2_results = test_w2_measurement_independence()
1299
+ all_results['W2'] = w2_results
1300
+
1301
+ w4_results = test_w4_vqe_fidelity_constancy()
1302
+ all_results['W4'] = w4_results
1303
+
1304
+ w5_results = test_w5_ml_vs_heuristics()
1305
+ all_results['W5'] = w5_results
1306
+
1307
+ # -----------------------------------------------------------------
1308
+ # PHASE 2: HARDWARE TESTS (single Batch)
1309
+ # -----------------------------------------------------------------
1310
+ print("\n\n" + "#" * 70)
1311
+ print("# PHASE 2: HARDWARE TESTS (single Batch job)")
1312
+ print("#" * 70)
1313
+
1314
+ service = QiskitRuntimeService(channel="ibm_cloud", instance="claude")
1315
+ usage_before = check_usage(service)
1316
+ log(f"Usage: {usage_before['total']}s / 600s ({usage_before['percentage']:.1f}%)")
1317
+ log(f"Remaining: {usage_before['remaining']}s")
1318
+
1319
+ if usage_before['remaining'] < 30:
1320
+ log("Less than 30s remaining. Skipping hardware tests.")
1321
+ # Save offline results only
1322
+ outfile = TESTS_DIR / 'weakness_tests.json'
1323
+ with open(outfile, 'w') as f:
1324
+ json.dump(all_results, f, indent=2, default=str)
1325
+ log(f"Saved offline results: {outfile}")
1326
+ return
1327
+
1328
+ backend = service.backend("ibm_torino")
1329
+ log(f"Backend: {backend.name} ({backend.num_qubits}q)")
1330
+
1331
+ experiments, hw_meta = build_hardware_experiments(backend)
1332
+ log(f"Total circuits: {len(experiments)}")
1333
+
1334
+ # Transpile
1335
+ log("Transpiling...")
1336
+ pm = generate_preset_pass_manager(backend=backend, optimization_level=1)
1337
+
1338
+ transpiled = []
1339
+ valid_experiments = []
1340
+
1341
+ for exp in experiments:
1342
+ try:
1343
+ tc = pm.run(exp.circuit)
1344
+ transpiled.append(tc)
1345
+ valid_experiments.append(exp)
1346
+ except Exception as e:
1347
+ log(f"ERROR transpiling {exp.name}: {e}")
1348
+
1349
+ log(f"Transpiled: {len(transpiled)}/{len(experiments)}")
1350
+
1351
+ if not transpiled:
1352
+ log("No circuits transpiled successfully. Aborting hardware tests.")
1353
+ return
1354
+
1355
+ depths = [tc.depth() for tc in transpiled]
1356
+ log(f"Depths: min={min(depths)}, max={max(depths)}, median={sorted(depths)[len(depths)//2]}")
1357
+
1358
+ # Submit single batch
1359
+ log("Submitting batch...")
1360
+ start_time = datetime.now(timezone.utc)
1361
+ shots = 4096
1362
+
1363
+ with Batch(backend=backend) as batch:
1364
+ sampler = SamplerV2(mode=batch)
1365
+ job = sampler.run(transpiled, shots=shots)
1366
+ log(f"Job ID: {job.job_id()}")
1367
+ log("Waiting...")
1368
+ job.wait_for_final_state()
1369
+
1370
+ end_time = datetime.now(timezone.utc)
1371
+ wall_time = (end_time - start_time).total_seconds()
1372
+ log(f"Done. Wall time: {wall_time:.1f}s, QPU: {job.usage() or 0}s")
1373
+
1374
+ result = job.result()
1375
+
1376
+ hw_results, hw_verdicts = analyze_hardware_results(valid_experiments, result, hw_meta)
1377
+
1378
+ all_results['W1'] = hw_verdicts['W1']
1379
+ all_results['W3'] = hw_verdicts['W3']
1380
+ all_results['W6'] = hw_verdicts['W6']
1381
+ all_results['hardware_meta'] = {
1382
+ **hw_meta,
1383
+ 'job_id': job.job_id(),
1384
+ 'usage_seconds': job.usage() or 0,
1385
+ 'wall_time_seconds': wall_time,
1386
+ 'n_circuits': len(transpiled),
1387
+ 'shots': shots,
1388
+ 'timestamp': start_time.isoformat(),
1389
+ }
1390
+
1391
+ # -----------------------------------------------------------------
1392
+ # SAVE & SUMMARY
1393
+ # -----------------------------------------------------------------
1394
+ outfile = TESTS_DIR / 'weakness_tests.json'
1395
+ with open(outfile, 'w') as f:
1396
+ json.dump(all_results, f, indent=2, default=str)
1397
+ log(f"Saved: {outfile}")
1398
+
1399
+ print("\n\n" + "=" * 70)
1400
+ print("SUMMARY OF ALL SIX WEAKNESS TESTS")
1401
+ print("=" * 70)
1402
+
1403
+ for w_id in ['W1', 'W2', 'W3', 'W4', 'W5', 'W6']:
1404
+ w = all_results.get(w_id, {})
1405
+ verdict = w.get('verdict', 'N/A')
1406
+ if isinstance(w, dict) and 'verdict' not in w:
1407
+ # Multi-sub-test — collect verdicts
1408
+ sub_verdicts = [v.get('verdict', '') for k, v in w.items() if isinstance(v, dict) and 'verdict' in v]
1409
+ verdict = ' | '.join(sub_verdicts) if sub_verdicts else 'N/A'
1410
+ print(f"\n {w_id}: {verdict}")
1411
+
1412
+ usage_after = check_usage(service)
1413
+ log(f"\nUsage after: {usage_after['total']}s / 600s ({usage_after['percentage']:.1f}%)")
1414
+ log(f"This job: {job.usage() or 0}s")
1415
+
1416
+
1417
+ if __name__ == '__main__':
1418
+ try:
1419
+ main()
1420
+ except KeyboardInterrupt:
1421
+ log("Interrupted.")
1422
+ sys.exit(1)
1423
+ except Exception as e:
1424
+ log(f"FATAL: {e}")
1425
+ import traceback
1426
+ traceback.print_exc()
1427
+ sys.exit(1)
tests/weakness_tests.json ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "W2": {
3
+ "w2a_transition_analysis": {
4
+ "n_shots": 500,
5
+ "mean_transitions": 2.692,
6
+ "expected_transitions": 6.344517230987549,
7
+ "transition_ratio": 0.4243033633594498,
8
+ "mean_run_length": 8.66738894907909,
9
+ "transition_autocorrelation": 0.4119721980294112,
10
+ "t_stat": 53.762899612456586,
11
+ "p_value": 1.3474201297243222e-178,
12
+ "verdict": "FAIL: Transitions themselves are correlated. Error events cluster."
13
+ },
14
+ "w2b_binomial_gof": {
15
+ "n_meas": 32,
16
+ "p_meas": 0.11572265625,
17
+ "total_shots": 4096,
18
+ "chi2": 15323.0839652716,
19
+ "p_value": 0.0,
20
+ "bins_tested": 11,
21
+ "verdict": "FAIL: Flip counts deviate from Binomial. Backaction creates correlated runs."
22
+ },
23
+ "w2c_monotonicity": {
24
+ "fidelity_by_flips": [
25
+ [
26
+ 0,
27
+ 0.9686847599164927
28
+ ],
29
+ [
30
+ 1,
31
+ 0.9555382215288611
32
+ ],
33
+ [
34
+ 2,
35
+ 0.9526952695269527
36
+ ],
37
+ [
38
+ 3,
39
+ 0.9392523364485982
40
+ ],
41
+ [
42
+ 4,
43
+ 0.8947368421052632
44
+ ],
45
+ [
46
+ 5,
47
+ 0.8113207547169812
48
+ ],
49
+ [
50
+ 6,
51
+ 0.7333333333333333
52
+ ],
53
+ [
54
+ 7,
55
+ 0.36363636363636365
56
+ ],
57
+ [
58
+ 8,
59
+ 0.5
60
+ ],
61
+ [
62
+ 12,
63
+ 0.4
64
+ ],
65
+ [
66
+ 17,
67
+ 0.6666666666666666
68
+ ],
69
+ [
70
+ 24,
71
+ 0.3333333333333333
72
+ ],
73
+ [
74
+ 25,
75
+ 0.35714285714285715
76
+ ],
77
+ [
78
+ 26,
79
+ 0.2727272727272727
80
+ ],
81
+ [
82
+ 27,
83
+ 0.20833333333333334
84
+ ],
85
+ [
86
+ 28,
87
+ 0.16666666666666666
88
+ ],
89
+ [
90
+ 29,
91
+ 0.2857142857142857
92
+ ],
93
+ [
94
+ 30,
95
+ 0.14705882352941177
96
+ ],
97
+ [
98
+ 31,
99
+ 0.07407407407407407
100
+ ]
101
+ ],
102
+ "violations": 4,
103
+ "verdict": "FAIL: 4 monotonicity violations. Flip count is a poor fidelity predictor."
104
+ }
105
+ },
106
+ "W4": {
107
+ "w4_fidelity_constancy": {
108
+ "n_thetas": 9,
109
+ "mean_fidelity": 0.5163154410848451,
110
+ "std_fidelity": 0.3394285161934174,
111
+ "spread": 0.9516129032258065,
112
+ "F_ratio": 1062.9229626856127,
113
+ "global_rmse": 18.986229211309393,
114
+ "pertheta_rmse": 1.2521720627384025,
115
+ "verdict": "FAIL: Fidelity varies >8pp. Per-theta calibration needed."
116
+ }
117
+ },
118
+ "W5": {
119
+ "w5_ml_vs_heuristics": {
120
+ "n_trajectories": 4096,
121
+ "strategies": {
122
+ "hard_k0": {
123
+ "fidelity": 0.9680624556422995,
124
+ "utilization": 0.68798828125,
125
+ "effective_yield": 0.666015625
126
+ },
127
+ "soft_k1": {
128
+ "fidelity": 0.9652852529601722,
129
+ "utilization": 0.9072265625,
130
+ "effective_yield": 0.875732421875
131
+ },
132
+ "soft_k2": {
133
+ "fidelity": 0.9634369287020109,
134
+ "utilization": 0.934814453125,
135
+ "effective_yield": 0.900634765625
136
+ },
137
+ "exp_k": {
138
+ "fidelity": 0.9663760786147975,
139
+ "utilization": 0.7726615289055263,
140
+ "effective_yield": 0.7466816184002365
141
+ },
142
+ "excess_flip": {
143
+ "fidelity": 0.966339701762272,
144
+ "utilization": 0.7747182690079382,
145
+ "effective_yield": 0.7486410210229146
146
+ },
147
+ "early_penalty": {
148
+ "fidelity": 0.9662011359170656,
149
+ "utilization": 0.7917104068840887,
150
+ "effective_yield": 0.7649514944487686
151
+ },
152
+ "pos0_aware": {
153
+ "fidelity": 0.964131156245851,
154
+ "utilization": 0.9195556640625009,
155
+ "effective_yield": 0.8865722656250004
156
+ },
157
+ "uniform": {
158
+ "fidelity": 0.912109375,
159
+ "utilization": 1.0,
160
+ "effective_yield": 0.912109375
161
+ }
162
+ },
163
+ "best_simple_yield": 0.900634765625,
164
+ "exp_k_yield": 0.7466816184002365,
165
+ "gap": -0.1539531472247635,
166
+ "verdict": "REFUTED: Simple heuristic actually beats exp(-k). Position awareness helps."
167
+ }
168
+ },
169
+ "W1": {
170
+ "verdict": "FAIL: Some qubits show Zeno DISADVANTAGE. Results are qubit-dependent.",
171
+ "improvements_I": [
172
+ 0.0452231252327957,
173
+ 0.0022516596077793993,
174
+ 0.007394570319754101,
175
+ 0.0046508063074586214,
176
+ -9.731657901379531e-05
177
+ ],
178
+ "improvements_X": [
179
+ -0.011832915012489065,
180
+ -0.025856505263611496,
181
+ -0.022231385683244342,
182
+ -0.021130844386844427,
183
+ -0.023924039129208152
184
+ ]
185
+ },
186
+ "W3": {
187
+ "verdict": "MIXED: ZNE (0.8989) and Zeno (0.8859) are comparable.",
188
+ "I": {
189
+ "raw_fidelities": [
190
+ 0.898193359375,
191
+ 0.896728515625,
192
+ 0.88623046875,
193
+ 0.890869140625
194
+ ],
195
+ "zne_linear": 0.89892578125,
196
+ "zne_quadratic": 0.895538330078125
197
+ },
198
+ "X": {
199
+ "raw_fidelities": [
200
+ 0.893310546875,
201
+ 0.90185546875,
202
+ 0.899169921875,
203
+ 0.906494140625
204
+ ],
205
+ "zne_linear": 0.8890380859375,
206
+ "zne_quadratic": 0.88482666015625
207
+ }
208
+ },
209
+ "W6": {
210
+ "verdict": "REFUTED: Advantage survives interleaved computation. Practical use viable.",
211
+ "advantages": [
212
+ 0.041001923381343786,
213
+ 0.028494706439102346,
214
+ 0.024268913015265237,
215
+ 0.027480862169691034
216
+ ]
217
+ },
218
+ "hardware_meta": {
219
+ "w1_qubits": [
220
+ 0,
221
+ 131,
222
+ 85,
223
+ 95,
224
+ 37
225
+ ],
226
+ "qubit_properties": {
227
+ "0": {
228
+ "T1_us": 115.2263264704152,
229
+ "meas_error": 0.11572265625
230
+ },
231
+ "131": {
232
+ "T1_us": 332.54033018370484,
233
+ "meas_error": 0.017578125
234
+ },
235
+ "85": {
236
+ "T1_us": 3.5656842137414944,
237
+ "meas_error": 0.045654296875
238
+ },
239
+ "95": {
240
+ "T1_us": 174.3273204280589,
241
+ "meas_error": 0.026611328125
242
+ },
243
+ "37": {
244
+ "T1_us": 59.919350992670644,
245
+ "meas_error": 0.010009765625
246
+ }
247
+ },
248
+ "meas_duration_dt": 390,
249
+ "meas_error_q0": 0.11572265625,
250
+ "dt_ns": 4.0,
251
+ "job_id": "d6jkidm33pjc73dm3upg",
252
+ "usage_seconds": 56,
253
+ "wall_time_seconds": 282.760999,
254
+ "n_circuits": 51,
255
+ "shots": 4096,
256
+ "timestamp": "2026-03-03T20:48:48.416591+00:00"
257
+ }
258
+ }
zeno_interval.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Zeno Interval — Vary the inter-measurement gap.
3
+
4
+ N=32 fixed. Insert deliberate delays of 0, 5, 10, 20, 50, 100μs between
5
+ each measurement. At 100μs the gap approaches T1 — Zeno protection
6
+ should collapse. Maps the phase boundary between Zeno-protected and
7
+ unprotected thermalization.
8
+
9
+ Theory predicts: fidelity depends on the ratio of measurement rate to
10
+ decoherence rate. When inter-measurement interval << T1, Zeno wins.
11
+ When interval ≈ T1, the qubit thermalizes between measurements and
12
+ Zeno can't help.
13
+ """
14
+
15
+ import json
16
+ import sys
17
+ from datetime import datetime, timezone
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ import numpy as np
21
+ from scipy.special import comb
22
+
23
+ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
24
+ from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
25
+ from qiskit_ibm_runtime import (
26
+ QiskitRuntimeService,
27
+ SamplerV2,
28
+ Batch,
29
+ )
30
+
31
+
32
+ DATA_DIR = Path("D:/qiskit-zenodragging")
33
+ N_MEAS = 32
34
+
35
+
36
+ @dataclass
37
+ class ExperimentConfig:
38
+ name: str
39
+ circuit: QuantumCircuit
40
+ category: str
41
+ params: dict
42
+
43
+
44
+ def log(msg, level=0):
45
+ indent = " " * level
46
+ ts = datetime.now().strftime("%H:%M:%S")
47
+ print(f"[{ts}] {indent}{msg}")
48
+
49
+
50
+ def check_usage(service):
51
+ jobs = list(service.jobs(limit=200))
52
+ now = datetime.now(timezone.utc)
53
+ month_start = datetime(now.year, now.month, 1, tzinfo=timezone.utc)
54
+ total = 0
55
+ for j in jobs:
56
+ u = j.usage() or 0
57
+ try:
58
+ m = j.metrics()
59
+ ts = m.get('timestamps', {}).get('created', '')
60
+ if ts:
61
+ dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
62
+ if dt >= month_start:
63
+ total += u
64
+ except Exception:
65
+ pass
66
+ return {"total": total, "remaining": 600 - total, "percentage": 100 * total / 600}
67
+
68
+
69
+ def build_zeno_with_gap(theta, n_meas, gap_dt):
70
+ """Zeno drag with deliberate delay between each measurement."""
71
+ qr = QuantumRegister(1, 'q')
72
+ cr = ClassicalRegister(n_meas + 1, 'c')
73
+ qc = QuantumCircuit(qr, cr)
74
+
75
+ for k in range(1, n_meas + 1):
76
+ theta_k = k * theta / n_meas
77
+ qc.ry(-theta_k, 0)
78
+ qc.measure(0, k - 1)
79
+ qc.ry(theta_k, 0)
80
+ if gap_dt > 0 and k < n_meas:
81
+ qc.delay(gap_dt, 0, unit='dt')
82
+
83
+ qc.ry(-theta, 0)
84
+ qc.measure(0, n_meas)
85
+ return qc
86
+
87
+
88
+ def build_identity_zeno_with_gap(n_meas, gap_dt):
89
+ """Identity Zeno with deliberate delay between each measurement."""
90
+ qr = QuantumRegister(1, 'q')
91
+ cr = ClassicalRegister(n_meas + 1, 'c')
92
+ qc = QuantumCircuit(qr, cr)
93
+
94
+ for k in range(n_meas):
95
+ qc.measure(0, k)
96
+ if gap_dt > 0 and k < n_meas - 1:
97
+ qc.delay(gap_dt, 0, unit='dt')
98
+
99
+ qc.measure(0, n_meas)
100
+ return qc
101
+
102
+
103
+ def build_delay_total(total_delay_dt):
104
+ """Pure delay for same total circuit time. Ideal = |0>."""
105
+ qc = QuantumCircuit(1, 1)
106
+ if total_delay_dt > 0:
107
+ qc.delay(total_delay_dt, 0, unit='dt')
108
+ qc.measure(0, 0)
109
+ return qc
110
+
111
+
112
+ def analyze_zeno(bitstrings, n_meas, p_meas):
113
+ total = len(bitstrings)
114
+ successful = 0
115
+ correct_given_success = 0
116
+ flip_bins = {}
117
+
118
+ for bs in bitstrings:
119
+ if len(bs) < n_meas + 1:
120
+ continue
121
+
122
+ final = bs[0]
123
+ intermediate = bs[1:n_meas + 1]
124
+ n_flips = sum(1 for b in intermediate if b == '1')
125
+
126
+ if n_flips not in flip_bins:
127
+ flip_bins[n_flips] = {'total': 0, 'correct': 0}
128
+ flip_bins[n_flips]['total'] += 1
129
+ if final == '0':
130
+ flip_bins[n_flips]['correct'] += 1
131
+
132
+ if n_flips == 0:
133
+ successful += 1
134
+ if final == '0':
135
+ correct_given_success += 1
136
+
137
+ success_rate = successful / total if total > 0 else 0
138
+ fidelity_hard = correct_given_success / successful if successful > 0 else 0
139
+
140
+ expected_meas_flips = n_meas * p_meas
141
+
142
+ # Excess-flip weighting
143
+ w_c, w_t = 0, 0
144
+ for nf, data in flip_bins.items():
145
+ excess = max(0, nf - expected_meas_flips)
146
+ w = np.exp(-excess)
147
+ w_c += w * data['correct']
148
+ w_t += w * data['total']
149
+ fid_excess = w_c / w_t if w_t > 0 else 0
150
+
151
+ # Likelihood ratio
152
+ wl_c, wl_t = 0, 0
153
+ for nf, data in flip_bins.items():
154
+ if nf <= n_meas:
155
+ p_target = comb(n_meas, nf, exact=True) * (p_meas ** nf) * ((1 - p_meas) ** (n_meas - nf))
156
+ p_random = comb(n_meas, nf, exact=True) * (0.5 ** n_meas)
157
+ w = min(p_target / p_random, 1e10) if p_random > 0 else 0
158
+ else:
159
+ w = 0
160
+ wl_c += w * data['correct']
161
+ wl_t += w * data['total']
162
+ fid_likelihood = wl_c / wl_t if wl_t > 0 else 0
163
+
164
+ all_flips = []
165
+ for nf, data in flip_bins.items():
166
+ all_flips.extend([nf] * data['total'])
167
+ mean_flips = np.mean(all_flips) if all_flips else 0
168
+ std_flips = np.std(all_flips) if all_flips else 0
169
+
170
+ return {
171
+ 'total': total,
172
+ 'successful': successful,
173
+ 'success_rate': success_rate,
174
+ 'fidelity_hard_ps': fidelity_hard,
175
+ 'fidelity_excess': fid_excess,
176
+ 'fidelity_likelihood': fid_likelihood,
177
+ 'expected_meas_flips': expected_meas_flips,
178
+ 'mean_flips': mean_flips,
179
+ 'std_flips': std_flips,
180
+ 'flip_distribution': {str(k): v for k, v in sorted(flip_bins.items())},
181
+ 'type': 'zeno',
182
+ }
183
+
184
+
185
+ def analyze_standard(bitstrings):
186
+ total = len(bitstrings)
187
+ zeros = sum(1 for b in bitstrings if b[-1] == '0')
188
+ return {'total': total, 'fidelity': zeros / total, 'type': 'standard'}
189
+
190
+
191
+ def main():
192
+ print("=" * 70)
193
+ print("ZENO INTERVAL — VARY INTER-MEASUREMENT GAP")
194
+ print("=" * 70)
195
+
196
+ service = QiskitRuntimeService(channel="ibm_cloud", instance="claude")
197
+
198
+ usage_before = check_usage(service)
199
+ log(f"Usage: {usage_before['total']}s / 600s ({usage_before['percentage']:.1f}%)")
200
+ log(f"Remaining: {usage_before['remaining']}s")
201
+
202
+ if usage_before['remaining'] < 30:
203
+ log("Less than 30s remaining. Aborting.")
204
+ return
205
+
206
+ backend = service.backend("ibm_torino")
207
+ log(f"Backend: {backend.name} ({backend.num_qubits}q)")
208
+
209
+ dt = backend.dt
210
+ target_obj = backend.target
211
+ meas_props = target_obj['measure'][(0,)]
212
+ meas_duration_s = meas_props.duration
213
+ meas_duration_dt = int(meas_duration_s / dt)
214
+ meas_error = meas_props.error
215
+
216
+ props = backend.qubit_properties(0)
217
+ T1 = props.t1
218
+ T2 = props.t2
219
+
220
+ log(f"Measurement: {meas_duration_s*1e6:.3f} us ({meas_duration_dt} dt), error={meas_error:.4f}")
221
+ log(f"Qubit 0: T1={T1*1e6:.1f} us, T2={T2*1e6:.1f} us")
222
+ log(f"dt = {dt*1e9:.1f} ns")
223
+
224
+ # Gap values in microseconds
225
+ gap_us_values = [0, 5, 10, 20, 50, 100]
226
+ theta = np.pi
227
+ shots = 4096
228
+
229
+ print(f"\nN = {N_MEAS} fixed")
230
+ print(f"\nExperiment plan:")
231
+ print(f"{'Gap(us)':>7} | {'Interval(us)':>12} | {'Interval/T1':>11} | {'Total(us)':>9} | {'Total/T1':>8}")
232
+ print("-" * 55)
233
+ for gap_us in gap_us_values:
234
+ interval = meas_duration_s * 1e6 + gap_us
235
+ total = N_MEAS * interval
236
+ print(f"{gap_us:7.0f} | {interval:12.1f} | {interval / (T1*1e6):11.3f} | {total:9.1f} | {total / (T1*1e6):8.2f}")
237
+
238
+ all_experiments = []
239
+
240
+ for gap_us in gap_us_values:
241
+ gap_s = gap_us * 1e-6
242
+ gap_dt = int(gap_s / dt)
243
+ interval_us = meas_duration_s * 1e6 + gap_us
244
+ total_time_us = N_MEAS * interval_us
245
+
246
+ # X Zeno with gap
247
+ all_experiments.append(ExperimentConfig(
248
+ name=f"x_zeno_gap{gap_us}",
249
+ circuit=build_zeno_with_gap(theta, N_MEAS, gap_dt),
250
+ category="x_zeno",
251
+ params={'gate': 'X', 'theta': theta, 'n_meas': N_MEAS,
252
+ 'gap_us': gap_us, 'gap_dt': gap_dt,
253
+ 'interval_us': interval_us,
254
+ 'interval_over_T1': interval_us / (T1 * 1e6),
255
+ 'total_time_us': total_time_us,
256
+ 'T1_multiple': total_time_us / (T1 * 1e6)},
257
+ ))
258
+
259
+ # Identity Zeno with gap
260
+ all_experiments.append(ExperimentConfig(
261
+ name=f"identity_zeno_gap{gap_us}",
262
+ circuit=build_identity_zeno_with_gap(N_MEAS, gap_dt),
263
+ category="identity_zeno",
264
+ params={'gate': 'I', 'theta': 0, 'n_meas': N_MEAS,
265
+ 'gap_us': gap_us, 'gap_dt': gap_dt,
266
+ 'interval_us': interval_us,
267
+ 'interval_over_T1': interval_us / (T1 * 1e6),
268
+ 'total_time_us': total_time_us,
269
+ 'T1_multiple': total_time_us / (T1 * 1e6)},
270
+ ))
271
+
272
+ # Delay-matched (same total time, no measurements)
273
+ total_delay_dt = int(total_time_us * 1e-6 / dt)
274
+ all_experiments.append(ExperimentConfig(
275
+ name=f"delay_gap{gap_us}",
276
+ circuit=build_delay_total(total_delay_dt),
277
+ category="delay",
278
+ params={'gate': 'I', 'theta': 0, 'n_meas': 0,
279
+ 'gap_us': gap_us,
280
+ 'total_time_us': total_time_us,
281
+ 'T1_multiple': total_time_us / (T1 * 1e6)},
282
+ ))
283
+
284
+ log(f"Total experiments: {len(all_experiments)}")
285
+
286
+ log("Transpiling...")
287
+ pm = generate_preset_pass_manager(backend=backend, optimization_level=1)
288
+
289
+ transpiled = []
290
+ for exp in all_experiments:
291
+ try:
292
+ tc = pm.run(exp.circuit)
293
+ transpiled.append(tc)
294
+ except Exception as e:
295
+ log(f"ERROR transpiling {exp.name}: {e}")
296
+ transpiled.append(None)
297
+
298
+ valid_indices = [i for i, tc in enumerate(transpiled) if tc is not None]
299
+ valid_transpiled = [transpiled[i] for i in valid_indices]
300
+ valid_experiments = [all_experiments[i] for i in valid_indices]
301
+
302
+ log(f"Transpiled: {len(valid_transpiled)}/{len(all_experiments)}")
303
+
304
+ depths = [tc.depth() for tc in valid_transpiled]
305
+ log(f"Depths: min={min(depths)}, max={max(depths)}")
306
+
307
+ for i, exp in enumerate(valid_experiments):
308
+ exp.params['transpiled_depth'] = depths[i]
309
+
310
+ log("Submitting batch...")
311
+ start_time = datetime.now(timezone.utc)
312
+
313
+ with Batch(backend=backend) as batch:
314
+ sampler = SamplerV2(mode=batch)
315
+ job = sampler.run(valid_transpiled, shots=shots)
316
+ log(f"Job ID: {job.job_id()}")
317
+ log("Waiting...")
318
+ job.wait_for_final_state()
319
+
320
+ end_time = datetime.now(timezone.utc)
321
+ wall_time = (end_time - start_time).total_seconds()
322
+ log(f"Done. Wall time: {wall_time:.1f}s, QPU: {job.usage() or 0}s")
323
+
324
+ result = job.result()
325
+ metrics = job.metrics()
326
+ results_data = {}
327
+
328
+ for i, exp in enumerate(valid_experiments):
329
+ pub_result = result[i]
330
+ data_bin = pub_result.data
331
+
332
+ if hasattr(data_bin, 'c'):
333
+ bitstrings = list(data_bin.c.get_bitstrings())
334
+ elif hasattr(data_bin, 'meas'):
335
+ bitstrings = list(data_bin.meas.get_bitstrings())
336
+ else:
337
+ cr_name = list(data_bin.keys())[0]
338
+ bitstrings = list(getattr(data_bin, cr_name).get_bitstrings())
339
+
340
+ if 'zeno' in exp.category:
341
+ analysis = analyze_zeno(bitstrings, exp.params['n_meas'], meas_error)
342
+ else:
343
+ analysis = analyze_standard(bitstrings)
344
+
345
+ results_data[exp.name] = {
346
+ 'category': exp.category,
347
+ 'params': {k: (float(v) if isinstance(v, (np.floating, float)) else v)
348
+ for k, v in exp.params.items()},
349
+ 'analysis': analysis,
350
+ 'raw_bitstrings': bitstrings[:500],
351
+ }
352
+
353
+ # Save
354
+ output = {
355
+ 'experiment': 'zeno_interval',
356
+ 'description': 'Vary inter-measurement gap to map the Zeno protection phase boundary',
357
+ 'timestamp': start_time.isoformat(),
358
+ 'backend': backend.name,
359
+ 'shots': shots,
360
+ 'n_meas': N_MEAS,
361
+ 'job_id': job.job_id(),
362
+ 'usage_seconds': job.usage() or 0,
363
+ 'wall_time_seconds': wall_time,
364
+ 'metrics': metrics,
365
+ 'hardware_timing': {
366
+ 'dt_ns': dt * 1e9,
367
+ 'measurement_duration_us': meas_duration_s * 1e6,
368
+ 'measurement_duration_dt': meas_duration_dt,
369
+ 'measurement_error': meas_error,
370
+ 'qubit_0_T1_us': T1 * 1e6,
371
+ 'qubit_0_T2_us': T2 * 1e6,
372
+ },
373
+ 'results': results_data,
374
+ }
375
+
376
+ outfile = DATA_DIR / 'results' / 'zeno_interval' / 'zeno_interval.json'
377
+ outfile.parent.mkdir(exist_ok=True)
378
+ with open(outfile, 'w') as f:
379
+ json.dump(output, f, indent=2, default=str)
380
+ log(f"Saved: {outfile}")
381
+
382
+ # =========================================================================
383
+ # THE PHASE BOUNDARY
384
+ # =========================================================================
385
+ print("\n" + "=" * 70)
386
+ print("ZENO PHASE BOUNDARY — INTER-MEASUREMENT INTERVAL")
387
+ print("=" * 70)
388
+
389
+ print(f"\nN = {N_MEAS}, Qubit 0 T1 = {T1*1e6:.1f} us")
390
+
391
+ print(f"\n{'Gap(us)':>7} | {'Interval':>8} | {'Int/T1':>6} | {'X Zeno':>7} | {'I Zeno':>7} | "
392
+ f"{'Delay':>7} | {'X-Delay':>7} | {'Total':>7} | {'×T1':>5}")
393
+ print("-" * 85)
394
+
395
+ for gap_us in gap_us_values:
396
+ xk = f"x_zeno_gap{gap_us}"
397
+ ik = f"identity_zeno_gap{gap_us}"
398
+ dk = f"delay_gap{gap_us}"
399
+
400
+ if not all(k in results_data for k in [xk, ik, dk]):
401
+ continue
402
+
403
+ xa = results_data[xk]['analysis']
404
+ ia = results_data[ik]['analysis']
405
+ da = results_data[dk]['analysis']
406
+ xp = results_data[xk]['params']
407
+
408
+ gap_xd = xa['fidelity_excess'] - da['fidelity']
409
+
410
+ print(f"{gap_us:7.0f} | {xp['interval_us']:6.1f}us | {xp['interval_over_T1']:6.3f} | "
411
+ f"{xa['fidelity_excess']:7.4f} | {ia['fidelity_excess']:7.4f} | "
412
+ f"{da['fidelity']:7.4f} | {gap_xd:+7.4f} | {xp['total_time_us']:5.0f}us | {xp['T1_multiple']:4.1f}x")
413
+
414
+ # Find crossover
415
+ print(f"\n{'=' * 70}")
416
+ print("ANALYSIS")
417
+ print(f"{'=' * 70}")
418
+
419
+ prev_gap = None
420
+ prev_advantage = None
421
+ for gap_us in gap_us_values:
422
+ xk = f"x_zeno_gap{gap_us}"
423
+ dk = f"delay_gap{gap_us}"
424
+ if xk in results_data and dk in results_data:
425
+ adv = results_data[xk]['analysis']['fidelity_excess'] - results_data[dk]['analysis']['fidelity']
426
+ if prev_advantage is not None and adv <= 0 and prev_advantage > 0:
427
+ print(f"\n Zeno advantage crosses zero between gap={prev_gap}us and gap={gap_us}us")
428
+ prev_gap = gap_us
429
+ prev_advantage = adv
430
+
431
+ # Compare 0 gap vs 100 gap
432
+ x0 = results_data.get('x_zeno_gap0', {}).get('analysis', {}).get('fidelity_excess', 0)
433
+ x100 = results_data.get('x_zeno_gap100', {}).get('analysis', {}).get('fidelity_excess', 0)
434
+ i0 = results_data.get('identity_zeno_gap0', {}).get('analysis', {}).get('fidelity_excess', 0)
435
+ i100 = results_data.get('identity_zeno_gap100', {}).get('analysis', {}).get('fidelity_excess', 0)
436
+
437
+ print(f"\n X Zeno: gap=0 → {x0:.4f}, gap=100μs → {x100:.4f}, decline: {x0-x100:.4f}")
438
+ print(f" I Zeno: gap=0 → {i0:.4f}, gap=100μs → {i100:.4f}, decline: {i0-i100:.4f}")
439
+
440
+ usage_after = check_usage(service)
441
+ log(f"\nUsage: {usage_after['total']}s / 600s ({usage_after['percentage']:.1f}%)")
442
+ log(f"This job: {job.usage() or 0}s")
443
+
444
+
445
+ if __name__ == '__main__':
446
+ try:
447
+ main()
448
+ except KeyboardInterrupt:
449
+ log("Interrupted.")
450
+ sys.exit(1)
451
+ except Exception as e:
452
+ log(f"FATAL: {e}")
453
+ import traceback
454
+ traceback.print_exc()
455
+ sys.exit(1)
zeno_multiaxis.py ADDED
@@ -0,0 +1,1141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Zeno Multi-Axis Validation
3
+
4
+ Six-section experiment testing Zeno dragging across qubits, rotation
5
+ angles, measurement schedules, and idle gap mitigation strategies.
6
+
7
+ 48 circuits, single Batch submission.
8
+
9
+ Section A: Corrected multi-qubit gate comparison (W1 fix) — 18 circuits
10
+ Section B: Per-theta VQE calibration (W4 fix) — 10 circuits
11
+ Section C: Adaptive-N Zeno (new) — 8 circuits
12
+ Section D: Non-uniform STZ schedule (new) — 6 circuits
13
+ Section E: Zeno-DD hybrid (new) — 4 circuits
14
+ Section F: Two-qubit soft weighting (new) — 2 circuits
15
+
16
+ Primary metric: soft k<=2 effective yield.
17
+ Budget: ~175s QPU remaining. Target: ~20-25s QPU.
18
+ Safety: abort if <30s remaining; reduced mode (A+B only) if 30-50s.
19
+ """
20
+
21
+ import json
22
+ import sys
23
+ from datetime import datetime, timezone
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+ import numpy as np
27
+ from scipy.special import comb
28
+
29
+ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
30
+ from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
31
+ from qiskit_ibm_runtime import (
32
+ QiskitRuntimeService,
33
+ SamplerV2,
34
+ Batch,
35
+ )
36
+
37
+
38
+ DATA_DIR = Path("D:/qiskit-zenodragging")
39
+ RESULTS_DIR = DATA_DIR / "results" / "zeno_multiaxis"
40
+
41
+
42
+ @dataclass
43
+ class ExperimentConfig:
44
+ name: str
45
+ circuit: QuantumCircuit
46
+ category: str
47
+ section: str
48
+ params: dict
49
+ target_qubits: list = field(default_factory=lambda: [0])
50
+
51
+
52
+ def log(msg, level=0):
53
+ indent = " " * level
54
+ ts = datetime.now().strftime("%H:%M:%S")
55
+ print(f"[{ts}] {indent}{msg}")
56
+
57
+
58
+ def check_usage(service):
59
+ jobs = list(service.jobs(limit=200))
60
+ now = datetime.now(timezone.utc)
61
+ month_start = datetime(now.year, now.month, 1, tzinfo=timezone.utc)
62
+ total = 0
63
+ for j in jobs:
64
+ u = j.usage() or 0
65
+ try:
66
+ m = j.metrics()
67
+ ts = m.get('timestamps', {}).get('created', '')
68
+ if ts:
69
+ dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
70
+ if dt >= month_start:
71
+ total += u
72
+ except Exception:
73
+ pass
74
+ return {"total": total, "remaining": 600 - total, "percentage": 100 * total / 600}
75
+
76
+
77
+ # =============================================================================
78
+ # CIRCUIT BUILDERS
79
+ # =============================================================================
80
+
81
+ def build_standard(theta):
82
+ """Standard: Ry(theta) Ry(-theta) measure. Ideal = |0>."""
83
+ qc = QuantumCircuit(1, 1)
84
+ qc.ry(theta, 0)
85
+ qc.ry(-theta, 0)
86
+ qc.measure(0, 0)
87
+ return qc
88
+
89
+
90
+ def build_vqe_standard(theta):
91
+ """VQE prep: Ry(theta)|0>, measure Z. No undo."""
92
+ qc = QuantumCircuit(1, 1)
93
+ qc.ry(theta, 0)
94
+ qc.measure(0, 0)
95
+ return qc
96
+
97
+
98
+ def build_zeno(theta, n_meas):
99
+ """Zeno drag 0->theta via N measurements, then undo. Ideal = |0>."""
100
+ qr = QuantumRegister(1, 'q')
101
+ cr = ClassicalRegister(n_meas + 1, 'c')
102
+ qc = QuantumCircuit(qr, cr)
103
+ for k in range(1, n_meas + 1):
104
+ theta_k = k * theta / n_meas
105
+ qc.ry(-theta_k, 0)
106
+ qc.measure(0, k - 1)
107
+ qc.ry(theta_k, 0)
108
+ qc.ry(-theta, 0)
109
+ qc.measure(0, n_meas)
110
+ return qc
111
+
112
+
113
+ def build_zeno_stz(theta, n_meas):
114
+ """Zeno drag with sinusoidal (STZ) schedule: theta_k = theta * sin^2(k*pi/2N).
115
+
116
+ Concentrates measurement steps near Bloch sphere poles (slow start/end,
117
+ fast middle). Lewalle et al. (PRX Quantum 2024) showed this is optimal.
118
+ """
119
+ qr = QuantumRegister(1, 'q')
120
+ cr = ClassicalRegister(n_meas + 1, 'c')
121
+ qc = QuantumCircuit(qr, cr)
122
+ for k in range(1, n_meas + 1):
123
+ theta_k = theta * np.sin(k * np.pi / (2 * n_meas)) ** 2
124
+ qc.ry(-theta_k, 0)
125
+ qc.measure(0, k - 1)
126
+ qc.ry(theta_k, 0)
127
+ qc.ry(-theta, 0)
128
+ qc.measure(0, n_meas)
129
+ return qc
130
+
131
+
132
+ def build_delay_matched(theta, n_meas, meas_duration_dt):
133
+ """Standard gate + idle delay = same wall-clock as Zeno. Ideal = |0>."""
134
+ qc = QuantumCircuit(1, 1)
135
+ qc.ry(theta, 0)
136
+ qc.delay(n_meas * meas_duration_dt, 0, unit='dt')
137
+ qc.ry(-theta, 0)
138
+ qc.measure(0, 0)
139
+ return qc
140
+
141
+
142
+ def build_delay_total(total_delay_dt):
143
+ """Pure delay then measure. Ideal = |0>."""
144
+ qc = QuantumCircuit(1, 1)
145
+ if total_delay_dt > 0:
146
+ qc.delay(total_delay_dt, 0, unit='dt')
147
+ qc.measure(0, 0)
148
+ return qc
149
+
150
+
151
+ def build_zeno_bare_gap(theta, n_meas, gap_dt):
152
+ """Zeno drag with bare idle delay between measurements."""
153
+ qr = QuantumRegister(1, 'q')
154
+ cr = ClassicalRegister(n_meas + 1, 'c')
155
+ qc = QuantumCircuit(qr, cr)
156
+ for k in range(1, n_meas + 1):
157
+ theta_k = k * theta / n_meas
158
+ qc.ry(-theta_k, 0)
159
+ qc.measure(0, k - 1)
160
+ qc.ry(theta_k, 0)
161
+ if gap_dt > 0 and k < n_meas:
162
+ qc.delay(gap_dt, 0, unit='dt')
163
+ qc.ry(-theta, 0)
164
+ qc.measure(0, n_meas)
165
+ return qc
166
+
167
+
168
+ def build_zeno_dd_gap(theta, n_meas, gap_dt):
169
+ """Zeno drag with Hahn echo DD (delay/2 - X - delay/2) in gaps.
170
+
171
+ The X-X echo refocuses low-frequency dephasing noise during idle gaps.
172
+ Net unitary of DD sequence is identity (X^2 = I).
173
+ """
174
+ qr = QuantumRegister(1, 'q')
175
+ cr = ClassicalRegister(n_meas + 1, 'c')
176
+ qc = QuantumCircuit(qr, cr)
177
+ half_gap = gap_dt // 2
178
+ for k in range(1, n_meas + 1):
179
+ theta_k = k * theta / n_meas
180
+ qc.ry(-theta_k, 0)
181
+ qc.measure(0, k - 1)
182
+ qc.ry(theta_k, 0)
183
+ if gap_dt > 0 and k < n_meas:
184
+ qc.delay(half_gap, 0, unit='dt')
185
+ qc.x(0)
186
+ qc.delay(gap_dt - half_gap, 0, unit='dt')
187
+ qc.x(0)
188
+ qc.ry(-theta, 0)
189
+ qc.measure(0, n_meas)
190
+ return qc
191
+
192
+
193
+ def build_identity_zeno_bare_gap(n_meas, gap_dt):
194
+ """Identity Zeno (no rotation) with bare gap between measurements."""
195
+ qr = QuantumRegister(1, 'q')
196
+ cr = ClassicalRegister(n_meas + 1, 'c')
197
+ qc = QuantumCircuit(qr, cr)
198
+ for k in range(n_meas):
199
+ qc.measure(0, k)
200
+ if gap_dt > 0 and k < n_meas - 1:
201
+ qc.delay(gap_dt, 0, unit='dt')
202
+ qc.measure(0, n_meas)
203
+ return qc
204
+
205
+
206
+ def build_cnot_standard():
207
+ """Standard: X(q0), CX round-trip, X(q0), measure both. Ideal = |00>."""
208
+ qc = QuantumCircuit(2, 2)
209
+ qc.x(0)
210
+ qc.cx(0, 1)
211
+ qc.cx(0, 1)
212
+ qc.x(0)
213
+ qc.measure([0, 1], [0, 1])
214
+ return qc
215
+
216
+
217
+ def build_cnot_zeno(n_meas):
218
+ """Zeno drag q0 to |1>, CX round-trip, undo drag, measure both.
219
+
220
+ Intermediate measurements on q0 track drag quality.
221
+ Ideal = |00>.
222
+ """
223
+ theta = np.pi
224
+ qr = QuantumRegister(2, 'q')
225
+ cr = ClassicalRegister(n_meas + 2, 'c')
226
+ qc = QuantumCircuit(qr, cr)
227
+ # Zeno drag q0 from |0> to |1>
228
+ for k in range(1, n_meas + 1):
229
+ theta_k = k * theta / n_meas
230
+ qc.ry(-theta_k, 0)
231
+ qc.measure(0, k - 1)
232
+ qc.ry(theta_k, 0)
233
+ # CX round-trip (q0=|1> flips q1, then flips back)
234
+ qc.cx(0, 1)
235
+ qc.cx(0, 1)
236
+ # Undo the drag
237
+ qc.ry(-theta, 0)
238
+ # Final measurements
239
+ qc.measure(0, n_meas)
240
+ qc.measure(1, n_meas + 1)
241
+ return qc
242
+
243
+
244
+ # =============================================================================
245
+ # ANALYSIS
246
+ # =============================================================================
247
+
248
+ def analyze_zeno(bitstrings, n_meas, p_meas):
249
+ """Full Zeno analysis with soft k<=2 as primary metric."""
250
+ total = len(bitstrings)
251
+ successful = 0
252
+ correct_given_success = 0
253
+ flip_bins = {}
254
+
255
+ for bs in bitstrings:
256
+ if len(bs) < n_meas + 1:
257
+ continue
258
+ final = bs[0]
259
+ intermediate = bs[1:n_meas + 1]
260
+ n_flips = sum(1 for b in intermediate if b == '1')
261
+
262
+ if n_flips not in flip_bins:
263
+ flip_bins[n_flips] = {'total': 0, 'correct': 0}
264
+ flip_bins[n_flips]['total'] += 1
265
+ if final == '0':
266
+ flip_bins[n_flips]['correct'] += 1
267
+
268
+ if n_flips == 0:
269
+ successful += 1
270
+ if final == '0':
271
+ correct_given_success += 1
272
+
273
+ success_rate = successful / total if total > 0 else 0
274
+ fidelity_hard = correct_given_success / successful if successful > 0 else 0
275
+ expected_meas_flips = n_meas * p_meas
276
+
277
+ # Soft k<=2 (PRIMARY METRIC)
278
+ sk2_c, sk2_t = 0, 0
279
+ for nf, data in flip_bins.items():
280
+ if nf <= 2:
281
+ sk2_c += data['correct']
282
+ sk2_t += data['total']
283
+ fidelity_soft_k2 = sk2_c / sk2_t if sk2_t > 0 else 0
284
+ utilization_k2 = sk2_t / total if total > 0 else 0
285
+ effective_yield_k2 = sk2_c / total if total > 0 else 0
286
+
287
+ # Excess-flip
288
+ w3_c, w3_t = 0, 0
289
+ for nf, data in flip_bins.items():
290
+ excess = max(0, nf - expected_meas_flips)
291
+ w = np.exp(-excess)
292
+ w3_c += w * data['correct']
293
+ w3_t += w * data['total']
294
+ fid_excess = w3_c / w3_t if w3_t > 0 else 0
295
+
296
+ # Likelihood ratio
297
+ w4_c, w4_t = 0, 0
298
+ for nf, data in flip_bins.items():
299
+ if nf <= n_meas:
300
+ p_target = comb(n_meas, nf, exact=True) * (p_meas ** nf) * ((1 - p_meas) ** (n_meas - nf))
301
+ p_random = comb(n_meas, nf, exact=True) * (0.5 ** n_meas)
302
+ w = min(p_target / p_random, 1e10) if p_random > 0 else 0
303
+ else:
304
+ w = 0
305
+ w4_c += w * data['correct']
306
+ w4_t += w * data['total']
307
+ fid_likelihood = w4_c / w4_t if w4_t > 0 else 0
308
+
309
+ all_flips = []
310
+ for nf, data in flip_bins.items():
311
+ all_flips.extend([nf] * data['total'])
312
+ mean_flips = float(np.mean(all_flips)) if all_flips else 0
313
+ std_flips = float(np.std(all_flips)) if all_flips else 0
314
+
315
+ return {
316
+ 'total': total,
317
+ 'successful': successful,
318
+ 'success_rate': success_rate,
319
+ 'fidelity_hard_ps': fidelity_hard,
320
+ 'fidelity_soft_k2': fidelity_soft_k2,
321
+ 'utilization_k2': utilization_k2,
322
+ 'effective_yield_k2': effective_yield_k2,
323
+ 'fidelity_excess': fid_excess,
324
+ 'fidelity_likelihood': fid_likelihood,
325
+ 'expected_meas_flips': expected_meas_flips,
326
+ 'mean_flips': mean_flips,
327
+ 'std_flips': std_flips,
328
+ 'flip_distribution': {str(k): v for k, v in sorted(flip_bins.items())},
329
+ 'type': 'zeno',
330
+ }
331
+
332
+
333
+ def analyze_standard(bitstrings):
334
+ total = len(bitstrings)
335
+ zeros = sum(1 for b in bitstrings if b[-1] == '0')
336
+ return {'total': total, 'fidelity': zeros / total if total > 0 else 0, 'type': 'standard'}
337
+
338
+
339
+ def analyze_vqe(bitstrings, theta):
340
+ """Analyze VQE standard circuit: P(0) -> z_raw."""
341
+ total = len(bitstrings)
342
+ p0 = sum(1 for bs in bitstrings if bs[-1] == '0') / total if total > 0 else 0.5
343
+ z_raw = 2 * p0 - 1
344
+ true_z = float(np.cos(theta))
345
+ return {
346
+ 'total': total,
347
+ 'p0': p0,
348
+ 'z_raw': z_raw,
349
+ 'true_z': true_z,
350
+ 'error': z_raw - true_z,
351
+ 'type': 'vqe_standard',
352
+ }
353
+
354
+
355
+ def analyze_two_qubit_zeno(bitstrings, n_meas, p_meas):
356
+ """Analyze 2-qubit Zeno: intermediate on q0, final on both. Target = |00>."""
357
+ total = len(bitstrings)
358
+ flip_bins = {}
359
+
360
+ for bs in bitstrings:
361
+ if len(bs) < n_meas + 2:
362
+ continue
363
+ final_q1 = bs[0]
364
+ final_q0 = bs[1]
365
+ intermediate = bs[2:n_meas + 2]
366
+ n_flips = sum(1 for b in intermediate if b == '1')
367
+ correct = 1 if (final_q0 == '0' and final_q1 == '0') else 0
368
+
369
+ if n_flips not in flip_bins:
370
+ flip_bins[n_flips] = {'total': 0, 'correct': 0}
371
+ flip_bins[n_flips]['total'] += 1
372
+ flip_bins[n_flips]['correct'] += correct
373
+
374
+ # Soft k<=2
375
+ sk2_c, sk2_t = 0, 0
376
+ for nf, data in flip_bins.items():
377
+ if nf <= 2:
378
+ sk2_c += data['correct']
379
+ sk2_t += data['total']
380
+ fidelity_soft_k2 = sk2_c / sk2_t if sk2_t > 0 else 0
381
+
382
+ # Hard PS
383
+ hard_data = flip_bins.get(0, {'total': 0, 'correct': 0})
384
+ fidelity_hard = hard_data['correct'] / hard_data['total'] if hard_data['total'] > 0 else 0
385
+
386
+ # Raw (unweighted)
387
+ raw_correct = sum(d['correct'] for d in flip_bins.values())
388
+ fidelity_raw = raw_correct / total if total > 0 else 0
389
+
390
+ return {
391
+ 'total': total,
392
+ 'fidelity_soft_k2': fidelity_soft_k2,
393
+ 'fidelity_hard_ps': fidelity_hard,
394
+ 'fidelity_raw': fidelity_raw,
395
+ 'soft_k2_shots': sk2_t,
396
+ 'hard_ps_shots': hard_data['total'],
397
+ 'flip_distribution': {str(k): v for k, v in sorted(flip_bins.items())},
398
+ 'type': 'two_qubit_zeno',
399
+ }
400
+
401
+
402
+ def analyze_two_qubit_standard(bitstrings):
403
+ """Analyze standard 2-qubit circuit. Target = |00>."""
404
+ total = len(bitstrings)
405
+ correct = sum(1 for bs in bitstrings if all(b == '0' for b in bs))
406
+ return {
407
+ 'total': total,
408
+ 'fidelity': correct / total if total > 0 else 0,
409
+ 'type': 'two_qubit_standard',
410
+ }
411
+
412
+
413
+ # =============================================================================
414
+ # MAIN
415
+ # =============================================================================
416
+
417
+ def main():
418
+ print("=" * 70)
419
+ print("ZENO MULTI-AXIS VALIDATION — DEFINITIVE EXPERIMENT")
420
+ print("=" * 70)
421
+
422
+ service = QiskitRuntimeService(channel="ibm_cloud", instance="claude")
423
+
424
+ usage_before = check_usage(service)
425
+ log(f"Usage: {usage_before['total']:.1f}s / 600s ({usage_before['percentage']:.1f}%)")
426
+ log(f"Remaining: {usage_before['remaining']:.1f}s")
427
+
428
+ if usage_before['remaining'] < 30:
429
+ log("Less than 30s remaining. Aborting.")
430
+ return
431
+
432
+ reduced_mode = usage_before['remaining'] < 50
433
+ if reduced_mode:
434
+ log("30-50s remaining — REDUCED mode (Sections A+B only, 28 circuits)")
435
+
436
+ backend = service.backend("ibm_torino")
437
+ log(f"Backend: {backend.name} ({backend.num_qubits}q)")
438
+
439
+ # Hardware properties
440
+ dt = backend.dt
441
+ hw_target = backend.target
442
+ shots = 4096
443
+
444
+ # Target qubits for Section A: low measurement error qubits
445
+ # Q37 (1.0%), Q95 (2.7%), Q131 (1.8%) — replaces Q0 (11.6%)
446
+ section_a_qubits = [37, 95, 131]
447
+ qubit_info = {}
448
+ for qi in section_a_qubits:
449
+ try:
450
+ props = backend.qubit_properties(qi)
451
+ mp = hw_target['measure'][(qi,)]
452
+ qubit_info[qi] = {
453
+ 'T1_us': props.t1 * 1e6,
454
+ 'T2_us': props.t2 * 1e6,
455
+ 'meas_error': mp.error,
456
+ 'meas_duration_dt': int(mp.duration / dt),
457
+ }
458
+ except Exception as e:
459
+ log(f"WARNING: Could not get properties for Q{qi}: {e}")
460
+
461
+ if 37 not in qubit_info:
462
+ log("FATAL: Q37 properties unavailable. Cannot proceed.")
463
+ return
464
+
465
+ q37 = qubit_info[37]
466
+ meas_err_37 = q37['meas_error']
467
+ meas_dt_37 = q37['meas_duration_dt']
468
+
469
+ for qi, info in sorted(qubit_info.items()):
470
+ log(f"Q{qi}: T1={info['T1_us']:.1f}us, T2={info['T2_us']:.1f}us, "
471
+ f"meas_err={info['meas_error']:.4f}", 1)
472
+
473
+ # Find CX neighbor for Q37 (Section F)
474
+ cx_neighbor = None
475
+ if not reduced_mode:
476
+ try:
477
+ cm = backend.coupling_map
478
+ # Get neighbors from coupling map edges
479
+ neighbors = list(set(
480
+ [j for (i, j) in cm.get_edges() if i == 37] +
481
+ [i for (i, j) in cm.get_edges() if j == 37]
482
+ ))
483
+ if neighbors:
484
+ best_neighbor = None
485
+ best_err = 1.0
486
+ for n in neighbors:
487
+ try:
488
+ nerr = hw_target['measure'][(n,)].error
489
+ if nerr < best_err:
490
+ best_err = nerr
491
+ best_neighbor = n
492
+ except Exception:
493
+ pass
494
+ cx_neighbor = best_neighbor
495
+ if cx_neighbor is not None:
496
+ log(f"Section F: CX pair Q37-Q{cx_neighbor} "
497
+ f"(neighbor meas_err={best_err:.4f})")
498
+ else:
499
+ log("Section F: No valid CX neighbor found. Skipping.")
500
+ else:
501
+ log("Section F: Q37 has no coupling map neighbors. Skipping.")
502
+ except Exception as e:
503
+ log(f"Section F: Could not query coupling map: {e}")
504
+
505
+ # =========================================================================
506
+ # BUILD ALL EXPERIMENTS
507
+ # =========================================================================
508
+ all_experiments = []
509
+ n_meas_default = 8
510
+
511
+ # --- SECTION A: Corrected Multi-Qubit Gate Comparison (18 circuits) ---
512
+ log("Building Section A: Multi-qubit gate comparison...")
513
+ for qi in section_a_qubits:
514
+ if qi not in qubit_info:
515
+ continue
516
+ info = qubit_info[qi]
517
+ for gate_name, theta in [('I', 0.0), ('X', np.pi)]:
518
+ # Standard
519
+ all_experiments.append(ExperimentConfig(
520
+ name=f"a_q{qi}_{gate_name}_standard",
521
+ circuit=build_standard(theta),
522
+ category="standard",
523
+ section="A",
524
+ params={'qubit': qi, 'gate': gate_name, 'theta': theta,
525
+ 'T1_us': info['T1_us'], 'meas_error': info['meas_error']},
526
+ target_qubits=[qi],
527
+ ))
528
+ # Zeno N=8
529
+ all_experiments.append(ExperimentConfig(
530
+ name=f"a_q{qi}_{gate_name}_zeno",
531
+ circuit=build_zeno(theta, n_meas_default),
532
+ category="zeno",
533
+ section="A",
534
+ params={'qubit': qi, 'gate': gate_name, 'theta': theta,
535
+ 'n_meas': n_meas_default,
536
+ 'T1_us': info['T1_us'], 'meas_error': info['meas_error']},
537
+ target_qubits=[qi],
538
+ ))
539
+ # Delay-matched
540
+ all_experiments.append(ExperimentConfig(
541
+ name=f"a_q{qi}_{gate_name}_delay",
542
+ circuit=build_delay_matched(theta, n_meas_default,
543
+ info['meas_duration_dt']),
544
+ category="delay_matched",
545
+ section="A",
546
+ params={'qubit': qi, 'gate': gate_name, 'theta': theta,
547
+ 'n_meas': n_meas_default,
548
+ 'T1_us': info['T1_us'], 'meas_error': info['meas_error']},
549
+ target_qubits=[qi],
550
+ ))
551
+
552
+ # --- SECTION B: Per-Theta VQE Calibration (10 circuits) ---
553
+ log("Building Section B: Per-theta VQE calibration...")
554
+ vqe_thetas = [0.2, 0.8, 1.5, 2.4, np.pi]
555
+ for theta in vqe_thetas:
556
+ theta_label = f"{theta:.2f}".replace('.', 'p')
557
+ # Standard VQE (just Ry, no undo)
558
+ all_experiments.append(ExperimentConfig(
559
+ name=f"b_vqe_std_t{theta_label}",
560
+ circuit=build_vqe_standard(theta),
561
+ category="vqe_standard",
562
+ section="B",
563
+ params={'theta': theta, 'true_z': float(np.cos(theta))},
564
+ target_qubits=[37],
565
+ ))
566
+ # Zeno calibration (drag + undo, gives f(theta))
567
+ all_experiments.append(ExperimentConfig(
568
+ name=f"b_vqe_zeno_t{theta_label}",
569
+ circuit=build_zeno(theta, n_meas_default),
570
+ category="zeno",
571
+ section="B",
572
+ params={'theta': theta, 'n_meas': n_meas_default,
573
+ 'meas_error': meas_err_37},
574
+ target_qubits=[37],
575
+ ))
576
+
577
+ if not reduced_mode:
578
+ # --- SECTION C: Adaptive-N (8 circuits) ---
579
+ log("Building Section C: Adaptive-N Zeno...")
580
+ adaptive_configs = [
581
+ (np.pi / 8, [4, 8]),
582
+ (np.pi / 2, [4, 8, 12]),
583
+ (np.pi, [8, 12, 16]),
584
+ ]
585
+ for theta, n_values in adaptive_configs:
586
+ theta_label = f"{theta/np.pi:.3f}pi".replace('.', 'p')
587
+ for n in n_values:
588
+ all_experiments.append(ExperimentConfig(
589
+ name=f"c_t{theta_label}_n{n}",
590
+ circuit=build_zeno(theta, n),
591
+ category="zeno",
592
+ section="C",
593
+ params={'theta': theta, 'n_meas': n,
594
+ 'meas_error': meas_err_37},
595
+ target_qubits=[37],
596
+ ))
597
+
598
+ # --- SECTION D: Non-Uniform Schedule / STZ (6 circuits) ---
599
+ log("Building Section D: STZ non-uniform schedule...")
600
+ stz_thetas = [np.pi / 2, 3 * np.pi / 4, np.pi]
601
+ for theta in stz_thetas:
602
+ theta_label = f"{theta/np.pi:.3f}pi".replace('.', 'p')
603
+ # Uniform (standard Zeno)
604
+ all_experiments.append(ExperimentConfig(
605
+ name=f"d_uniform_t{theta_label}",
606
+ circuit=build_zeno(theta, n_meas_default),
607
+ category="zeno_uniform",
608
+ section="D",
609
+ params={'theta': theta, 'n_meas': n_meas_default,
610
+ 'schedule': 'uniform', 'meas_error': meas_err_37},
611
+ target_qubits=[37],
612
+ ))
613
+ # Sinusoidal (STZ)
614
+ all_experiments.append(ExperimentConfig(
615
+ name=f"d_stz_t{theta_label}",
616
+ circuit=build_zeno_stz(theta, n_meas_default),
617
+ category="zeno_stz",
618
+ section="D",
619
+ params={'theta': theta, 'n_meas': n_meas_default,
620
+ 'schedule': 'sinusoidal', 'meas_error': meas_err_37},
621
+ target_qubits=[37],
622
+ ))
623
+
624
+ # --- SECTION E: Zeno-DD Hybrid (4 circuits) ---
625
+ log("Building Section E: Zeno-DD hybrid...")
626
+ gap_us = 10
627
+ gap_s = gap_us * 1e-6
628
+ gap_dt = int(gap_s / dt)
629
+ theta_E = np.pi # X gate
630
+
631
+ # 1. X Zeno + bare gap
632
+ all_experiments.append(ExperimentConfig(
633
+ name="e_x_zeno_bare_gap",
634
+ circuit=build_zeno_bare_gap(theta_E, n_meas_default, gap_dt),
635
+ category="zeno_bare_gap",
636
+ section="E",
637
+ params={'theta': theta_E, 'n_meas': n_meas_default,
638
+ 'gap_us': gap_us, 'gap_dt': gap_dt,
639
+ 'meas_error': meas_err_37},
640
+ target_qubits=[37],
641
+ ))
642
+ # 2. X Zeno + DD echo in gap
643
+ all_experiments.append(ExperimentConfig(
644
+ name="e_x_zeno_dd_gap",
645
+ circuit=build_zeno_dd_gap(theta_E, n_meas_default, gap_dt),
646
+ category="zeno_dd_gap",
647
+ section="E",
648
+ params={'theta': theta_E, 'n_meas': n_meas_default,
649
+ 'gap_us': gap_us, 'gap_dt': gap_dt,
650
+ 'meas_error': meas_err_37},
651
+ target_qubits=[37],
652
+ ))
653
+ # 3. Delay-matched baseline (same total time)
654
+ total_delay_e = (n_meas_default * meas_dt_37
655
+ + (n_meas_default - 1) * gap_dt)
656
+ all_experiments.append(ExperimentConfig(
657
+ name="e_delay_matched",
658
+ circuit=build_delay_total(total_delay_e),
659
+ category="delay_matched",
660
+ section="E",
661
+ params={'theta': 0.0, 'total_delay_dt': total_delay_e,
662
+ 'gap_us': gap_us},
663
+ target_qubits=[37],
664
+ ))
665
+ # 4. Identity Zeno + bare gap (control)
666
+ all_experiments.append(ExperimentConfig(
667
+ name="e_identity_zeno_bare_gap",
668
+ circuit=build_identity_zeno_bare_gap(n_meas_default, gap_dt),
669
+ category="identity_zeno_bare_gap",
670
+ section="E",
671
+ params={'theta': 0.0, 'n_meas': n_meas_default,
672
+ 'gap_us': gap_us, 'gap_dt': gap_dt,
673
+ 'meas_error': meas_err_37},
674
+ target_qubits=[37],
675
+ ))
676
+
677
+ # --- SECTION F: Two-Qubit Zeno with Soft Weighting (2 circuits) ---
678
+ if cx_neighbor is not None:
679
+ log(f"Building Section F: Two-qubit Zeno on Q37-Q{cx_neighbor}...")
680
+ # Standard CNOT round-trip
681
+ all_experiments.append(ExperimentConfig(
682
+ name="f_cnot_standard",
683
+ circuit=build_cnot_standard(),
684
+ category="two_qubit_standard",
685
+ section="F",
686
+ params={'control': 37, 'target_qubit': cx_neighbor},
687
+ target_qubits=[37, cx_neighbor],
688
+ ))
689
+ # Zeno CNOT round-trip
690
+ all_experiments.append(ExperimentConfig(
691
+ name="f_cnot_zeno",
692
+ circuit=build_cnot_zeno(n_meas_default),
693
+ category="two_qubit_zeno",
694
+ section="F",
695
+ params={'control': 37, 'target_qubit': cx_neighbor,
696
+ 'n_meas': n_meas_default,
697
+ 'meas_error': meas_err_37},
698
+ target_qubits=[37, cx_neighbor],
699
+ ))
700
+
701
+ section_counts = {}
702
+ for exp in all_experiments:
703
+ section_counts[exp.section] = section_counts.get(exp.section, 0) + 1
704
+ for s, c in sorted(section_counts.items()):
705
+ log(f"Section {s}: {c} circuits", 1)
706
+ log(f"Total circuits: {len(all_experiments)}")
707
+
708
+ # =========================================================================
709
+ # TRANSPILE (with per-qubit initial_layout)
710
+ # =========================================================================
711
+ log("Transpiling...")
712
+ pm_cache = {}
713
+ transpiled = []
714
+ valid_experiments = []
715
+
716
+ for exp in all_experiments:
717
+ layout_key = tuple(exp.target_qubits)
718
+ if layout_key not in pm_cache:
719
+ pm_cache[layout_key] = generate_preset_pass_manager(
720
+ backend=backend,
721
+ optimization_level=1,
722
+ initial_layout=list(layout_key),
723
+ )
724
+ try:
725
+ tc = pm_cache[layout_key].run(exp.circuit)
726
+ transpiled.append(tc)
727
+ valid_experiments.append(exp)
728
+ except Exception as e:
729
+ log(f"ERROR transpiling {exp.name}: {e}")
730
+
731
+ log(f"Transpiled: {len(transpiled)}/{len(all_experiments)}")
732
+ if not transpiled:
733
+ log("No circuits transpiled. Aborting.")
734
+ return
735
+
736
+ depths = [tc.depth() for tc in transpiled]
737
+ log(f"Depths: min={min(depths)}, max={max(depths)}")
738
+
739
+ for i, exp in enumerate(valid_experiments):
740
+ exp.params['transpiled_depth'] = depths[i]
741
+
742
+ # =========================================================================
743
+ # SUBMIT
744
+ # =========================================================================
745
+ log("Submitting batch...")
746
+ start_time = datetime.now(timezone.utc)
747
+
748
+ with Batch(backend=backend) as batch:
749
+ sampler = SamplerV2(mode=batch)
750
+ job = sampler.run(transpiled, shots=shots)
751
+ log(f"Job ID: {job.job_id()}")
752
+ log("Waiting...")
753
+ job.wait_for_final_state()
754
+
755
+ end_time = datetime.now(timezone.utc)
756
+ wall_time = (end_time - start_time).total_seconds()
757
+ log(f"Done. Wall time: {wall_time:.1f}s, QPU: {job.usage() or 0}s")
758
+
759
+ # =========================================================================
760
+ # PARSE RESULTS
761
+ # =========================================================================
762
+ result = job.result()
763
+ metrics = job.metrics()
764
+ results_data = {}
765
+
766
+ for i, exp in enumerate(valid_experiments):
767
+ pub_result = result[i]
768
+ data_bin = pub_result.data
769
+
770
+ if hasattr(data_bin, 'c'):
771
+ bitstrings = list(data_bin.c.get_bitstrings())
772
+ elif hasattr(data_bin, 'meas'):
773
+ bitstrings = list(data_bin.meas.get_bitstrings())
774
+ else:
775
+ cr_name = list(data_bin.keys())[0]
776
+ bitstrings = list(getattr(data_bin, cr_name).get_bitstrings())
777
+
778
+ p_meas = exp.params.get('meas_error', meas_err_37)
779
+ n_meas = exp.params.get('n_meas', 0)
780
+
781
+ if exp.category == 'two_qubit_zeno':
782
+ analysis = analyze_two_qubit_zeno(bitstrings, n_meas, p_meas)
783
+ elif exp.category == 'two_qubit_standard':
784
+ analysis = analyze_two_qubit_standard(bitstrings)
785
+ elif exp.category == 'vqe_standard':
786
+ analysis = analyze_vqe(bitstrings, exp.params['theta'])
787
+ elif 'zeno' in exp.category:
788
+ analysis = analyze_zeno(bitstrings, n_meas, p_meas)
789
+ else:
790
+ analysis = analyze_standard(bitstrings)
791
+
792
+ results_data[exp.name] = {
793
+ 'section': exp.section,
794
+ 'category': exp.category,
795
+ 'params': {k: (float(v) if isinstance(v, (np.floating, float)) else v)
796
+ for k, v in exp.params.items()},
797
+ 'analysis': analysis,
798
+ 'raw_bitstrings': bitstrings, # all 4096, not truncated
799
+ }
800
+
801
+ # =========================================================================
802
+ # SECTION A ANALYSIS
803
+ # =========================================================================
804
+ print("\n" + "=" * 70)
805
+ print("SECTION A: CORRECTED MULTI-QUBIT GATE COMPARISON (W1 fix)")
806
+ print("=" * 70)
807
+
808
+ print(f"\n {'Qubit':>5} | {'MeasErr':>7} | {'Gate':>4} | {'Standard':>8} | "
809
+ f"{'Zeno k2':>8} | {'Delay':>7} | {'Z-Std':>7} | {'Z-Delay':>7}")
810
+ print(" " + "-" * 70)
811
+
812
+ a_improvements_I = []
813
+ a_improvements_X = []
814
+
815
+ for qi in section_a_qubits:
816
+ if qi not in qubit_info:
817
+ continue
818
+ for gate_name in ['I', 'X']:
819
+ std_key = f"a_q{qi}_{gate_name}_standard"
820
+ zen_key = f"a_q{qi}_{gate_name}_zeno"
821
+ del_key = f"a_q{qi}_{gate_name}_delay"
822
+
823
+ std_fid = results_data.get(std_key, {}).get('analysis', {}).get('fidelity', 0)
824
+ zen_k2 = results_data.get(zen_key, {}).get('analysis', {}).get('fidelity_soft_k2', 0)
825
+ del_fid = results_data.get(del_key, {}).get('analysis', {}).get('fidelity', 0)
826
+ merr = qubit_info[qi]['meas_error']
827
+
828
+ imp = zen_k2 - std_fid
829
+ if gate_name == 'I':
830
+ a_improvements_I.append(imp)
831
+ else:
832
+ a_improvements_X.append(imp)
833
+
834
+ print(f" Q{qi:>3} | {merr:7.4f} | {gate_name:>4} | {std_fid:8.4f} | "
835
+ f"{zen_k2:8.4f} | {del_fid:7.4f} | {imp:+7.4f} | "
836
+ f"{zen_k2-del_fid:+7.4f}")
837
+
838
+ i_wins = sum(1 for x in a_improvements_I if x > 0)
839
+ x_wins = sum(1 for x in a_improvements_X if x > 0)
840
+ n_qubits_tested = len([q for q in section_a_qubits if q in qubit_info])
841
+ print(f"\n I gate: Zeno improvement on {i_wins}/{n_qubits_tested} qubits")
842
+ print(f" X gate: Zeno improvement on {x_wins}/{n_qubits_tested} qubits")
843
+
844
+ # =========================================================================
845
+ # SECTION B ANALYSIS
846
+ # =========================================================================
847
+ print("\n" + "=" * 70)
848
+ print("SECTION B: PER-THETA VQE CALIBRATION (W4 fix)")
849
+ print("=" * 70)
850
+
851
+ print(f"\n {'theta':>7} | {'cos(t)':>7} | {'z_raw':>7} | {'f(t) k2':>8} | "
852
+ f"{'err_std':>8} | {'err_glob':>8} | {'err_per':>8}")
853
+ print(" " + "-" * 70)
854
+
855
+ z_raws = []
856
+ fidelities_b = []
857
+ true_zs = []
858
+
859
+ for theta in vqe_thetas:
860
+ theta_label = f"{theta:.2f}".replace('.', 'p')
861
+ std_key = f"b_vqe_std_t{theta_label}"
862
+ zen_key = f"b_vqe_zeno_t{theta_label}"
863
+
864
+ vqe_a = results_data.get(std_key, {}).get('analysis', {})
865
+ zen_a = results_data.get(zen_key, {}).get('analysis', {})
866
+
867
+ z_raw = vqe_a.get('z_raw', 0)
868
+ true_z = float(np.cos(theta))
869
+ f_theta = zen_a.get('fidelity_soft_k2', 0.5)
870
+
871
+ z_raws.append(z_raw)
872
+ fidelities_b.append(f_theta)
873
+ true_zs.append(true_z)
874
+
875
+ f_global = np.mean(fidelities_b) if fidelities_b else 0.5
876
+
877
+ std_errors_sq = []
878
+ glob_errors_sq = []
879
+ per_errors_sq = []
880
+
881
+ for i, theta in enumerate(vqe_thetas):
882
+ z_raw = z_raws[i]
883
+ f_theta = fidelities_b[i]
884
+ true_z = true_zs[i]
885
+
886
+ err_std = z_raw - true_z
887
+
888
+ denom_glob = 2 * f_global - 1
889
+ z_glob = z_raw / denom_glob if abs(denom_glob) > 0.01 else z_raw
890
+ z_glob = max(-1.0, min(1.0, z_glob))
891
+ err_glob = z_glob - true_z
892
+
893
+ denom_per = 2 * f_theta - 1
894
+ z_per = z_raw / denom_per if abs(denom_per) > 0.01 else z_raw
895
+ z_per = max(-1.0, min(1.0, z_per))
896
+ err_per = z_per - true_z
897
+
898
+ std_errors_sq.append(err_std ** 2)
899
+ glob_errors_sq.append(err_glob ** 2)
900
+ per_errors_sq.append(err_per ** 2)
901
+
902
+ print(f" {theta:7.3f} | {true_z:+7.4f} | {z_raw:+7.4f} | {f_theta:8.4f} | "
903
+ f"{err_std:+8.4f} | {err_glob:+8.4f} | {err_per:+8.4f}")
904
+
905
+ rmse_std = float(np.sqrt(np.mean(std_errors_sq))) if std_errors_sq else 0
906
+ rmse_glob = float(np.sqrt(np.mean(glob_errors_sq))) if glob_errors_sq else 0
907
+ rmse_per = float(np.sqrt(np.mean(per_errors_sq))) if per_errors_sq else 0
908
+
909
+ print(f"\n RMSE standard: {rmse_std:.4f}")
910
+ print(f" RMSE global-f: {rmse_glob:.4f} (f_global={f_global:.4f})")
911
+ print(f" RMSE per-theta: {rmse_per:.4f}")
912
+
913
+ if rmse_per < rmse_glob < rmse_std:
914
+ print(" RESULT: per-theta < global < standard")
915
+ elif rmse_per < rmse_std:
916
+ print(" RESULT: per-theta improves over standard")
917
+ else:
918
+ print(" RESULT: correction does not improve RMSE — honest result")
919
+
920
+ if not reduced_mode:
921
+ # =================================================================
922
+ # SECTION C ANALYSIS
923
+ # =================================================================
924
+ print("\n" + "=" * 70)
925
+ print("SECTION C: ADAPTIVE-N ZENO")
926
+ print("=" * 70)
927
+
928
+ print(f"\n {'theta':>8} | {'N':>3} | {'k2 fid':>7} | {'k2 yield':>8} | "
929
+ f"{'hard PS':>7} | {'success':>7} | {'excess':>7}")
930
+ print(" " + "-" * 65)
931
+
932
+ for theta, n_values in adaptive_configs:
933
+ for n in n_values:
934
+ theta_label = f"{theta/np.pi:.3f}pi".replace('.', 'p')
935
+ key = f"c_t{theta_label}_n{n}"
936
+ a = results_data.get(key, {}).get('analysis', {})
937
+
938
+ fk2 = a.get('fidelity_soft_k2', 0)
939
+ yk2 = a.get('effective_yield_k2', 0)
940
+ fh = a.get('fidelity_hard_ps', 0)
941
+ sr = a.get('success_rate', 0)
942
+ fe = a.get('fidelity_excess', 0)
943
+
944
+ print(f" {theta/np.pi:6.3f}pi | {n:3d} | {fk2:7.4f} | {yk2:8.4f} | "
945
+ f"{fh:7.4f} | {sr*100:6.1f}% | {fe:7.4f}")
946
+ print()
947
+
948
+ # Check: does N=4 suffice for small angles?
949
+ pi8_n4 = results_data.get(
950
+ f"c_t{(np.pi/8/np.pi):.3f}pi_n4".replace('.', 'p'), {}
951
+ ).get('analysis', {}).get('fidelity_soft_k2', 0)
952
+ pi8_n8 = results_data.get(
953
+ f"c_t{(np.pi/8/np.pi):.3f}pi_n8".replace('.', 'p'), {}
954
+ ).get('analysis', {}).get('fidelity_soft_k2', 0)
955
+ if pi8_n4 > 0 and pi8_n8 > 0:
956
+ diff = pi8_n8 - pi8_n4
957
+ print(f" pi/8: N=4 vs N=8 fidelity gap: {diff:+.4f}")
958
+ if abs(diff) < 0.02:
959
+ print(" -> N=4 suffices for small angles (2x shallower)")
960
+ else:
961
+ print(" -> N=8 still meaningfully better")
962
+
963
+ # =================================================================
964
+ # SECTION D ANALYSIS
965
+ # =================================================================
966
+ print("\n" + "=" * 70)
967
+ print("SECTION D: NON-UNIFORM SCHEDULE (STZ)")
968
+ print("=" * 70)
969
+
970
+ print(f"\n {'theta':>8} | {'Schedule':>10} | {'k2 fid':>7} | "
971
+ f"{'k2 yield':>8} | {'excess':>7} | {'diff':>7}")
972
+ print(" " + "-" * 60)
973
+
974
+ d_diffs = []
975
+ for theta in stz_thetas:
976
+ theta_label = f"{theta/np.pi:.3f}pi".replace('.', 'p')
977
+ uni_key = f"d_uniform_t{theta_label}"
978
+ stz_key = f"d_stz_t{theta_label}"
979
+
980
+ uni_a = results_data.get(uni_key, {}).get('analysis', {})
981
+ stz_a = results_data.get(stz_key, {}).get('analysis', {})
982
+
983
+ uni_k2 = uni_a.get('fidelity_soft_k2', 0)
984
+ stz_k2 = stz_a.get('fidelity_soft_k2', 0)
985
+ uni_y = uni_a.get('effective_yield_k2', 0)
986
+ stz_y = stz_a.get('effective_yield_k2', 0)
987
+ uni_e = uni_a.get('fidelity_excess', 0)
988
+ stz_e = stz_a.get('fidelity_excess', 0)
989
+ diff_pp = (stz_k2 - uni_k2) * 100
990
+ d_diffs.append(abs(stz_k2 - uni_k2))
991
+
992
+ print(f" {theta/np.pi:6.3f}pi | {'uniform':>10} | {uni_k2:7.4f} | "
993
+ f"{uni_y:8.4f} | {uni_e:7.4f} |")
994
+ print(f" {'':>8} | {'sinusoidal':>10} | {stz_k2:7.4f} | "
995
+ f"{stz_y:8.4f} | {stz_e:7.4f} | {diff_pp:+6.1f}pp")
996
+
997
+ any_gt_half = any(d > 0.005 for d in d_diffs)
998
+ print(f"\n >0.5pp difference for any angle: {any_gt_half}")
999
+
1000
+ # =================================================================
1001
+ # SECTION E ANALYSIS
1002
+ # =================================================================
1003
+ print("\n" + "=" * 70)
1004
+ print("SECTION E: ZENO-DD HYBRID")
1005
+ print("=" * 70)
1006
+
1007
+ e_configs = [
1008
+ ("X Zeno + bare gap", "e_x_zeno_bare_gap", True),
1009
+ ("X Zeno + DD echo", "e_x_zeno_dd_gap", True),
1010
+ ("Delay-matched", "e_delay_matched", False),
1011
+ ("I Zeno + bare gap", "e_identity_zeno_bare_gap", True),
1012
+ ]
1013
+
1014
+ print(f"\n {'Variant':>22} | {'k2 fid':>7} | {'k2 yield':>8} | "
1015
+ f"{'excess':>7} | {'fidelity':>8}")
1016
+ print(" " + "-" * 60)
1017
+
1018
+ for label, key, is_zeno in e_configs:
1019
+ a = results_data.get(key, {}).get('analysis', {})
1020
+ if is_zeno:
1021
+ fk2 = a.get('fidelity_soft_k2', 0)
1022
+ yk2 = a.get('effective_yield_k2', 0)
1023
+ fe = a.get('fidelity_excess', 0)
1024
+ print(f" {label:>22} | {fk2:7.4f} | {yk2:8.4f} | "
1025
+ f"{fe:7.4f} | {'---':>8}")
1026
+ else:
1027
+ fid = a.get('fidelity', 0)
1028
+ print(f" {label:>22} | {'---':>7} | {'---':>8} | "
1029
+ f"{'---':>7} | {fid:8.4f}")
1030
+
1031
+ bare_k2 = (results_data.get("e_x_zeno_bare_gap", {})
1032
+ .get('analysis', {}).get('fidelity_soft_k2', 0))
1033
+ dd_k2 = (results_data.get("e_x_zeno_dd_gap", {})
1034
+ .get('analysis', {}).get('fidelity_soft_k2', 0))
1035
+ print(f"\n DD improvement over bare gap: {(dd_k2 - bare_k2)*100:+.1f}pp")
1036
+
1037
+ # =================================================================
1038
+ # SECTION F ANALYSIS
1039
+ # =================================================================
1040
+ if cx_neighbor is not None and 'f_cnot_standard' in results_data:
1041
+ print("\n" + "=" * 70)
1042
+ print(f"SECTION F: TWO-QUBIT ZENO (Q37-Q{cx_neighbor})")
1043
+ print("=" * 70)
1044
+
1045
+ std_f = results_data['f_cnot_standard']['analysis']
1046
+ zen_f = results_data.get('f_cnot_zeno', {}).get('analysis', {})
1047
+
1048
+ std_fid = std_f.get('fidelity', 0)
1049
+ zen_k2 = zen_f.get('fidelity_soft_k2', 0)
1050
+ zen_hard = zen_f.get('fidelity_hard_ps', 0)
1051
+ zen_raw = zen_f.get('fidelity_raw', 0)
1052
+
1053
+ print(f"\n Standard CNOT round-trip: {std_fid:.4f}")
1054
+ print(f" Zeno CNOT (hard PS): {zen_hard:.4f} "
1055
+ f"({zen_f.get('hard_ps_shots', 0)} shots)")
1056
+ print(f" Zeno CNOT (soft k<=2): {zen_k2:.4f} "
1057
+ f"({zen_f.get('soft_k2_shots', 0)} shots)")
1058
+ print(f" Zeno CNOT (raw): {zen_raw:.4f}")
1059
+ print(f" Improvement (k2-std): {zen_k2 - std_fid:+.4f}")
1060
+
1061
+ # =========================================================================
1062
+ # SAVE
1063
+ # =========================================================================
1064
+ output = {
1065
+ 'experiment': 'zeno_multiaxis',
1066
+ 'description': (
1067
+ 'Definitive experiment: corrects W1-W6 weakness failures and tests '
1068
+ 'adaptive-N, STZ scheduling, DD hybrids, soft-weighted two-qubit '
1069
+ 'operations. Primary metric: soft k<=2 effective yield.'
1070
+ ),
1071
+ 'timestamp': start_time.isoformat(),
1072
+ 'backend': backend.name,
1073
+ 'shots': shots,
1074
+ 'job_id': job.job_id(),
1075
+ 'usage_seconds': job.usage() or 0,
1076
+ 'wall_time_seconds': wall_time,
1077
+ 'metrics': metrics,
1078
+ 'reduced_mode': reduced_mode,
1079
+ 'hardware': {
1080
+ 'dt_ns': dt * 1e9,
1081
+ 'qubit_info': {str(k): v for k, v in qubit_info.items()},
1082
+ 'cx_neighbor': cx_neighbor,
1083
+ },
1084
+ 'sections': {},
1085
+ 'results': results_data,
1086
+ }
1087
+
1088
+ # Section-level summaries
1089
+ for section_id in ['A', 'B', 'C', 'D', 'E', 'F']:
1090
+ section_results = {k: v for k, v in results_data.items()
1091
+ if v['section'] == section_id}
1092
+ if section_results:
1093
+ output['sections'][section_id] = {
1094
+ 'n_circuits': len(section_results),
1095
+ 'circuit_names': list(section_results.keys()),
1096
+ }
1097
+
1098
+ # VQE RMSE summary
1099
+ output['sections'].setdefault('B', {}).update({
1100
+ 'rmse_standard': rmse_std,
1101
+ 'rmse_global': rmse_glob,
1102
+ 'rmse_pertheta': rmse_per,
1103
+ 'f_global': float(f_global),
1104
+ })
1105
+
1106
+ RESULTS_DIR.mkdir(parents=True, exist_ok=True)
1107
+ outfile = RESULTS_DIR / 'zeno_multiaxis.json'
1108
+ with open(outfile, 'w') as f:
1109
+ json.dump(output, f, indent=2, default=str)
1110
+ log(f"Saved: {outfile}")
1111
+
1112
+ # =========================================================================
1113
+ # SUMMARY
1114
+ # =========================================================================
1115
+ print("\n" + "=" * 70)
1116
+ print("SUMMARY")
1117
+ print("=" * 70)
1118
+
1119
+ print(f"\n Total circuits: {len(valid_experiments)}")
1120
+ print(f" QPU time: {job.usage() or 0}s")
1121
+ print(f" Wall time: {wall_time:.1f}s")
1122
+ for s, c in sorted(section_counts.items()):
1123
+ print(f" Section {s}: {c} circuits")
1124
+
1125
+ usage_after = check_usage(service)
1126
+ log(f"\nUsage: {usage_after['total']:.1f}s / 600s "
1127
+ f"({usage_after['percentage']:.1f}%)")
1128
+ log(f"Remaining: {usage_after['remaining']:.1f}s")
1129
+
1130
+
1131
+ if __name__ == '__main__':
1132
+ try:
1133
+ main()
1134
+ except KeyboardInterrupt:
1135
+ log("Interrupted.")
1136
+ sys.exit(1)
1137
+ except Exception as e:
1138
+ log(f"FATAL: {e}")
1139
+ import traceback
1140
+ traceback.print_exc()
1141
+ sys.exit(1)