""" Zeno Dragging State Tomography Full quantum state tomography of Zeno-dragged states at high measurement counts. Measures in X, Y, and Z Pauli bases without post-selection or trajectory weighting. Reconstructs single-qubit density matrices from raw statistics. Per-flip-count bin tomography provides assumption-free ground truth for calibrating all weighting schemes. Protocol: Zeno: drag |0> to |1> via N intermediate projective measurements, then measure in X, Y, or Z basis (no undo rotation). Control: Ry(pi)|0> + equivalent idle delay + basis measurement. For each N, six circuits are submitted (3 bases x 2 categories). Shots are binned by intermediate flip count after collection, and density matrices are reconstructed per bin independently. N values: 32, 128, 256, 512, 1024 Shots: 8192 per circuit Target state: |1> """ 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") RESULTS_DIR = DATA_DIR / "results" / "zeno_tomography" @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} # ============================================================================= # CIRCUIT BUILDERS # ============================================================================= def build_zeno_tomo(theta, n_meas, basis): """Zeno drag |0> to |1> with final measurement in the specified basis. Intermediate measurements are recorded for trajectory binning. No undo rotation is applied — the qubit remains in the dragged state. Args: theta: total drag angle (pi for |0> -> |1>) n_meas: number of intermediate projective measurements basis: 'Z', 'X', or 'Y' """ 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 basis == 'X': qc.h(0) elif basis == 'Y': qc.sdg(0) qc.h(0) qc.measure(0, n_meas) return qc def build_delay_tomo(theta, n_meas, meas_duration_dt, basis): """Delay-matched control with final measurement in the specified basis. Applies Ry(theta) then idles for the same wall-clock duration as the corresponding Zeno circuit, then measures in the specified basis. Args: theta: rotation angle n_meas: number of Zeno steps to match in duration meas_duration_dt: hardware measurement duration in dt units basis: 'Z', 'X', or 'Y' """ qc = QuantumCircuit(1, 1) qc.ry(theta, 0) qc.delay(n_meas * meas_duration_dt, 0, unit='dt') if basis == 'X': qc.h(0) elif basis == 'Y': qc.sdg(0) qc.h(0) qc.measure(0, 0) return qc # ============================================================================= # DENSITY MATRIX RECONSTRUCTION # ============================================================================= def reconstruct_density_matrix(exp_x, exp_y, exp_z): """Reconstruct single-qubit density matrix from Pauli expectation values. rho = (I + exp_x * sigma_X + exp_y * sigma_Y + exp_z * sigma_Z) / 2 """ rho = np.array([ [1 + exp_z, exp_x - 1j * exp_y], [exp_x + 1j * exp_y, 1 - exp_z], ], dtype=complex) / 2 return rho def state_fidelity_ket1(rho): """Fidelity of rho with |1>: F = <1|rho|1> = rho[1,1].""" return float(np.real(rho[1, 1])) def purity(rho): """Tr(rho^2).""" return float(np.real(np.trace(rho @ rho))) # ============================================================================= # ANALYSIS # ============================================================================= def bin_zeno_shots(bitstrings, n_meas): """Parse Zeno bitstrings into flip-count bins. Returns dict: {n_flips: {'zeros': int, 'total': int}} where 'zeros' counts final-bit == '0' outcomes. """ bins = {} total_zeros = 0 total_count = 0 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 bins: bins[n_flips] = {'zeros': 0, 'total': 0} bins[n_flips]['total'] += 1 if final == '0': bins[n_flips]['zeros'] += 1 total_count += 1 if final == '0': total_zeros += 1 return bins, total_zeros, total_count def analyze_zeno_tomo(bs_z, bs_x, bs_y, n_meas, p_meas): """Full tomographic analysis of Zeno-dragged state. Performs: 1. Raw tomography over all shots (no selection). 2. Per-flip-count-bin tomography. 3. Weighting scheme comparison using per-bin ground truth. """ z_bins, z_zeros, z_total = bin_zeno_shots(bs_z, n_meas) x_bins, x_zeros, x_total = bin_zeno_shots(bs_x, n_meas) y_bins, y_zeros, y_total = bin_zeno_shots(bs_y, n_meas) # --- Raw tomography (all shots, no selection) --- def exp_val(zeros, total): return 2 * zeros / total - 1 if total > 0 else 0.0 rho_raw = reconstruct_density_matrix( exp_val(x_zeros, x_total), exp_val(y_zeros, y_total), exp_val(z_zeros, z_total), ) raw_result = { 'exp_x': exp_val(x_zeros, x_total), 'exp_y': exp_val(y_zeros, y_total), 'exp_z': exp_val(z_zeros, z_total), 'fidelity': state_fidelity_ket1(rho_raw), 'purity': purity(rho_raw), 'shots_per_basis': z_total, 'rho_00': float(np.real(rho_raw[0, 0])), 'rho_01_re': float(np.real(rho_raw[0, 1])), 'rho_01_im': float(np.imag(rho_raw[0, 1])), 'rho_11': float(np.real(rho_raw[1, 1])), } # --- Per-bin tomography --- all_flips = sorted(set( list(z_bins.keys()) + list(x_bins.keys()) + list(y_bins.keys()) )) per_bin = {} for nf in all_flips: zd = z_bins.get(nf, {'zeros': 0, 'total': 0}) xd = x_bins.get(nf, {'zeros': 0, 'total': 0}) yd = y_bins.get(nf, {'zeros': 0, 'total': 0}) min_count = min(zd['total'], xd['total'], yd['total']) if min_count < 10: continue bexp_x = exp_val(xd['zeros'], xd['total']) bexp_y = exp_val(yd['zeros'], yd['total']) bexp_z = exp_val(zd['zeros'], zd['total']) brho = reconstruct_density_matrix(bexp_x, bexp_y, bexp_z) per_bin[str(nf)] = { 'n_flips': nf, 'shots_z': zd['total'], 'shots_x': xd['total'], 'shots_y': yd['total'], 'exp_x': float(bexp_x), 'exp_y': float(bexp_y), 'exp_z': float(bexp_z), 'fidelity': state_fidelity_ket1(brho), 'purity': purity(brho), } # --- Weighting scheme ground-truth comparison --- weighting = _weighting_ground_truth(per_bin, n_meas, p_meas) return { 'raw': raw_result, 'per_bin': per_bin, 'weighting_predictions': weighting, } def analyze_delay_tomo(bs_z, bs_x, bs_y): """Tomography for delay-matched control (no intermediate measurements).""" def exp_val(bitstrings): total = len(bitstrings) zeros = sum(1 for b in bitstrings if b[-1] == '0') return 2 * zeros / total - 1 if total > 0 else 0.0, total ex, nx = exp_val(bs_x) ey, ny = exp_val(bs_y) ez, nz = exp_val(bs_z) rho = reconstruct_density_matrix(ex, ey, ez) return { 'exp_x': float(ex), 'exp_y': float(ey), 'exp_z': float(ez), 'fidelity': state_fidelity_ket1(rho), 'purity': purity(rho), 'shots_per_basis': nz, 'rho_00': float(np.real(rho[0, 0])), 'rho_01_re': float(np.real(rho[0, 1])), 'rho_01_im': float(np.imag(rho[0, 1])), 'rho_11': float(np.real(rho[1, 1])), } def _weighting_ground_truth(per_bin, n_meas, p_meas): """Evaluate weighting schemes against per-bin tomographic fidelity. Uses the per-bin density-matrix fidelity as ground truth to compute the weighted-average fidelity each scheme would produce. """ if not per_bin: return {} bins = [] for bd in per_bin.values(): pop = (bd['shots_z'] + bd['shots_x'] + bd['shots_y']) / 3.0 bins.append({ 'k': bd['n_flips'], 'pop': pop, 'fid': bd['fidelity'], }) total_pop = sum(b['pop'] for b in bins) if total_pop == 0: return {} expected_flips = n_meas * p_meas def weighted_fidelity(weight_fn): num = sum(weight_fn(b['k']) * b['pop'] * b['fid'] for b in bins) den = sum(weight_fn(b['k']) * b['pop'] for b in bins) if den == 0: return None fid = num / den util = den / total_pop return { 'tomographic_fidelity': float(fid), 'utilization': float(util), 'effective_yield': float(fid * util), } schemes = {} # 1. No weighting r = weighted_fidelity(lambda k: 1.0) if r: schemes['unweighted'] = r # 2. Hard post-selection (k=0) r = weighted_fidelity(lambda k: 1.0 if k == 0 else 0.0) if r: schemes['hard_ps_k0'] = r # 3. Soft k<=2 r = weighted_fidelity(lambda k: 1.0 if k <= 2 else 0.0) if r: schemes['soft_k2'] = r # 4. exp(-k) r = weighted_fidelity(lambda k: np.exp(-k)) if r: schemes['exp_minus_k'] = r # 5. Calibrated exp(-alpha*k) alpha = np.log(2) / max(expected_flips, 1) r = weighted_fidelity(lambda k: np.exp(-alpha * k)) if r: schemes['calibrated_exp'] = r schemes['calibrated_exp']['alpha'] = float(alpha) # 6. Excess-flip: exp(-max(0, k - expected)) r = weighted_fidelity(lambda k: np.exp(-max(0, k - expected_flips))) if r: schemes['excess_flip'] = r schemes['excess_flip']['expected_flips'] = float(expected_flips) # 7. Likelihood ratio: Binom(k; N, p_meas) / Binom(k; N, 0.5) def lr_weight(k): if k > n_meas: return 0.0 p_t = comb(n_meas, k, exact=True) * (p_meas ** k) * ((1 - p_meas) ** (n_meas - k)) p_r = comb(n_meas, k, exact=True) * (0.5 ** n_meas) return min(p_t / p_r, 1e10) if p_r > 0 else 0.0 r = weighted_fidelity(lr_weight) if r: schemes['likelihood_ratio'] = r return schemes # ============================================================================= # MAIN # ============================================================================= def main(): print("=" * 70) print("ZENO STATE TOMOGRAPHY") 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("Insufficient quota (<30s). Aborting.") return backend = service.backend("ibm_torino") log(f"Backend: {backend.name} ({backend.num_qubits}q)") dt = backend.dt hw_target = backend.target meas_props = hw_target['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 ({meas_duration_dt} dt), " f"error={meas_error:.4f}") log(f"Qubit 0: T1={T1*1e6:.1f} us, T2={T2*1e6:.1f} us") theta = np.pi n_values = [32, 128, 256, 512, 1024] bases = ['Z', 'X', 'Y'] shots = 8192 # QPU budget estimate estimated_qpu = 0 for n in n_values: step_time = n * (meas_duration_s + 100e-9) # meas + ~2 Ry gates estimated_qpu += 3 * shots * step_time # 3 Zeno basis circuits estimated_qpu += 3 * shots * n * meas_duration_s # 3 delay circuits (rough) log(f"Estimated QPU: {estimated_qpu:.0f}s") if estimated_qpu > usage_before['remaining']: log(f"WARNING: estimated QPU ({estimated_qpu:.0f}s) exceeds " f"remaining quota ({usage_before['remaining']:.0f}s)") log("Proceeding — estimate is conservative. Abort manually if needed.") print(f"\n{'N':>5} | {'Time(us)':>8} | {'x T1':>6} | {'Est depth':>9}") print("-" * 38) for n in n_values: t_us = n * meas_duration_s * 1e6 t1m = n * meas_duration_s / T1 print(f"{n:5d} | {t_us:8.1f} | {t1m:5.1f}x | {n * 5:9d}") # Build circuits all_experiments = [] for n in n_values: total_time_us = n * meas_duration_s * 1e6 t1_mult = n * meas_duration_s / T1 for basis in bases: all_experiments.append(ExperimentConfig( name=f"zeno_N{n}_{basis}", circuit=build_zeno_tomo(theta, n, basis), category="zeno", params={'n_meas': n, 'theta': float(theta), 'basis': basis, 'total_time_us': total_time_us, 'T1_multiple': t1_mult}, )) all_experiments.append(ExperimentConfig( name=f"delay_N{n}_{basis}", circuit=build_delay_tomo(theta, n, meas_duration_dt, basis), category="delay", params={'n_meas': n, 'theta': float(theta), 'basis': basis, 'total_time_us': total_time_us, 'T1_multiple': t1_mult}, )) log(f"Circuits: {len(all_experiments)} ({len(all_experiments)//2} Zeno " f"+ {len(all_experiments)//2} delay)") # Transpile log("Transpiling...") pm = generate_preset_pass_manager(backend=backend, optimization_level=1) transpiled = [] valid_experiments = [] for exp in all_experiments: try: tc = pm.run(exp.circuit) transpiled.append(tc) valid_experiments.append(exp) except Exception as e: log(f"Transpile error ({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"Complete. Wall: {wall_time:.1f}s, QPU: {job.usage() or 0}s") # Parse bitstrings result = job.result() metrics = job.metrics() bitstring_map = {} 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()) bitstring_map[exp.name] = bitstrings # Tomographic reconstruction results_data = {} for n in n_values: zeno_z = bitstring_map.get(f"zeno_N{n}_Z", []) zeno_x = bitstring_map.get(f"zeno_N{n}_X", []) zeno_y = bitstring_map.get(f"zeno_N{n}_Y", []) if zeno_z and zeno_x and zeno_y: results_data[f"zeno_N{n}"] = analyze_zeno_tomo( zeno_z, zeno_x, zeno_y, n, meas_error) delay_z = bitstring_map.get(f"delay_N{n}_Z", []) delay_x = bitstring_map.get(f"delay_N{n}_X", []) delay_y = bitstring_map.get(f"delay_N{n}_Y", []) if delay_z and delay_x and delay_y: results_data[f"delay_N{n}"] = { 'raw': analyze_delay_tomo(delay_z, delay_x, delay_y) } # Save output = { 'experiment': 'zeno_state_tomography', 'description': ( 'Full single-qubit state tomography of Zeno-dragged states at ' 'N = 32 through 1024 intermediate measurements. Density matrices ' 'reconstructed from X, Y, Z basis measurements without post-selection ' 'or trajectory weighting. Per-flip-count bin tomography provides ' 'ground-truth fidelity for calibrating weighting schemes. ' 'Delay-matched controls at every N value.' ), 'protocol': { 'zeno': 'Drag |0> to |1> via N projective measurements, ' 'then measure in Pauli basis. No undo rotation.', 'delay': 'Ry(pi)|0> + idle delay matching Zeno wall-clock, ' 'then measure in Pauli basis.', 'target_state': '|1>', 'bases': ['X', 'Y', 'Z'], 'shots_per_circuit': shots, }, 'timestamp': start_time.isoformat(), 'backend': backend.name, 'n_values': n_values, 'total_circuits': len(valid_experiments), 'job_id': job.job_id(), 'usage_seconds': job.usage() or 0, 'wall_time_seconds': wall_time, 'metrics': metrics, 'hardware': { 'qubit': 0, 'dt_ns': dt * 1e9, 'measurement_duration_us': meas_duration_s * 1e6, 'measurement_duration_dt': meas_duration_dt, 'measurement_error': meas_error, 'T1_us': T1 * 1e6, 'T2_us': T2 * 1e6, }, 'results': results_data, 'raw_bitstrings': {name: bs for name, bs in bitstring_map.items()}, } RESULTS_DIR.mkdir(parents=True, exist_ok=True) outfile = RESULTS_DIR / 'zeno_tomography.json' with open(outfile, 'w') as f: json.dump(output, f, indent=2, default=str) log(f"Saved: {outfile}") # ========================================================================= # RESULTS # ========================================================================= print("\n" + "=" * 70) print("RAW TOMOGRAPHIC FIDELITY WITH |1> (NO SELECTION)") print("=" * 70) print(f"\n{'N':>5} | {'x T1':>5} | {'Zeno F':>7} | {'Zeno P':>7} | " f"{'Delay F':>7} | {'Delay P':>7} | {'Z - D':>7}") print("-" * 56) for n in n_values: zk = f"zeno_N{n}" dk = f"delay_N{n}" if zk not in results_data or dk not in results_data: continue zr = results_data[zk]['raw'] dr = results_data[dk]['raw'] t1m = n * meas_duration_s / T1 gap = zr['fidelity'] - dr['fidelity'] print(f"{n:5d} | {t1m:4.1f}x | {zr['fidelity']:7.4f} | " f"{zr['purity']:7.4f} | {dr['fidelity']:7.4f} | " f"{dr['purity']:7.4f} | {gap:+7.4f}") # Bloch vector summary print(f"\n{'N':>5} | {'Cat':>5} | {'':>7} | {'':>7} | {'':>7} | " f"{'|r|':>6}") print("-" * 48) for n in n_values: for cat in ['zeno', 'delay']: key = f"{cat}_N{n}" if key not in results_data: continue r = results_data[key]['raw'] bloch_len = np.sqrt(r['exp_x']**2 + r['exp_y']**2 + r['exp_z']**2) print(f"{n:5d} | {cat:>5} | {r['exp_x']:+7.4f} | " f"{r['exp_y']:+7.4f} | {r['exp_z']:+7.4f} | {bloch_len:6.4f}") # Per-bin tables for selected N for n in [32, 256, 1024]: zk = f"zeno_N{n}" if zk not in results_data: continue zeno = results_data[zk] if not zeno['per_bin']: continue print(f"\n{'=' * 70}") print(f"PER-BIN TOMOGRAPHY: N={n}") print(f"{'=' * 70}") print(f"\n{'k':>5} | {'shots':>6} | {'':>7} | {'':>7} | " f"{'':>7} | {'F(|1>)':>7} | {'Purity':>7}") print("-" * 58) for nf_str in sorted(zeno['per_bin'].keys(), key=lambda x: int(x)): bd = zeno['per_bin'][nf_str] print(f"{bd['n_flips']:5d} | {bd['shots_z']:6d} | " f"{bd['exp_x']:+7.4f} | {bd['exp_y']:+7.4f} | " f"{bd['exp_z']:+7.4f} | {bd['fidelity']:7.4f} | " f"{bd['purity']:7.4f}") # Weighting scheme ground truth print(f"\n{'=' * 70}") print("WEIGHTING SCHEME GROUND-TRUTH CALIBRATION") print("=" * 70) scheme_names = [ 'unweighted', 'hard_ps_k0', 'soft_k2', 'exp_minus_k', 'calibrated_exp', 'excess_flip', 'likelihood_ratio', ] print(f"\n{'N':>5} | {'Scheme':>16} | {'Tomo F':>7} | " f"{'Util':>7} | {'Yield':>7}") print("-" * 52) for n in n_values: zk = f"zeno_N{n}" if zk not in results_data: continue wp = results_data[zk].get('weighting_predictions', {}) for sn in scheme_names: if sn in wp: s = wp[sn] print(f"{n:5d} | {sn:>16} | {s['tomographic_fidelity']:7.4f} | " f"{s['utilization']:7.4f} | {s['effective_yield']:7.4f}") print() usage_after = check_usage(service) log(f"Usage: {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)