"""Reconstruct Table I from the acquisition counters embedded in the archival files.""" import argparse from collections import defaultdict from hashlib import file_digest from io import BytesIO import json from pathlib import Path, PurePosixPath import re from zipfile import ZipFile import numpy as np from scipy.io import loadmat ARCHIVE = "ae85e5ec424439638e93366cc57004e527a9cd333ae6b3b6bab18489222dd2f4" SELECTED = re.compile(r"CH_Bell_Data/05082013_(\d+) t753 a252ap38/QRNG_([12]{2})_(\d+)\.mat$") KEYS = ["11", "12", "21", "22"] PUBLIC_TABLE = np.array([[27153020, 46068, 46039, 29173], [28352350, 48076, 146205, 34145], [27827318, 150840, 47447, 34473], [27926994, 150505, 144070, 1862]]) def select(archive): runs = defaultdict(list) for name in archive.namelist(): match = SELECTED.fullmatch(PurePosixPath(name).as_posix()) if match: run, setting, record = match.groups() runs[int(run)].append((int(record), setting, name)) if len(runs) != 20 or sum(map(len, runs.values())) != 4450: raise ValueError("Expected the 20 published archive runs and all 4,450 blocks.") return runs def score_table(matrix): trials, a, b, coincidences = matrix.T.astype(float) rates = coincidences / trials single_a = a[:2].sum() / trials[:2].sum() single_b = b[::2].sum() / trials[::2].sum() coincidence_sum = rates[:3].sum() - rates[3] singles = single_a + single_b return dict(score=float(coincidence_sum - singles), ratio=float(coincidence_sum / singles)) def records_of(archive, runs): block_checks = 0 unexpected = [] marker_slots = np.zeros(4, dtype=np.int64) registered = np.zeros((4, 3), dtype=np.int64) for _, blocks in sorted(runs.items()): previous = np.zeros((4, 3), dtype=np.int64) for record, setting, filename in sorted(blocks): channel_field = "channel" + setting data = loadmat(BytesIO(archive.read(filename)), variable_names=["counts", channel_field]) channels = data[channel_field].ravel() raw_a, raw_b, raw_markers = (int(np.count_nonzero(channels == channel)) for channel in (1, 2, 15)) marker_slots[KEYS.index(setting)] += 2 * raw_markers current = data["counts"].astype(np.int64) if current.shape != previous.shape: raise ValueError(f"Invalid cumulative acquisition table at {filename}.") increases = current - previous row = KEYS.index(setting) b, both, a = increases[row] if ((increases < 0).any() or np.count_nonzero(np.delete(increases, row, axis=0)) or (both > min(a, b)) or a > raw_a or b > raw_b): unexpected.append({"block": record, "setting": setting, "increments": increases.tolist(), "rawA": raw_a, "rawB": raw_b}) previous = current block_checks += 1 registered += previous return block_checks, unexpected, np.column_stack((marker_slots, registered[:, [2, 0, 1]])) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("output", type=Path) options = parser.parse_args() with options.archive.open("rb") as stream: if file_digest(stream, "sha256").hexdigest() != ARCHIVE: raise SystemExit("Archive bytes differ from the checked source.") with ZipFile(options.archive) as archive: blocks, unexpected, result = records_of(archive, select(archive)) details = {"sourceSha256": ARCHIVE, "blocks": blocks, "inconsistentIncrements": len(unexpected), "examplesOfInconsistency": unexpected[:10], "columns": ["clockTrials", "aSingles", "bSingles", "coincidences"], "settings": KEYS, "archiveResult": result.tolist(), "publishedTable": PUBLIC_TABLE.tolist(), "archiveMinusPaper": (result - PUBLIC_TABLE).tolist(), "sameCounts": bool(np.array_equal(result, PUBLIC_TABLE)), "archiveScore": score_table(result), "publishedScore": score_table(PUBLIC_TABLE)} with options.output.open("x", encoding="utf-8") as stream: json.dump(details, stream, indent=2) stream.write("\n") print(options.output) if __name__ == "__main__": main()