""" Zeno Multi-Axis Validation Six-section experiment testing Zeno dragging across qubits, rotation angles, measurement schedules, and idle gap mitigation strategies. 48 circuits, single Batch submission. Section A: Corrected multi-qubit gate comparison (W1 fix) — 18 circuits Section B: Per-theta VQE calibration (W4 fix) — 10 circuits Section C: Adaptive-N Zeno (new) — 8 circuits Section D: Non-uniform STZ schedule (new) — 6 circuits Section E: Zeno-DD hybrid (new) — 4 circuits Section F: Two-qubit soft weighting (new) — 2 circuits Primary metric: soft k<=2 effective yield. Budget: ~175s QPU remaining. Target: ~20-25s QPU. Safety: abort if <30s remaining; reduced mode (A+B only) if 30-50s. """ import json import sys from datetime import datetime, timezone from dataclasses import dataclass, field from pathlib import Path import numpy as np from scipy.special import comb from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import ( QiskitRuntimeService, SamplerV2, Batch, ) DATA_DIR = Path("D:/qiskit-zenodragging") RESULTS_DIR = DATA_DIR / "results" / "zeno_multiaxis" @dataclass class ExperimentConfig: name: str circuit: QuantumCircuit category: str section: str params: dict target_qubits: list = field(default_factory=lambda: [0]) def log(msg, level=0): indent = " " * level ts = datetime.now().strftime("%H:%M:%S") print(f"[{ts}] {indent}{msg}") def check_usage(service): jobs = list(service.jobs(limit=200)) now = datetime.now(timezone.utc) month_start = datetime(now.year, now.month, 1, tzinfo=timezone.utc) total = 0 for j in jobs: u = j.usage() or 0 try: m = j.metrics() ts = m.get('timestamps', {}).get('created', '') if ts: dt = datetime.fromisoformat(ts.replace('Z', '+00:00')) if dt >= month_start: total += u except Exception: pass return {"total": total, "remaining": 600 - total, "percentage": 100 * total / 600} # ============================================================================= # CIRCUIT BUILDERS # ============================================================================= def build_standard(theta): """Standard: Ry(theta) Ry(-theta) measure. Ideal = |0>.""" qc = QuantumCircuit(1, 1) qc.ry(theta, 0) qc.ry(-theta, 0) qc.measure(0, 0) return qc def build_vqe_standard(theta): """VQE prep: Ry(theta)|0>, measure Z. No undo.""" qc = QuantumCircuit(1, 1) qc.ry(theta, 0) qc.measure(0, 0) return qc def build_zeno(theta, n_meas): """Zeno drag 0->theta via N measurements, then undo. Ideal = |0>.""" qr = QuantumRegister(1, 'q') cr = ClassicalRegister(n_meas + 1, 'c') qc = QuantumCircuit(qr, cr) for k in range(1, n_meas + 1): theta_k = k * theta / n_meas qc.ry(-theta_k, 0) qc.measure(0, k - 1) qc.ry(theta_k, 0) qc.ry(-theta, 0) qc.measure(0, n_meas) return qc def build_zeno_stz(theta, n_meas): """Zeno drag with sinusoidal (STZ) schedule: theta_k = theta * sin^2(k*pi/2N). Concentrates measurement steps near Bloch sphere poles (slow start/end, fast middle). Lewalle et al. (PRX Quantum 2024) showed this is optimal. """ qr = QuantumRegister(1, 'q') cr = ClassicalRegister(n_meas + 1, 'c') qc = QuantumCircuit(qr, cr) for k in range(1, n_meas + 1): theta_k = theta * np.sin(k * np.pi / (2 * n_meas)) ** 2 qc.ry(-theta_k, 0) qc.measure(0, k - 1) qc.ry(theta_k, 0) qc.ry(-theta, 0) qc.measure(0, n_meas) return qc def build_delay_matched(theta, n_meas, meas_duration_dt): """Standard gate + idle delay = same wall-clock as Zeno. Ideal = |0>.""" qc = QuantumCircuit(1, 1) qc.ry(theta, 0) qc.delay(n_meas * meas_duration_dt, 0, unit='dt') qc.ry(-theta, 0) qc.measure(0, 0) return qc def build_delay_total(total_delay_dt): """Pure delay then measure. Ideal = |0>.""" qc = QuantumCircuit(1, 1) if total_delay_dt > 0: qc.delay(total_delay_dt, 0, unit='dt') qc.measure(0, 0) return qc def build_zeno_bare_gap(theta, n_meas, gap_dt): """Zeno drag with bare idle delay between measurements.""" qr = QuantumRegister(1, 'q') cr = ClassicalRegister(n_meas + 1, 'c') qc = QuantumCircuit(qr, cr) for k in range(1, n_meas + 1): theta_k = k * theta / n_meas qc.ry(-theta_k, 0) qc.measure(0, k - 1) qc.ry(theta_k, 0) if gap_dt > 0 and k < n_meas: qc.delay(gap_dt, 0, unit='dt') qc.ry(-theta, 0) qc.measure(0, n_meas) return qc def build_zeno_dd_gap(theta, n_meas, gap_dt): """Zeno drag with Hahn echo DD (delay/2 - X - delay/2) in gaps. The X-X echo refocuses low-frequency dephasing noise during idle gaps. Net unitary of DD sequence is identity (X^2 = I). """ qr = QuantumRegister(1, 'q') cr = ClassicalRegister(n_meas + 1, 'c') qc = QuantumCircuit(qr, cr) half_gap = gap_dt // 2 for k in range(1, n_meas + 1): theta_k = k * theta / n_meas qc.ry(-theta_k, 0) qc.measure(0, k - 1) qc.ry(theta_k, 0) if gap_dt > 0 and k < n_meas: qc.delay(half_gap, 0, unit='dt') qc.x(0) qc.delay(gap_dt - half_gap, 0, unit='dt') qc.x(0) qc.ry(-theta, 0) qc.measure(0, n_meas) return qc def build_identity_zeno_bare_gap(n_meas, gap_dt): """Identity Zeno (no rotation) with bare gap between measurements.""" qr = QuantumRegister(1, 'q') cr = ClassicalRegister(n_meas + 1, 'c') qc = QuantumCircuit(qr, cr) for k in range(n_meas): qc.measure(0, k) if gap_dt > 0 and k < n_meas - 1: qc.delay(gap_dt, 0, unit='dt') qc.measure(0, n_meas) return qc def build_cnot_standard(): """Standard: X(q0), CX round-trip, X(q0), measure both. Ideal = |00>.""" qc = QuantumCircuit(2, 2) qc.x(0) qc.cx(0, 1) qc.cx(0, 1) qc.x(0) qc.measure([0, 1], [0, 1]) return qc def build_cnot_zeno(n_meas): """Zeno drag q0 to |1>, CX round-trip, undo drag, measure both. Intermediate measurements on q0 track drag quality. Ideal = |00>. """ theta = np.pi qr = QuantumRegister(2, 'q') cr = ClassicalRegister(n_meas + 2, 'c') qc = QuantumCircuit(qr, cr) # Zeno drag q0 from |0> to |1> for k in range(1, n_meas + 1): theta_k = k * theta / n_meas qc.ry(-theta_k, 0) qc.measure(0, k - 1) qc.ry(theta_k, 0) # CX round-trip (q0=|1> flips q1, then flips back) qc.cx(0, 1) qc.cx(0, 1) # Undo the drag qc.ry(-theta, 0) # Final measurements qc.measure(0, n_meas) qc.measure(1, n_meas + 1) return qc # ============================================================================= # ANALYSIS # ============================================================================= def analyze_zeno(bitstrings, n_meas, p_meas): """Full Zeno analysis with soft k<=2 as primary metric.""" total = len(bitstrings) successful = 0 correct_given_success = 0 flip_bins = {} for bs in bitstrings: if len(bs) < n_meas + 1: continue final = bs[0] intermediate = bs[1:n_meas + 1] n_flips = sum(1 for b in intermediate if b == '1') if n_flips not in flip_bins: flip_bins[n_flips] = {'total': 0, 'correct': 0} flip_bins[n_flips]['total'] += 1 if final == '0': flip_bins[n_flips]['correct'] += 1 if n_flips == 0: successful += 1 if final == '0': correct_given_success += 1 success_rate = successful / total if total > 0 else 0 fidelity_hard = correct_given_success / successful if successful > 0 else 0 expected_meas_flips = n_meas * p_meas # Soft k<=2 (PRIMARY METRIC) sk2_c, sk2_t = 0, 0 for nf, data in flip_bins.items(): if nf <= 2: sk2_c += data['correct'] sk2_t += data['total'] fidelity_soft_k2 = sk2_c / sk2_t if sk2_t > 0 else 0 utilization_k2 = sk2_t / total if total > 0 else 0 effective_yield_k2 = sk2_c / total if total > 0 else 0 # Excess-flip w3_c, w3_t = 0, 0 for nf, data in flip_bins.items(): excess = max(0, nf - expected_meas_flips) w = np.exp(-excess) w3_c += w * data['correct'] w3_t += w * data['total'] fid_excess = w3_c / w3_t if w3_t > 0 else 0 # Likelihood ratio w4_c, w4_t = 0, 0 for nf, data in flip_bins.items(): if nf <= n_meas: p_target = comb(n_meas, nf, exact=True) * (p_meas ** nf) * ((1 - p_meas) ** (n_meas - nf)) p_random = comb(n_meas, nf, exact=True) * (0.5 ** n_meas) w = min(p_target / p_random, 1e10) if p_random > 0 else 0 else: w = 0 w4_c += w * data['correct'] w4_t += w * data['total'] fid_likelihood = w4_c / w4_t if w4_t > 0 else 0 all_flips = [] for nf, data in flip_bins.items(): all_flips.extend([nf] * data['total']) mean_flips = float(np.mean(all_flips)) if all_flips else 0 std_flips = float(np.std(all_flips)) if all_flips else 0 return { 'total': total, 'successful': successful, 'success_rate': success_rate, 'fidelity_hard_ps': fidelity_hard, 'fidelity_soft_k2': fidelity_soft_k2, 'utilization_k2': utilization_k2, 'effective_yield_k2': effective_yield_k2, 'fidelity_excess': fid_excess, 'fidelity_likelihood': fid_likelihood, 'expected_meas_flips': expected_meas_flips, 'mean_flips': mean_flips, 'std_flips': std_flips, 'flip_distribution': {str(k): v for k, v in sorted(flip_bins.items())}, 'type': 'zeno', } def analyze_standard(bitstrings): total = len(bitstrings) zeros = sum(1 for b in bitstrings if b[-1] == '0') return {'total': total, 'fidelity': zeros / total if total > 0 else 0, 'type': 'standard'} def analyze_vqe(bitstrings, theta): """Analyze VQE standard circuit: P(0) -> z_raw.""" total = len(bitstrings) p0 = sum(1 for bs in bitstrings if bs[-1] == '0') / total if total > 0 else 0.5 z_raw = 2 * p0 - 1 true_z = float(np.cos(theta)) return { 'total': total, 'p0': p0, 'z_raw': z_raw, 'true_z': true_z, 'error': z_raw - true_z, 'type': 'vqe_standard', } def analyze_two_qubit_zeno(bitstrings, n_meas, p_meas): """Analyze 2-qubit Zeno: intermediate on q0, final on both. Target = |00>.""" total = len(bitstrings) flip_bins = {} for bs in bitstrings: if len(bs) < n_meas + 2: continue final_q1 = bs[0] final_q0 = bs[1] intermediate = bs[2:n_meas + 2] n_flips = sum(1 for b in intermediate if b == '1') correct = 1 if (final_q0 == '0' and final_q1 == '0') else 0 if n_flips not in flip_bins: flip_bins[n_flips] = {'total': 0, 'correct': 0} flip_bins[n_flips]['total'] += 1 flip_bins[n_flips]['correct'] += correct # Soft k<=2 sk2_c, sk2_t = 0, 0 for nf, data in flip_bins.items(): if nf <= 2: sk2_c += data['correct'] sk2_t += data['total'] fidelity_soft_k2 = sk2_c / sk2_t if sk2_t > 0 else 0 # Hard PS hard_data = flip_bins.get(0, {'total': 0, 'correct': 0}) fidelity_hard = hard_data['correct'] / hard_data['total'] if hard_data['total'] > 0 else 0 # Raw (unweighted) raw_correct = sum(d['correct'] for d in flip_bins.values()) fidelity_raw = raw_correct / total if total > 0 else 0 return { 'total': total, 'fidelity_soft_k2': fidelity_soft_k2, 'fidelity_hard_ps': fidelity_hard, 'fidelity_raw': fidelity_raw, 'soft_k2_shots': sk2_t, 'hard_ps_shots': hard_data['total'], 'flip_distribution': {str(k): v for k, v in sorted(flip_bins.items())}, 'type': 'two_qubit_zeno', } def analyze_two_qubit_standard(bitstrings): """Analyze standard 2-qubit circuit. Target = |00>.""" total = len(bitstrings) correct = sum(1 for bs in bitstrings if all(b == '0' for b in bs)) return { 'total': total, 'fidelity': correct / total if total > 0 else 0, 'type': 'two_qubit_standard', } # ============================================================================= # MAIN # ============================================================================= def main(): print("=" * 70) print("ZENO MULTI-AXIS VALIDATION — DEFINITIVE EXPERIMENT") print("=" * 70) service = QiskitRuntimeService(channel="ibm_cloud", instance="claude") usage_before = check_usage(service) log(f"Usage: {usage_before['total']:.1f}s / 600s ({usage_before['percentage']:.1f}%)") log(f"Remaining: {usage_before['remaining']:.1f}s") if usage_before['remaining'] < 30: log("Less than 30s remaining. Aborting.") return reduced_mode = usage_before['remaining'] < 50 if reduced_mode: log("30-50s remaining — REDUCED mode (Sections A+B only, 28 circuits)") backend = service.backend("ibm_torino") log(f"Backend: {backend.name} ({backend.num_qubits}q)") # Hardware properties dt = backend.dt hw_target = backend.target shots = 4096 # Target qubits for Section A: low measurement error qubits # Q37 (1.0%), Q95 (2.7%), Q131 (1.8%) — replaces Q0 (11.6%) section_a_qubits = [37, 95, 131] qubit_info = {} for qi in section_a_qubits: try: props = backend.qubit_properties(qi) mp = hw_target['measure'][(qi,)] qubit_info[qi] = { 'T1_us': props.t1 * 1e6, 'T2_us': props.t2 * 1e6, 'meas_error': mp.error, 'meas_duration_dt': int(mp.duration / dt), } except Exception as e: log(f"WARNING: Could not get properties for Q{qi}: {e}") if 37 not in qubit_info: log("FATAL: Q37 properties unavailable. Cannot proceed.") return q37 = qubit_info[37] meas_err_37 = q37['meas_error'] meas_dt_37 = q37['meas_duration_dt'] for qi, info in sorted(qubit_info.items()): log(f"Q{qi}: T1={info['T1_us']:.1f}us, T2={info['T2_us']:.1f}us, " f"meas_err={info['meas_error']:.4f}", 1) # Find CX neighbor for Q37 (Section F) cx_neighbor = None if not reduced_mode: try: cm = backend.coupling_map # Get neighbors from coupling map edges neighbors = list(set( [j for (i, j) in cm.get_edges() if i == 37] + [i for (i, j) in cm.get_edges() if j == 37] )) if neighbors: best_neighbor = None best_err = 1.0 for n in neighbors: try: nerr = hw_target['measure'][(n,)].error if nerr < best_err: best_err = nerr best_neighbor = n except Exception: pass cx_neighbor = best_neighbor if cx_neighbor is not None: log(f"Section F: CX pair Q37-Q{cx_neighbor} " f"(neighbor meas_err={best_err:.4f})") else: log("Section F: No valid CX neighbor found. Skipping.") else: log("Section F: Q37 has no coupling map neighbors. Skipping.") except Exception as e: log(f"Section F: Could not query coupling map: {e}") # ========================================================================= # BUILD ALL EXPERIMENTS # ========================================================================= all_experiments = [] n_meas_default = 8 # --- SECTION A: Corrected Multi-Qubit Gate Comparison (18 circuits) --- log("Building Section A: Multi-qubit gate comparison...") for qi in section_a_qubits: if qi not in qubit_info: continue info = qubit_info[qi] for gate_name, theta in [('I', 0.0), ('X', np.pi)]: # Standard all_experiments.append(ExperimentConfig( name=f"a_q{qi}_{gate_name}_standard", circuit=build_standard(theta), category="standard", section="A", params={'qubit': qi, 'gate': gate_name, 'theta': theta, 'T1_us': info['T1_us'], 'meas_error': info['meas_error']}, target_qubits=[qi], )) # Zeno N=8 all_experiments.append(ExperimentConfig( name=f"a_q{qi}_{gate_name}_zeno", circuit=build_zeno(theta, n_meas_default), category="zeno", section="A", params={'qubit': qi, 'gate': gate_name, 'theta': theta, 'n_meas': n_meas_default, 'T1_us': info['T1_us'], 'meas_error': info['meas_error']}, target_qubits=[qi], )) # Delay-matched all_experiments.append(ExperimentConfig( name=f"a_q{qi}_{gate_name}_delay", circuit=build_delay_matched(theta, n_meas_default, info['meas_duration_dt']), category="delay_matched", section="A", params={'qubit': qi, 'gate': gate_name, 'theta': theta, 'n_meas': n_meas_default, 'T1_us': info['T1_us'], 'meas_error': info['meas_error']}, target_qubits=[qi], )) # --- SECTION B: Per-Theta VQE Calibration (10 circuits) --- log("Building Section B: Per-theta VQE calibration...") vqe_thetas = [0.2, 0.8, 1.5, 2.4, np.pi] for theta in vqe_thetas: theta_label = f"{theta:.2f}".replace('.', 'p') # Standard VQE (just Ry, no undo) all_experiments.append(ExperimentConfig( name=f"b_vqe_std_t{theta_label}", circuit=build_vqe_standard(theta), category="vqe_standard", section="B", params={'theta': theta, 'true_z': float(np.cos(theta))}, target_qubits=[37], )) # Zeno calibration (drag + undo, gives f(theta)) all_experiments.append(ExperimentConfig( name=f"b_vqe_zeno_t{theta_label}", circuit=build_zeno(theta, n_meas_default), category="zeno", section="B", params={'theta': theta, 'n_meas': n_meas_default, 'meas_error': meas_err_37}, target_qubits=[37], )) if not reduced_mode: # --- SECTION C: Adaptive-N (8 circuits) --- log("Building Section C: Adaptive-N Zeno...") adaptive_configs = [ (np.pi / 8, [4, 8]), (np.pi / 2, [4, 8, 12]), (np.pi, [8, 12, 16]), ] for theta, n_values in adaptive_configs: theta_label = f"{theta/np.pi:.3f}pi".replace('.', 'p') for n in n_values: all_experiments.append(ExperimentConfig( name=f"c_t{theta_label}_n{n}", circuit=build_zeno(theta, n), category="zeno", section="C", params={'theta': theta, 'n_meas': n, 'meas_error': meas_err_37}, target_qubits=[37], )) # --- SECTION D: Non-Uniform Schedule / STZ (6 circuits) --- log("Building Section D: STZ non-uniform schedule...") stz_thetas = [np.pi / 2, 3 * np.pi / 4, np.pi] for theta in stz_thetas: theta_label = f"{theta/np.pi:.3f}pi".replace('.', 'p') # Uniform (standard Zeno) all_experiments.append(ExperimentConfig( name=f"d_uniform_t{theta_label}", circuit=build_zeno(theta, n_meas_default), category="zeno_uniform", section="D", params={'theta': theta, 'n_meas': n_meas_default, 'schedule': 'uniform', 'meas_error': meas_err_37}, target_qubits=[37], )) # Sinusoidal (STZ) all_experiments.append(ExperimentConfig( name=f"d_stz_t{theta_label}", circuit=build_zeno_stz(theta, n_meas_default), category="zeno_stz", section="D", params={'theta': theta, 'n_meas': n_meas_default, 'schedule': 'sinusoidal', 'meas_error': meas_err_37}, target_qubits=[37], )) # --- SECTION E: Zeno-DD Hybrid (4 circuits) --- log("Building Section E: Zeno-DD hybrid...") gap_us = 10 gap_s = gap_us * 1e-6 gap_dt = int(gap_s / dt) theta_E = np.pi # X gate # 1. X Zeno + bare gap all_experiments.append(ExperimentConfig( name="e_x_zeno_bare_gap", circuit=build_zeno_bare_gap(theta_E, n_meas_default, gap_dt), category="zeno_bare_gap", section="E", params={'theta': theta_E, 'n_meas': n_meas_default, 'gap_us': gap_us, 'gap_dt': gap_dt, 'meas_error': meas_err_37}, target_qubits=[37], )) # 2. X Zeno + DD echo in gap all_experiments.append(ExperimentConfig( name="e_x_zeno_dd_gap", circuit=build_zeno_dd_gap(theta_E, n_meas_default, gap_dt), category="zeno_dd_gap", section="E", params={'theta': theta_E, 'n_meas': n_meas_default, 'gap_us': gap_us, 'gap_dt': gap_dt, 'meas_error': meas_err_37}, target_qubits=[37], )) # 3. Delay-matched baseline (same total time) total_delay_e = (n_meas_default * meas_dt_37 + (n_meas_default - 1) * gap_dt) all_experiments.append(ExperimentConfig( name="e_delay_matched", circuit=build_delay_total(total_delay_e), category="delay_matched", section="E", params={'theta': 0.0, 'total_delay_dt': total_delay_e, 'gap_us': gap_us}, target_qubits=[37], )) # 4. Identity Zeno + bare gap (control) all_experiments.append(ExperimentConfig( name="e_identity_zeno_bare_gap", circuit=build_identity_zeno_bare_gap(n_meas_default, gap_dt), category="identity_zeno_bare_gap", section="E", params={'theta': 0.0, 'n_meas': n_meas_default, 'gap_us': gap_us, 'gap_dt': gap_dt, 'meas_error': meas_err_37}, target_qubits=[37], )) # --- SECTION F: Two-Qubit Zeno with Soft Weighting (2 circuits) --- if cx_neighbor is not None: log(f"Building Section F: Two-qubit Zeno on Q37-Q{cx_neighbor}...") # Standard CNOT round-trip all_experiments.append(ExperimentConfig( name="f_cnot_standard", circuit=build_cnot_standard(), category="two_qubit_standard", section="F", params={'control': 37, 'target_qubit': cx_neighbor}, target_qubits=[37, cx_neighbor], )) # Zeno CNOT round-trip all_experiments.append(ExperimentConfig( name="f_cnot_zeno", circuit=build_cnot_zeno(n_meas_default), category="two_qubit_zeno", section="F", params={'control': 37, 'target_qubit': cx_neighbor, 'n_meas': n_meas_default, 'meas_error': meas_err_37}, target_qubits=[37, cx_neighbor], )) section_counts = {} for exp in all_experiments: section_counts[exp.section] = section_counts.get(exp.section, 0) + 1 for s, c in sorted(section_counts.items()): log(f"Section {s}: {c} circuits", 1) log(f"Total circuits: {len(all_experiments)}") # ========================================================================= # TRANSPILE (with per-qubit initial_layout) # ========================================================================= log("Transpiling...") pm_cache = {} transpiled = [] valid_experiments = [] for exp in all_experiments: layout_key = tuple(exp.target_qubits) if layout_key not in pm_cache: pm_cache[layout_key] = generate_preset_pass_manager( backend=backend, optimization_level=1, initial_layout=list(layout_key), ) try: tc = pm_cache[layout_key].run(exp.circuit) transpiled.append(tc) valid_experiments.append(exp) except Exception as e: log(f"ERROR transpiling {exp.name}: {e}") log(f"Transpiled: {len(transpiled)}/{len(all_experiments)}") if not transpiled: log("No circuits transpiled. Aborting.") return depths = [tc.depth() for tc in transpiled] log(f"Depths: min={min(depths)}, max={max(depths)}") for i, exp in enumerate(valid_experiments): exp.params['transpiled_depth'] = depths[i] # ========================================================================= # SUBMIT # ========================================================================= log("Submitting batch...") start_time = datetime.now(timezone.utc) with Batch(backend=backend) as batch: sampler = SamplerV2(mode=batch) job = sampler.run(transpiled, shots=shots) log(f"Job ID: {job.job_id()}") log("Waiting...") job.wait_for_final_state() end_time = datetime.now(timezone.utc) wall_time = (end_time - start_time).total_seconds() log(f"Done. Wall time: {wall_time:.1f}s, QPU: {job.usage() or 0}s") # ========================================================================= # PARSE RESULTS # ========================================================================= result = job.result() metrics = job.metrics() results_data = {} for i, exp in enumerate(valid_experiments): pub_result = result[i] data_bin = pub_result.data if hasattr(data_bin, 'c'): bitstrings = list(data_bin.c.get_bitstrings()) elif hasattr(data_bin, 'meas'): bitstrings = list(data_bin.meas.get_bitstrings()) else: cr_name = list(data_bin.keys())[0] bitstrings = list(getattr(data_bin, cr_name).get_bitstrings()) p_meas = exp.params.get('meas_error', meas_err_37) n_meas = exp.params.get('n_meas', 0) if exp.category == 'two_qubit_zeno': analysis = analyze_two_qubit_zeno(bitstrings, n_meas, p_meas) elif exp.category == 'two_qubit_standard': analysis = analyze_two_qubit_standard(bitstrings) elif exp.category == 'vqe_standard': analysis = analyze_vqe(bitstrings, exp.params['theta']) elif 'zeno' in exp.category: analysis = analyze_zeno(bitstrings, n_meas, p_meas) else: analysis = analyze_standard(bitstrings) results_data[exp.name] = { 'section': exp.section, 'category': exp.category, 'params': {k: (float(v) if isinstance(v, (np.floating, float)) else v) for k, v in exp.params.items()}, 'analysis': analysis, 'raw_bitstrings': bitstrings, # all 4096, not truncated } # ========================================================================= # SECTION A ANALYSIS # ========================================================================= print("\n" + "=" * 70) print("SECTION A: CORRECTED MULTI-QUBIT GATE COMPARISON (W1 fix)") print("=" * 70) print(f"\n {'Qubit':>5} | {'MeasErr':>7} | {'Gate':>4} | {'Standard':>8} | " f"{'Zeno k2':>8} | {'Delay':>7} | {'Z-Std':>7} | {'Z-Delay':>7}") print(" " + "-" * 70) a_improvements_I = [] a_improvements_X = [] for qi in section_a_qubits: if qi not in qubit_info: continue for gate_name in ['I', 'X']: std_key = f"a_q{qi}_{gate_name}_standard" zen_key = f"a_q{qi}_{gate_name}_zeno" del_key = f"a_q{qi}_{gate_name}_delay" std_fid = results_data.get(std_key, {}).get('analysis', {}).get('fidelity', 0) zen_k2 = results_data.get(zen_key, {}).get('analysis', {}).get('fidelity_soft_k2', 0) del_fid = results_data.get(del_key, {}).get('analysis', {}).get('fidelity', 0) merr = qubit_info[qi]['meas_error'] imp = zen_k2 - std_fid if gate_name == 'I': a_improvements_I.append(imp) else: a_improvements_X.append(imp) print(f" Q{qi:>3} | {merr:7.4f} | {gate_name:>4} | {std_fid:8.4f} | " f"{zen_k2:8.4f} | {del_fid:7.4f} | {imp:+7.4f} | " f"{zen_k2-del_fid:+7.4f}") i_wins = sum(1 for x in a_improvements_I if x > 0) x_wins = sum(1 for x in a_improvements_X if x > 0) n_qubits_tested = len([q for q in section_a_qubits if q in qubit_info]) print(f"\n I gate: Zeno improvement on {i_wins}/{n_qubits_tested} qubits") print(f" X gate: Zeno improvement on {x_wins}/{n_qubits_tested} qubits") # ========================================================================= # SECTION B ANALYSIS # ========================================================================= print("\n" + "=" * 70) print("SECTION B: PER-THETA VQE CALIBRATION (W4 fix)") print("=" * 70) print(f"\n {'theta':>7} | {'cos(t)':>7} | {'z_raw':>7} | {'f(t) k2':>8} | " f"{'err_std':>8} | {'err_glob':>8} | {'err_per':>8}") print(" " + "-" * 70) z_raws = [] fidelities_b = [] true_zs = [] for theta in vqe_thetas: theta_label = f"{theta:.2f}".replace('.', 'p') std_key = f"b_vqe_std_t{theta_label}" zen_key = f"b_vqe_zeno_t{theta_label}" vqe_a = results_data.get(std_key, {}).get('analysis', {}) zen_a = results_data.get(zen_key, {}).get('analysis', {}) z_raw = vqe_a.get('z_raw', 0) true_z = float(np.cos(theta)) f_theta = zen_a.get('fidelity_soft_k2', 0.5) z_raws.append(z_raw) fidelities_b.append(f_theta) true_zs.append(true_z) f_global = np.mean(fidelities_b) if fidelities_b else 0.5 std_errors_sq = [] glob_errors_sq = [] per_errors_sq = [] for i, theta in enumerate(vqe_thetas): z_raw = z_raws[i] f_theta = fidelities_b[i] true_z = true_zs[i] err_std = z_raw - true_z denom_glob = 2 * f_global - 1 z_glob = z_raw / denom_glob if abs(denom_glob) > 0.01 else z_raw z_glob = max(-1.0, min(1.0, z_glob)) err_glob = z_glob - true_z denom_per = 2 * f_theta - 1 z_per = z_raw / denom_per if abs(denom_per) > 0.01 else z_raw z_per = max(-1.0, min(1.0, z_per)) err_per = z_per - true_z std_errors_sq.append(err_std ** 2) glob_errors_sq.append(err_glob ** 2) per_errors_sq.append(err_per ** 2) print(f" {theta:7.3f} | {true_z:+7.4f} | {z_raw:+7.4f} | {f_theta:8.4f} | " f"{err_std:+8.4f} | {err_glob:+8.4f} | {err_per:+8.4f}") rmse_std = float(np.sqrt(np.mean(std_errors_sq))) if std_errors_sq else 0 rmse_glob = float(np.sqrt(np.mean(glob_errors_sq))) if glob_errors_sq else 0 rmse_per = float(np.sqrt(np.mean(per_errors_sq))) if per_errors_sq else 0 print(f"\n RMSE standard: {rmse_std:.4f}") print(f" RMSE global-f: {rmse_glob:.4f} (f_global={f_global:.4f})") print(f" RMSE per-theta: {rmse_per:.4f}") if rmse_per < rmse_glob < rmse_std: print(" RESULT: per-theta < global < standard") elif rmse_per < rmse_std: print(" RESULT: per-theta improves over standard") else: print(" RESULT: correction does not improve RMSE — honest result") if not reduced_mode: # ================================================================= # SECTION C ANALYSIS # ================================================================= print("\n" + "=" * 70) print("SECTION C: ADAPTIVE-N ZENO") print("=" * 70) print(f"\n {'theta':>8} | {'N':>3} | {'k2 fid':>7} | {'k2 yield':>8} | " f"{'hard PS':>7} | {'success':>7} | {'excess':>7}") print(" " + "-" * 65) for theta, n_values in adaptive_configs: for n in n_values: theta_label = f"{theta/np.pi:.3f}pi".replace('.', 'p') key = f"c_t{theta_label}_n{n}" a = results_data.get(key, {}).get('analysis', {}) fk2 = a.get('fidelity_soft_k2', 0) yk2 = a.get('effective_yield_k2', 0) fh = a.get('fidelity_hard_ps', 0) sr = a.get('success_rate', 0) fe = a.get('fidelity_excess', 0) print(f" {theta/np.pi:6.3f}pi | {n:3d} | {fk2:7.4f} | {yk2:8.4f} | " f"{fh:7.4f} | {sr*100:6.1f}% | {fe:7.4f}") print() # Check: does N=4 suffice for small angles? pi8_n4 = results_data.get( f"c_t{(np.pi/8/np.pi):.3f}pi_n4".replace('.', 'p'), {} ).get('analysis', {}).get('fidelity_soft_k2', 0) pi8_n8 = results_data.get( f"c_t{(np.pi/8/np.pi):.3f}pi_n8".replace('.', 'p'), {} ).get('analysis', {}).get('fidelity_soft_k2', 0) if pi8_n4 > 0 and pi8_n8 > 0: diff = pi8_n8 - pi8_n4 print(f" pi/8: N=4 vs N=8 fidelity gap: {diff:+.4f}") if abs(diff) < 0.02: print(" -> N=4 suffices for small angles (2x shallower)") else: print(" -> N=8 still meaningfully better") # ================================================================= # SECTION D ANALYSIS # ================================================================= print("\n" + "=" * 70) print("SECTION D: NON-UNIFORM SCHEDULE (STZ)") print("=" * 70) print(f"\n {'theta':>8} | {'Schedule':>10} | {'k2 fid':>7} | " f"{'k2 yield':>8} | {'excess':>7} | {'diff':>7}") print(" " + "-" * 60) d_diffs = [] for theta in stz_thetas: theta_label = f"{theta/np.pi:.3f}pi".replace('.', 'p') uni_key = f"d_uniform_t{theta_label}" stz_key = f"d_stz_t{theta_label}" uni_a = results_data.get(uni_key, {}).get('analysis', {}) stz_a = results_data.get(stz_key, {}).get('analysis', {}) uni_k2 = uni_a.get('fidelity_soft_k2', 0) stz_k2 = stz_a.get('fidelity_soft_k2', 0) uni_y = uni_a.get('effective_yield_k2', 0) stz_y = stz_a.get('effective_yield_k2', 0) uni_e = uni_a.get('fidelity_excess', 0) stz_e = stz_a.get('fidelity_excess', 0) diff_pp = (stz_k2 - uni_k2) * 100 d_diffs.append(abs(stz_k2 - uni_k2)) print(f" {theta/np.pi:6.3f}pi | {'uniform':>10} | {uni_k2:7.4f} | " f"{uni_y:8.4f} | {uni_e:7.4f} |") print(f" {'':>8} | {'sinusoidal':>10} | {stz_k2:7.4f} | " f"{stz_y:8.4f} | {stz_e:7.4f} | {diff_pp:+6.1f}pp") any_gt_half = any(d > 0.005 for d in d_diffs) print(f"\n >0.5pp difference for any angle: {any_gt_half}") # ================================================================= # SECTION E ANALYSIS # ================================================================= print("\n" + "=" * 70) print("SECTION E: ZENO-DD HYBRID") print("=" * 70) e_configs = [ ("X Zeno + bare gap", "e_x_zeno_bare_gap", True), ("X Zeno + DD echo", "e_x_zeno_dd_gap", True), ("Delay-matched", "e_delay_matched", False), ("I Zeno + bare gap", "e_identity_zeno_bare_gap", True), ] print(f"\n {'Variant':>22} | {'k2 fid':>7} | {'k2 yield':>8} | " f"{'excess':>7} | {'fidelity':>8}") print(" " + "-" * 60) for label, key, is_zeno in e_configs: a = results_data.get(key, {}).get('analysis', {}) if is_zeno: fk2 = a.get('fidelity_soft_k2', 0) yk2 = a.get('effective_yield_k2', 0) fe = a.get('fidelity_excess', 0) print(f" {label:>22} | {fk2:7.4f} | {yk2:8.4f} | " f"{fe:7.4f} | {'---':>8}") else: fid = a.get('fidelity', 0) print(f" {label:>22} | {'---':>7} | {'---':>8} | " f"{'---':>7} | {fid:8.4f}") bare_k2 = (results_data.get("e_x_zeno_bare_gap", {}) .get('analysis', {}).get('fidelity_soft_k2', 0)) dd_k2 = (results_data.get("e_x_zeno_dd_gap", {}) .get('analysis', {}).get('fidelity_soft_k2', 0)) print(f"\n DD improvement over bare gap: {(dd_k2 - bare_k2)*100:+.1f}pp") # ================================================================= # SECTION F ANALYSIS # ================================================================= if cx_neighbor is not None and 'f_cnot_standard' in results_data: print("\n" + "=" * 70) print(f"SECTION F: TWO-QUBIT ZENO (Q37-Q{cx_neighbor})") print("=" * 70) std_f = results_data['f_cnot_standard']['analysis'] zen_f = results_data.get('f_cnot_zeno', {}).get('analysis', {}) std_fid = std_f.get('fidelity', 0) zen_k2 = zen_f.get('fidelity_soft_k2', 0) zen_hard = zen_f.get('fidelity_hard_ps', 0) zen_raw = zen_f.get('fidelity_raw', 0) print(f"\n Standard CNOT round-trip: {std_fid:.4f}") print(f" Zeno CNOT (hard PS): {zen_hard:.4f} " f"({zen_f.get('hard_ps_shots', 0)} shots)") print(f" Zeno CNOT (soft k<=2): {zen_k2:.4f} " f"({zen_f.get('soft_k2_shots', 0)} shots)") print(f" Zeno CNOT (raw): {zen_raw:.4f}") print(f" Improvement (k2-std): {zen_k2 - std_fid:+.4f}") # ========================================================================= # SAVE # ========================================================================= output = { 'experiment': 'zeno_multiaxis', 'description': ( 'Definitive experiment: corrects W1-W6 weakness failures and tests ' 'adaptive-N, STZ scheduling, DD hybrids, soft-weighted two-qubit ' 'operations. Primary metric: soft k<=2 effective yield.' ), 'timestamp': start_time.isoformat(), 'backend': backend.name, 'shots': shots, 'job_id': job.job_id(), 'usage_seconds': job.usage() or 0, 'wall_time_seconds': wall_time, 'metrics': metrics, 'reduced_mode': reduced_mode, 'hardware': { 'dt_ns': dt * 1e9, 'qubit_info': {str(k): v for k, v in qubit_info.items()}, 'cx_neighbor': cx_neighbor, }, 'sections': {}, 'results': results_data, } # Section-level summaries for section_id in ['A', 'B', 'C', 'D', 'E', 'F']: section_results = {k: v for k, v in results_data.items() if v['section'] == section_id} if section_results: output['sections'][section_id] = { 'n_circuits': len(section_results), 'circuit_names': list(section_results.keys()), } # VQE RMSE summary output['sections'].setdefault('B', {}).update({ 'rmse_standard': rmse_std, 'rmse_global': rmse_glob, 'rmse_pertheta': rmse_per, 'f_global': float(f_global), }) RESULTS_DIR.mkdir(parents=True, exist_ok=True) outfile = RESULTS_DIR / 'zeno_multiaxis.json' with open(outfile, 'w') as f: json.dump(output, f, indent=2, default=str) log(f"Saved: {outfile}") # ========================================================================= # SUMMARY # ========================================================================= print("\n" + "=" * 70) print("SUMMARY") print("=" * 70) print(f"\n Total circuits: {len(valid_experiments)}") print(f" QPU time: {job.usage() or 0}s") print(f" Wall time: {wall_time:.1f}s") for s, c in sorted(section_counts.items()): print(f" Section {s}: {c} circuits") usage_after = check_usage(service) log(f"\nUsage: {usage_after['total']:.1f}s / 600s " f"({usage_after['percentage']:.1f}%)") log(f"Remaining: {usage_after['remaining']:.1f}s") if __name__ == '__main__': try: main() except KeyboardInterrupt: log("Interrupted.") sys.exit(1) except Exception as e: log(f"FATAL: {e}") import traceback traceback.print_exc() sys.exit(1)