""" Zeno Diagnostic — Is the decline from gate errors or measurement mechanism? Identity Zeno (theta=0): just measure the qubit repeatedly, no rotations. If identity stays at 95% while X declined to 77% at N=1024, the decline is from accumulated Ry gate errors. If identity also declines, it's the measurement mechanism itself. """ import json import sys from datetime import datetime, timezone from dataclasses import dataclass 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") @dataclass class ExperimentConfig: name: str circuit: QuantumCircuit category: str params: dict 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} def build_identity_zeno(n_meas): """Zeno freeze: just measure |0> repeatedly. No rotations. Ideal = |0>.""" qr = QuantumRegister(1, 'q') cr = ClassicalRegister(n_meas + 1, 'c') qc = QuantumCircuit(qr, cr) for k in range(n_meas): qc.measure(0, k) qc.measure(0, n_meas) return qc def build_x_zeno(n_meas): """Zeno drag 0->pi via N measurements, then undo. Ideal = |0>. (For comparison.)""" theta = np.pi 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_delay_matched(n_meas, meas_duration_dt): """Identity + delay = same wall-clock. Ideal = |0>.""" qc = QuantumCircuit(1, 1) qc.delay(n_meas * meas_duration_dt, 0, unit='dt') qc.measure(0, 0) return qc def analyze_zeno(bitstrings, n_meas, p_meas): 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 # exp(-k) w1_c, w1_t = 0, 0 for nf, data in flip_bins.items(): w = np.exp(-nf) w1_c += w * data['correct'] w1_t += w * data['total'] fid_exp_k = w1_c / w1_t if w1_t > 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 = np.mean(all_flips) if all_flips else 0 std_flips = np.std(all_flips) if all_flips else 0 return { 'total': total, 'successful': successful, 'success_rate': success_rate, 'fidelity_hard_ps': fidelity_hard, 'fidelity_exp_k': fid_exp_k, '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, 'type': 'standard'} def main(): print("=" * 70) print("ZENO DIAGNOSTIC — GATE ERRORS OR MEASUREMENT MECHANISM?") print("=" * 70) service = QiskitRuntimeService(channel="ibm_cloud", instance="claude") usage_before = check_usage(service) log(f"Usage: {usage_before['total']}s / 600s ({usage_before['percentage']:.1f}%)") log(f"Remaining: {usage_before['remaining']}s") if usage_before['remaining'] < 30: log("Less than 30s remaining. Aborting.") return backend = service.backend("ibm_torino") log(f"Backend: {backend.name} ({backend.num_qubits}q)") dt = backend.dt target_obj = backend.target meas_props = target_obj['measure'][(0,)] meas_duration_s = meas_props.duration meas_duration_dt = int(meas_duration_s / dt) meas_error = meas_props.error props = backend.qubit_properties(0) T1 = props.t1 T2 = props.t2 log(f"Measurement: {meas_duration_s*1e6:.3f} us, error={meas_error:.4f}") log(f"Qubit 0: T1={T1*1e6:.1f} us, T2={T2*1e6:.1f} us") n_values = [32, 128, 256, 512, 1024] shots = 4096 all_experiments = [] for n in n_values: total_time_us = n * meas_duration_s * 1e6 t1_mult = n * meas_duration_s / T1 # Identity Zeno — no rotations all_experiments.append(ExperimentConfig( name=f"identity_zeno_N{n}", circuit=build_identity_zeno(n), category="identity_zeno", params={'gate': 'I', 'theta': 0, 'n_meas': n, 'total_time_us': total_time_us, 'T1_multiple': t1_mult}, )) # X Zeno — with rotations (for direct comparison) all_experiments.append(ExperimentConfig( name=f"x_zeno_N{n}", circuit=build_x_zeno(n), category="x_zeno", params={'gate': 'X', 'theta': np.pi, 'n_meas': n, 'total_time_us': total_time_us, 'T1_multiple': t1_mult}, )) # Delay-matched all_experiments.append(ExperimentConfig( name=f"delay_N{n}", circuit=build_delay_matched(n, meas_duration_dt), category="delay", params={'gate': 'I', 'theta': 0, 'n_meas': n, 'total_time_us': total_time_us, 'T1_multiple': t1_mult}, )) log(f"Total experiments: {len(all_experiments)}") log("Transpiling...") pm = generate_preset_pass_manager(backend=backend, optimization_level=1) transpiled = [] for exp in all_experiments: try: tc = pm.run(exp.circuit) transpiled.append(tc) except Exception as e: log(f"ERROR transpiling {exp.name}: {e}") transpiled.append(None) valid_indices = [i for i, tc in enumerate(transpiled) if tc is not None] valid_transpiled = [transpiled[i] for i in valid_indices] valid_experiments = [all_experiments[i] for i in valid_indices] log(f"Transpiled: {len(valid_transpiled)}/{len(all_experiments)}") depths = [tc.depth() for tc in valid_transpiled] log(f"Depths: min={min(depths)}, max={max(depths)}") for i, exp in enumerate(valid_experiments): exp.params['transpiled_depth'] = depths[i] log("Submitting batch...") start_time = datetime.now(timezone.utc) with Batch(backend=backend) as batch: sampler = SamplerV2(mode=batch) job = sampler.run(valid_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") 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()) if 'zeno' in exp.category: analysis = analyze_zeno(bitstrings, exp.params['n_meas'], meas_error) else: analysis = analyze_standard(bitstrings) results_data[exp.name] = { '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[:500], } # Save output = { 'experiment': 'zeno_diagnostic', 'description': 'Diagnose Zeno fidelity decline: gate errors vs measurement mechanism', '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, 'hardware_timing': { 'dt_ns': dt * 1e9, 'measurement_duration_us': meas_duration_s * 1e6, 'measurement_duration_dt': meas_duration_dt, 'measurement_error': meas_error, 'qubit_0_T1_us': T1 * 1e6, 'qubit_0_T2_us': T2 * 1e6, }, 'results': results_data, } outfile = DATA_DIR / 'results' / 'zeno_diagnostic' / 'zeno_diagnostic.json' outfile.parent.mkdir(exist_ok=True) with open(outfile, 'w') as f: json.dump(output, f, indent=2, default=str) log(f"Saved: {outfile}") # ========================================================================= # THE ANSWER # ========================================================================= print("\n" + "=" * 70) print("DIAGNOSTIC: IDENTITY ZENO vs X ZENO vs DELAY") print("=" * 70) print(f"\n{'N':>5} | {'×T1':>5} | {'I Zeno(exc)':>11} | {'X Zeno(exc)':>11} | {'Delay':>7} | {'I-X gap':>7} | {'I flips':>10} | {'X flips':>10}") print("-" * 90) for n in n_values: ik = f"identity_zeno_N{n}" xk = f"x_zeno_N{n}" dk = f"delay_N{n}" if not all(k in results_data for k in [ik, xk, dk]): continue ia = results_data[ik]['analysis'] xa = results_data[xk]['analysis'] da = results_data[dk]['analysis'] t1m = results_data[ik]['params']['T1_multiple'] gap = ia['fidelity_excess'] - xa['fidelity_excess'] print(f"{n:5d} | {t1m:4.1f}x | {ia['fidelity_excess']:11.4f} | {xa['fidelity_excess']:11.4f} | " f"{da['fidelity']:7.4f} | {gap:+7.4f} | {ia['mean_flips']:4.1f}±{ia['std_flips']:<4.1f} | " f"{xa['mean_flips']:4.1f}±{xa['std_flips']:<4.1f}") print(f"\n{'=' * 70}") print("VERDICT") print(f"{'=' * 70}") # Compare decline rates i_fids = [] x_fids = [] for n in n_values: ik = f"identity_zeno_N{n}" xk = f"x_zeno_N{n}" if ik in results_data and xk in results_data: i_fids.append(results_data[ik]['analysis']['fidelity_excess']) x_fids.append(results_data[xk]['analysis']['fidelity_excess']) i_decline = i_fids[0] - i_fids[-1] x_decline = x_fids[0] - x_fids[-1] print(f"\n Identity Zeno decline (N={n_values[0]} to N={n_values[-1]}): {i_decline:+.4f}") print(f" X gate Zeno decline (N={n_values[0]} to N={n_values[-1]}): {x_decline:+.4f}") print(f" Difference: {x_decline - i_decline:.4f}") if i_decline < 0.05 and x_decline > 0.10: print(f"\n GATE ERRORS are the bottleneck.") print(f" Identity Zeno holds steady — the measurement mechanism works.") print(f" X Zeno declines — accumulated Ry rotation errors cause the drop.") print(f" Better gates would eliminate the decline.") elif abs(i_decline - x_decline) < 0.05: print(f"\n MEASUREMENT MECHANISM is the bottleneck.") print(f" Both identity and X decline similarly.") print(f" The rotations aren't the problem — repeated measurement itself degrades fidelity.") else: print(f"\n MIXED: both contribute.") print(f" Identity decline: {i_decline:.4f}") print(f" X decline: {x_decline:.4f}") print(f" Gate errors account for ~{(x_decline - i_decline)/x_decline*100:.0f}% of the decline.") usage_after = check_usage(service) log(f"\nUsage: {usage_after['total']}s / 600s ({usage_after['percentage']:.1f}%)") log(f"This job: {job.usage() or 0}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)