| """ |
| Measurement Duration Experiment |
| |
| "Does the relatively long duration of measurement compared to unitary |
| operations not present an obstacle for practical adoption?" |
| |
| Protocol (matching zeno_gates_corrected): |
| - Standard: Ry(theta) Ry(-theta) measure — ideal outcome |0> |
| - Zeno: drag 0->theta via N measurements, then Ry(-theta) measure — ideal |0> |
| - Delay-matched: Ry(theta) + delay(N*t_meas) + Ry(-theta) measure — ideal |0> |
| |
| Fidelity = P(0) for all circuits. This is a fair comparison because all |
| circuits target the same output state in the same measurement basis. |
| |
| The delay-matched circuit isolates the decoherence cost: it experiences the same |
| wall-clock decoherence as Zeno but without the measurement-based error |
| suppression. If Zeno > delay-matched, measurements actively help. |
| """ |
|
|
| import json |
| import sys |
| from datetime import datetime, timezone |
| from dataclasses import dataclass |
| from pathlib import Path |
| import numpy as np |
|
|
| 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} |
|
|
|
|
| |
| |
| |
|
|
| 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 from 0 to 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 |
|
|
|
|
| def build_delay_only(n_meas, meas_duration_dt): |
| """Identity + delay — pure decoherence baseline. Ideal = |0>.""" |
| qc = QuantumCircuit(1, 1) |
| qc.delay(n_meas * meas_duration_dt, 0, unit='dt') |
| qc.measure(0, 0) |
| return qc |
|
|
|
|
| def build_depth_matched(theta, n_layers): |
| """Same Ry gates as Zeno but no measurements. Isolates circuit structure.""" |
| qc = QuantumCircuit(1, 1) |
| for k in range(1, n_layers + 1): |
| theta_k = k * theta / n_layers |
| qc.ry(-theta_k, 0) |
| qc.barrier() |
| qc.ry(theta_k, 0) |
| qc.ry(-theta, 0) |
| qc.measure(0, 0) |
| return qc |
|
|
|
|
| |
| |
| |
|
|
| def analyze_standard(bitstrings): |
| """P(0) = fidelity.""" |
| total = len(bitstrings) |
| zeros = sum(1 for b in bitstrings if b[-1] == '0') |
| return {'total': total, 'fidelity': zeros / total, 'type': 'standard'} |
|
|
|
|
| def analyze_zeno(bitstrings, n_meas): |
| """Zeno analysis: post-selection on intermediate measurements, plus trajectory weighting.""" |
| total = len(bitstrings) |
| successful = 0 |
| correct = 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 all(b == '0' for b in intermediate): |
| successful += 1 |
| if final == '0': |
| correct += 1 |
|
|
| success_rate = successful / total if total > 0 else 0 |
| fidelity_hard = correct / successful if successful > 0 else 0 |
|
|
| |
| weighted_correct = 0 |
| total_weight = 0 |
| for nf, data in flip_bins.items(): |
| w = np.exp(-nf) |
| weighted_correct += w * data['correct'] |
| total_weight += w * data['total'] |
| fidelity_weighted = weighted_correct / total_weight if total_weight > 0 else 0 |
|
|
| return { |
| 'total': total, |
| 'successful': successful, |
| 'success_rate': success_rate, |
| 'fidelity_hard_ps': fidelity_hard, |
| 'fidelity_weighted': fidelity_weighted, |
| 'flip_distribution': {str(k): v for k, v in sorted(flip_bins.items())}, |
| 'type': 'zeno', |
| } |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| print("=" * 70) |
| print("MEASUREMENT DURATION EXPERIMENT") |
| print("Does measurement duration obstruct practical adoption?") |
| 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 = 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 |
|
|
| log(f"Measurement: {meas_duration_s*1e6:.3f} us ({meas_duration_dt} dt), error={meas_error:.4f}") |
| log(f"SX gate: {sx_duration_s*1e9:.1f} ns") |
| log(f"Measurement/gate ratio: {meas_duration_s/sx_duration_s:.0f}x") |
|
|
| |
| qubit_t1 = {} |
| qubit_t2 = {} |
| for qi in range(min(backend.num_qubits, 133)): |
| try: |
| props = backend.qubit_properties(qi) |
| qubit_t1[qi] = props.t1 |
| qubit_t2[qi] = props.t2 |
| except Exception: |
| pass |
|
|
| |
| T1 = qubit_t1.get(0, 200e-6) |
| T2 = qubit_t2.get(0, 180e-6) |
| log(f"Qubit 0: T1={T1*1e6:.1f} us, T2={T2*1e6:.1f} us") |
|
|
| |
| thetas = { |
| 'I': 0, |
| 'Ry_pi8': np.pi / 8, |
| 'Ry_pi4': np.pi / 4, |
| 'Ry_pi2': np.pi / 2, |
| 'Ry_3pi4': 3 * np.pi / 4, |
| 'X': np.pi, |
| } |
| n_values = [2, 4, 8, 12, 16, 24, 32] |
| shots = 4096 |
|
|
| all_experiments = [] |
|
|
| for gate_name, theta in thetas.items(): |
| |
| all_experiments.append(ExperimentConfig( |
| name=f"{gate_name}_standard", |
| circuit=build_standard(theta), |
| category="standard", |
| params={'gate': gate_name, 'theta': theta, 'n_meas': 0, |
| 'total_time_us': sx_duration_s * 1e6}, |
| )) |
|
|
| |
| all_experiments.append(ExperimentConfig( |
| name=f"{gate_name}_depth_matched", |
| circuit=build_depth_matched(theta, 8), |
| category="depth_matched", |
| params={'gate': gate_name, 'theta': theta, 'n_meas': 0}, |
| )) |
|
|
| |
| for n in n_values: |
| total_time_us = n * meas_duration_s * 1e6 |
| all_experiments.append(ExperimentConfig( |
| name=f"{gate_name}_zeno_N{n}", |
| circuit=build_zeno(theta, n), |
| category="zeno", |
| params={'gate': gate_name, 'theta': theta, 'n_meas': n, |
| 'total_time_us': total_time_us, |
| 'T1_fraction': n * meas_duration_s / T1, |
| 'T2_fraction': n * meas_duration_s / T2}, |
| )) |
|
|
| |
| all_experiments.append(ExperimentConfig( |
| name=f"{gate_name}_delay_N{n}", |
| circuit=build_delay_matched(theta, n, meas_duration_dt), |
| category="delay_matched", |
| params={'gate': gate_name, 'theta': theta, 'n_meas': n, |
| 'total_time_us': total_time_us, |
| 'T1_fraction': n * meas_duration_s / T1, |
| 'T2_fraction': n * meas_duration_s / T2}, |
| )) |
|
|
| |
| for n in [8, 16, 32]: |
| total_time_us = n * meas_duration_s * 1e6 |
| all_experiments.append(ExperimentConfig( |
| name=f"delay_only_N{n}", |
| circuit=build_delay_only(n, meas_duration_dt), |
| category="delay_only", |
| params={'gate': 'I', 'theta': 0, 'n_meas': n, |
| 'total_time_us': total_time_us, |
| 'T1_fraction': n * meas_duration_s / T1}, |
| )) |
|
|
| 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)}") |
|
|
| |
| 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']) |
| 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()}, |
| 'transpiled_depth': depths[i], |
| 'analysis': analysis, |
| 'raw_bitstrings': bitstrings[:200], |
| } |
|
|
| if exp.category == 'zeno': |
| a = analysis |
| log(f"{exp.name}: hard={a['fidelity_hard_ps']:.3f} wt={a['fidelity_weighted']:.3f} " |
| f"sr={a['success_rate']:.3f}", 1) |
| else: |
| log(f"{exp.name}: fidelity={analysis['fidelity']:.3f}", 1) |
|
|
| |
| output = { |
| 'experiment': 'measurement_duration_analysis', |
| 'description': "Tests whether measurement duration overhead negates Zeno fidelity advantage", |
| 'question': "Does the relatively long duration of measurement compared to " |
| "unitary operations not present an obstacle for practical adoption?", |
| '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, |
| 'measurement_to_gate_ratio': meas_duration_s / sx_duration_s, |
| 'qubit_0_T1_us': T1 * 1e6, |
| 'qubit_0_T2_us': T2 * 1e6, |
| }, |
| 'results': results_data, |
| } |
|
|
| outfile = DATA_DIR / 'measurement_duration_analysis.json' |
| with open(outfile, 'w') as f: |
| json.dump(output, f, indent=2, default=str) |
| log(f"Saved: {outfile}") |
|
|
| |
| |
| |
| print("\n" + "=" * 70) |
| print("ANSWERING LEWALLE'S QUESTION") |
| print("=" * 70) |
|
|
| |
| print("\n--- Reproducing original zeno_gates_corrected (N=8) ---") |
| print(f"\n{'Gate':>8} | {'Standard':>8} | {'Zeno(hard)':>10} | {'Zeno(wt)':>8} | {'DepthM':>6} | {'Zeno-Std':>8}") |
| print("-" * 60) |
|
|
| for gate_name in thetas: |
| sk = f"{gate_name}_standard" |
| zk = f"{gate_name}_zeno_N8" |
| dk = f"{gate_name}_depth_matched" |
| if all(k in results_data for k in [sk, zk, dk]): |
| sf = results_data[sk]['analysis']['fidelity'] |
| zf_h = results_data[zk]['analysis']['fidelity_hard_ps'] |
| zf_w = results_data[zk]['analysis']['fidelity_weighted'] |
| df = results_data[dk]['analysis']['fidelity'] |
| print(f"{gate_name:>8} | {sf:8.4f} | {zf_h:10.4f} | {zf_w:8.4f} | {df:6.4f} | {zf_h-sf:+8.4f}") |
|
|
| |
| print("\n--- KEY: Zeno vs delay-matched (same wall-clock time) ---") |
| for gate_name in ['Ry_pi2', 'X']: |
| theta = thetas[gate_name] |
| print(f"\n {gate_name}:") |
| sk = f"{gate_name}_standard" |
| sf = results_data[sk]['analysis']['fidelity'] |
| print(f" Standard (fast): {sf:.4f}") |
|
|
| print(f"\n {'N':>3} | {'Zeno(hard)':>10} | {'Zeno(wt)':>8} | {'Delay':>6} | {'Z-D':>6} | {'Time(us)':>8} | {'T1%':>5}") |
| print(f" " + "-" * 60) |
|
|
| for n in n_values: |
| zk = f"{gate_name}_zeno_N{n}" |
| dlk = f"{gate_name}_delay_N{n}" |
| if zk in results_data and dlk in results_data: |
| za = results_data[zk]['analysis'] |
| da = results_data[dlk]['analysis'] |
| t = results_data[zk]['params']['total_time_us'] |
| t1f = results_data[zk]['params']['T1_fraction'] |
| zd = za['fidelity_hard_ps'] - da['fidelity'] |
| print(f" {n:3d} | {za['fidelity_hard_ps']:10.4f} | {za['fidelity_weighted']:8.4f} | " |
| f"{da['fidelity']:6.4f} | {zd:+6.4f} | {t:8.2f} | {t1f*100:5.1f}%") |
|
|
| |
| 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) |
|
|