""" Push Zeno Past T1 Extend Zeno dragging to N = 48, 64, 96, 128, 192, 256. Total circuit times: 75μs to 400μs — up to 3.5× T1. At these N values, hard post-selection is dead (success probability ≈ 0). Trajectory weighting is essential. We implement multiple schemes: 1. exp(-k): original, too aggressive for high N 2. exp(-α·k) with α calibrated to measurement error rate 3. Excess-flip: exp(-β·max(0, k - N·p_meas)) — penalize only flips beyond what measurement error alone would produce 4. Binomial likelihood ratio: P(k flips | qubit OK) / P(k flips | random) The claim: Zeno projective measurements can maintain quantum coherence indefinitely beyond the natural lifetime of the qubit. """ import json import sys from datetime import datetime, timezone from dataclasses import dataclass from pathlib import Path import numpy as np from scipy import stats as sp_stats 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): from datetime import datetime, timezone 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_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_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 # ============================================================================= # ANALYSIS — multiple weighting schemes # ============================================================================= def analyze_zeno(bitstrings, n_meas, p_meas): """ Full Zeno analysis with multiple trajectory weighting schemes. p_meas: measurement error probability (from calibration data) """ 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 flips from measurement error alone (qubit is fine, detector lies) expected_meas_flips = n_meas * p_meas # Weighting scheme 1: exp(-k) — original w1_correct = 0 w1_total = 0 for nf, data in flip_bins.items(): w = np.exp(-nf) w1_correct += w * data['correct'] w1_total += w * data['total'] fid_exp_k = w1_correct / w1_total if w1_total > 0 else 0 # Weighting scheme 2: exp(-α·k) with α calibrated # α chosen so that exp(-α·expected_flips) ≈ 0.5 — half-weight at the # expected measurement error count alpha = np.log(2) / max(expected_meas_flips, 1) w2_correct = 0 w2_total = 0 for nf, data in flip_bins.items(): w = np.exp(-alpha * nf) w2_correct += w * data['correct'] w2_total += w * data['total'] fid_calibrated = w2_correct / w2_total if w2_total > 0 else 0 # Weighting scheme 3: Excess-flip — only penalize flips beyond # what measurement error would produce beta = 1.0 w3_correct = 0 w3_total = 0 for nf, data in flip_bins.items(): excess = max(0, nf - expected_meas_flips) w = np.exp(-beta * excess) w3_correct += w * data['correct'] w3_total += w * data['total'] fid_excess = w3_correct / w3_total if w3_total > 0 else 0 # Weighting scheme 4: Binomial likelihood ratio # P(k flips | qubit always in target) = Binom(N, p_meas) # P(k flips | qubit randomized) = Binom(N, 0.5) # Weight = P(target) / P(random) w4_correct = 0 w4_total = 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 = p_target / p_random if p_random > 0 else 0 # Clip to avoid overflow w = min(w, 1e10) else: w = 0 w4_correct += w * data['correct'] w4_total += w * data['total'] fid_likelihood = w4_correct / w4_total if w4_total > 0 else 0 # Flip statistics 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'} # ============================================================================= # MAIN # ============================================================================= def main(): print("=" * 70) print("PUSH ZENO PAST T1") 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'] < 40: log("Less than 40s remaining. Aborting.") return backend = service.backend("ibm_torino") log(f"Backend: {backend.name} ({backend.num_qubits}q)") # Hardware timing dt = backend.dt target = backend.target meas_props = target['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['sx'][(0,)].duration # Qubit 0 T1/T2 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") log(f"Inter-measurement interval: {meas_duration_s*1e6:.3f} us = {meas_duration_s/T1*100:.2f}% of T1") # Parameters # Include some overlap with previous experiment for continuity n_values = [8, 16, 32, 48, 64, 96, 128, 192, 256] theta = np.pi # X gate — cleanest test, dragging |0> all the way to |1> shots = 4096 print(f"\nExperiment plan:") print(f"{'N':>5} | {'Time(us)':>8} | {'T1 mult':>7} | {'Expected meas flips':>19} | {'Hard PS prob':>12}") print("-" * 65) for n in n_values: t_us = n * meas_duration_s * 1e6 t1_mult = n * meas_duration_s / T1 exp_flips = n * meas_error # Hard PS success: (1-p_meas)^N approximately hard_ps = (1 - meas_error) ** n print(f"{n:5d} | {t_us:8.1f} | {t1_mult:7.2f}x | {exp_flips:19.1f} | {hard_ps:12.2e}") all_experiments = [] # Standard baseline (one) 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 # Zeno 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}, )) # Delay-matched 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)}") # Transpile 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] # Submit 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") # Retrieve and analyze 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_past_t1', 'description': 'Push Zeno dragging past T1 — testing if projective measurements ' 'can maintain coherence indefinitely beyond qubit natural lifetime', '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_past_t1' / 'zeno_past_t1.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 TABLE # ========================================================================= print("\n" + "=" * 70) print("ZENO PAST T1") 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"Measurement error: {meas_error:.4f}") print(f"\n{'N':>5} | {'Time':>7} | {'×T1':>5} | {'Hard PS':>7} | {'exp(-k)':>7} | " f"{'Calib':>7} | {'Excess':>7} | {'LikeR':>7} | {'Delay':>7} | {'Best-Delay':>10} | {'Flips':>12}") print("-" * 110) 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_zeno = max(za['fidelity_calibrated'], za['fidelity_excess'], za['fidelity_likelihood']) gap = best_zeno - da['fidelity'] hard_str = f"{za['fidelity_hard_ps']:.4f}" if za['successful'] > 0 else "---" exp_str = f"{za['fidelity_exp_k']:.4f}" if za['fidelity_exp_k'] > 0.01 else f"{za['fidelity_exp_k']:.1e}" print(f"{n:5d} | {t_us:5.0f}us | {t1m:4.1f}x | {hard_str:>7} | {exp_str:>7} | " f"{za['fidelity_calibrated']:.4f} | {za['fidelity_excess']:.4f} | {za['fidelity_likelihood']:.4f} | " f"{da['fidelity']:.4f} | {gap:+10.4f} | {za['mean_flips']:.1f}±{za['std_flips']:.1f}") # Summary print(f"\n{'=' * 70}") print("INTERPRETATION") print(f"{'=' * 70}") for n in [128, 256]: 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'] t1m = results_data[zk]['params']['T1_multiple'] best = max(za['fidelity_calibrated'], za['fidelity_excess'], za['fidelity_likelihood']) print(f"\n N={n} ({t1m:.1f}× T1):") print(f" Delay-matched (qubit thermalized): {da['fidelity']:.4f}") print(f" Zeno (best weighting): {best:.4f}") print(f" Gap: {best - da['fidelity']:+.4f}") # Usage usage_after = check_usage(service) log(f"\nUsage after: {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)