""" Zeno Extreme — N=512 and N=1024 N=512: 800μs, 6.9× T1 N=1024: 1597μs, 13.9× T1 Is the 3pp decline from N=8 to N=256 a slow linear death or an asymptote? """ 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_standard(theta): qc = QuantumCircuit(1, 1) qc.ry(theta, 0) qc.ry(-theta, 0) qc.measure(0, 0) return qc def build_zeno(theta, n_meas): 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(theta, n_meas, meas_duration_dt): 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 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 # Calibrated exp(-α·k) alpha = np.log(2) / max(expected_meas_flips, 1) w2_c, w2_t = 0, 0 for nf, data in flip_bins.items(): w = np.exp(-alpha * nf) w2_c += w * data['correct'] w2_t += w * data['total'] fid_calibrated = w2_c / w2_t if w2_t > 0 else 0 # Excess-flip beta = 1.0 w3_c, w3_t = 0, 0 for nf, data in flip_bins.items(): excess = max(0, nf - expected_meas_flips) w = np.exp(-beta * 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_calibrated': fid_calibrated, 'fidelity_excess': fid_excess, 'fidelity_likelihood': fid_likelihood, 'expected_meas_flips': expected_meas_flips, 'mean_flips': mean_flips, 'std_flips': std_flips, 'alpha_used': alpha, '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 EXTREME — N=512 AND N=1024") 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 sx_duration_s = target_obj['sx'][(0,)].duration 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") theta = np.pi # Include N=256 for continuity with previous experiment n_values = [256, 512, 1024] shots = 4096 print(f"\nExperiment plan:") print(f"{'N':>5} | {'Time(us)':>8} | {'T1 mult':>7} | {'Exp flips':>9} | {'Depth est':>9}") print("-" * 50) for n in n_values: t_us = n * meas_duration_s * 1e6 t1_mult = n * meas_duration_s / T1 exp_flips = n * meas_error depth_est = n * 5 # rough: each step ~5 native gates print(f"{n:5d} | {t_us:8.1f} | {t1_mult:7.1f}x | {exp_flips:9.1f} | {depth_est:9d}") all_experiments = [] # Standard baseline all_experiments.append(ExperimentConfig( name="standard_X", circuit=build_standard(theta), category="standard", params={'gate': 'X', 'theta': theta, 'n_meas': 0}, )) for n in n_values: total_time_us = n * meas_duration_s * 1e6 t1_mult = n * meas_duration_s / T1 all_experiments.append(ExperimentConfig( name=f"zeno_X_N{n}", circuit=build_zeno(theta, n), category="zeno", params={'gate': 'X', 'theta': theta, 'n_meas': n, 'total_time_us': total_time_us, 'T1_multiple': t1_mult}, )) all_experiments.append(ExperimentConfig( name=f"delay_X_N{n}", circuit=build_delay_matched(theta, n, meas_duration_dt), category="delay_matched", params={'gate': 'X', 'theta': theta, '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 exp.category == 'zeno': 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_extreme', 'description': 'Zeno at N=512 and N=1024 — 6.9x and 13.9x T1', '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, 'sx_duration_ns': sx_duration_s * 1e9, 'qubit_0_T1_us': T1 * 1e6, 'qubit_0_T2_us': T2 * 1e6, }, 'results': results_data, } outfile = DATA_DIR / 'results' / 'zeno_extreme' / 'zeno_extreme.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}") # ========================================================================= # RESULTS # ========================================================================= print("\n" + "=" * 70) print("ZENO EXTREME") print("=" * 70) std_fid = results_data['standard_X']['analysis']['fidelity'] print(f"\nStandard X gate: {std_fid:.4f}") print(f"Qubit 0 T1: {T1*1e6:.1f} us") print(f"\n{'N':>5} | {'Time':>7} | {'×T1':>5} | {'exp(-k)':>7} | {'Excess':>7} | {'LikeR':>7} | {'Delay':>7} | {'Gap':>7} | {'Flips':>12}") print("-" * 85) for n in n_values: zk = f"zeno_X_N{n}" dk = f"delay_X_N{n}" if zk not in results_data or dk not in results_data: continue za = results_data[zk]['analysis'] da = results_data[dk]['analysis'] t_us = results_data[zk]['params']['total_time_us'] t1m = results_data[zk]['params']['T1_multiple'] best = max(za['fidelity_excess'], za['fidelity_likelihood']) gap = best - da['fidelity'] print(f"{n:5d} | {t_us:5.0f}us | {t1m:4.1f}x | {za['fidelity_exp_k']:.4f} | " f"{za['fidelity_excess']:.4f} | {za['fidelity_likelihood']:.4f} | " f"{da['fidelity']:.4f} | {gap:+.4f} | {za['mean_flips']:.1f}±{za['std_flips']:.1f}") # Combined table with previous results print(f"\n{'=' * 70}") print("COMBINED: Full N sweep (from all three experiments)") print(f"{'=' * 70}") print(f"\n{'N':>5} | {'Time':>7} | {'×T1':>6} | {'Excess':>7} | {'Delay':>7} | {'Gap':>7}") print("-" * 55) # Hardcode previous results for the combined view prev = { 8: {'excess': None, 'delay': None}, # will come from this run's N=256 continuity 32: {'excess': 0.9160, 'delay': 0.5571}, 64: {'excess': 0.9022, 'delay': 0.4060}, 128: {'excess': 0.8647, 'delay': 0.2498}, 256: {'excess': 0.8510, 'delay': 0.1826}, } for n, p in sorted(prev.items()): if p['excess'] is not None: t_us = n * meas_duration_s * 1e6 t1m = n * meas_duration_s / T1 gap = p['excess'] - p['delay'] print(f"{n:5d} | {t_us:5.0f}us | {t1m:5.1f}x | {p['excess']:.4f} | {p['delay']:.4f} | {gap:+.4f}") for n in [512, 1024]: zk = f"zeno_X_N{n}" dk = f"delay_X_N{n}" if zk in results_data and dk in results_data: za = results_data[zk]['analysis'] da = results_data[dk]['analysis'] t_us = results_data[zk]['params']['total_time_us'] t1m = results_data[zk]['params']['T1_multiple'] gap = za['fidelity_excess'] - da['fidelity'] print(f"{n:5d} | {t_us:5.0f}us | {t1m:5.1f}x | {za['fidelity_excess']:.4f} | {da['fidelity']:.4f} | {gap:+.4f}") 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)