"""Recover the published pump cadence from one frozen set of photon time tags.""" import argparse from hashlib import file_digest from io import BytesIO import json from pathlib import Path import re from zipfile import ZipFile import numpy as np from scipy.io import loadmat ARCHIVE_SHA = "ae85e5ec424439638e93366cc57004e527a9cd333ae6b3b6bab18489222dd2f4" RUN = "CH_Bell_Data/05082013_15 t753 a252ap38/" NAME = re.compile(r"QRNG_([12][12])_(\d+)\.mat$") CALIBRATION_COUNT = 30 EXPECTED_IDS = range(7201, 7800, 2) TICK_US = 2 / 12800 GAP_TOLERANCE = 0.005 GATE_WIDTH = 18000 HISTOGRAM_BINS = 320 STATIONS = (1, 2) def sha256(path): with open(path, "rb") as stream: return file_digest(stream, "sha256").hexdigest() def input_blocks(archive): blocks = [] for entry in archive.infolist(): if not entry.filename.startswith(RUN): continue match = NAME.fullmatch(entry.filename[len(RUN):]) if match: settings, identifier = match.groups() if entry.file_size > 4_000_000: raise ValueError("A block exceeds the expected size.") blocks.append((int(identifier), settings, entry)) blocks.sort(key=lambda block: block[0]) if [identifier for identifier, _, _ in blocks] != list(EXPECTED_IDS): raise ValueError("The run has missing or duplicated block IDs.") return blocks def read_block(archive, block): _, settings, item = block channel_name, time_name = "channel" + settings, "timetags" + settings data = loadmat(BytesIO(archive.read(item)), variable_names=[channel_name, time_name]) channels = data[channel_name].ravel() times = data[time_name].ravel() if (channels.shape != times.shape or not np.isin(channels, [1, 2, 15]).all() or not np.isfinite(times).all() or (times < 0).any() or (times >= 2**53).any() or not np.equal(times, np.floor(times)).all()): raise ValueError(f"Unexpected time tags in {item.filename}.") times = times.astype(np.int64) spans = np.diff(times) if (spans <= 0).all(): times, channels = times[::-1], channels[::-1] elif (spans < 0).any(): raise ValueError(f"The records in {item.filename} are not ordered.") marks = times[channels == 15] if len(marks) < 2 or (np.diff(marks) <= 0).any(): raise ValueError(f"Too few or repeated markers in {item.filename}.") return marks, {station: times[channels == station] for station in STATIONS} def clock_window(phase, center, period): return np.abs((phase - center + period / 2) % period - period / 2) < GATE_WIDTH / 2 def folded_tags(marks, observed, period): widths = np.diff(marks) valid = np.abs(widths - period) <= GAP_TOLERANCE * period record = {"clockIntervals": len(widths), "eligibleIntervals": int(valid.sum()), "stations": {}} for station, clicks in observed.items(): left = np.searchsorted(marks, clicks, side="right") - 1 inside = (left >= 0) & (left < len(widths)) indices = left[inside] accepted = valid[indices] indices = indices[accepted] normalized = (clicks[inside][accepted] - marks[indices]) * period / widths[indices] phase = (normalized + period / 4) % period - period / 4 record["stations"][station] = {"allClicks": len(clicks), "phases": phase} return record, widths[valid] def distribution(phases, period): return np.histogram(phases, bins=HISTOGRAM_BINS, range=(-period / 4, 3 * period / 4)) def calibrate(archive, blocks, runner_sha): samples = [read_block(archive, block) for block in blocks[:CALIBRATION_COUNT]] intervals = np.concatenate([np.diff(marks) for marks, _ in samples]) period = float(np.median(intervals)) folded = [folded_tags(marks, clicks, period)[0] for marks, clicks in samples] gates = {} for station in STATIONS: phases = np.concatenate([sample["stations"][station]["phases"] for sample in folded]) counts, edges = distribution(phases, period) half = HISTOGRAM_BINS // 2 peaks = (int(counts[:half].argmax()), half + int(counts[half:].argmax())) gates[str(station)] = [float((edges[index] + edges[index + 1]) / 2) for index in peaks] return {"archiveSha256": ARCHIVE_SHA, "runnerSha256": runner_sha, "run": RUN, "calibratedBlocks": [block[0] for block in blocks[:CALIBRATION_COUNT]], "medianPeriodBins": period, "gateCentersBins": gates} def analyze(archive, blocks, calibration, runner_sha): if (calibration["archiveSha256"] != ARCHIVE_SHA or calibration["runnerSha256"] != runner_sha or calibration["run"] != RUN or calibration["calibratedBlocks"] != [block[0] for block in blocks[:CALIBRATION_COUNT]]): raise ValueError("The frozen calibration does not match the runner and the archive.") period = calibration["medianPeriodBins"] collected = [] for block in blocks[CALIBRATION_COUNT:]: marks, observed = read_block(archive, block) collected.append(folded_tags(marks, observed, period)) intervals = np.concatenate([widths for _, widths in collected]) total_intervals = sum(item["clockIntervals"] for item, _ in collected) stations = {} for station in STATIONS: phases = np.concatenate([item["stations"][station]["phases"] for item, _ in collected]) histogram, edges = distribution(phases, period) centers = calibration["gateCentersBins"][str(station)] pulse_gates = [clock_window(phases, center, period) for center in centers] controls = [clock_window(phases, center + period / 4, period) for center in centers] if any(np.any(gate & control) for gate in pulse_gates for control in controls): raise ValueError("The calibration generated overlapping pulse and control gates.") by_block = [item["stations"][station]["phases"] for item, _ in collected] station_result = {"recordedClicks": sum(item["stations"][station]["allClicks"] for item, _ in collected), "clicksInCompleteIntervals": len(phases), "pulseClicks": [int(gate.sum()) for gate in pulse_gates], "controlClicks": [int(gate.sum()) for gate in controls], "histogram": histogram.tolist(), "gateCentersUs": [center * TICK_US for center in centers]} per_block = [ [clock_window(block, center, period).sum() for block in by_block] for center in centers ] station_result["pulseClicksPerBlockQuartiles"] = [np.quantile(counts, [0.25, 0.5, 0.75]).tolist() for counts in per_block] station_result["clockHarmonics"] = [float(abs(np.exp(2j * np.pi * order * phases / period).mean())) for order in (1, 2)] stations[str(station)] = station_result period_quartiles = (np.quantile(intervals, [0.25, 0.5, 0.75]) * TICK_US).tolist() median_period = period_quartiles[1] return {"archiveSha256": ARCHIVE_SHA, "runnerSha256": runner_sha, "run": RUN, "calibrationBlocks": CALIBRATION_COUNT, "holdoutBlocks": len(collected), "nominalTimebinUs": TICK_US, "observedClockIntervals": total_intervals, "eligibleClockIntervals": len(intervals), "observedMarkerQuartilesUs": period_quartiles, "observedMedianMarkerUs": median_period, "observedMedianMarkerHz": 1_000_000 / median_period, "inferredPumpHz": 2_000_000 / median_period, "pulseGateWidthUs": GATE_WIDTH * TICK_US, "histogramRangeUs": [float(edges[0] * TICK_US), float(edges[-1] * TICK_US)], "stations": stations} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("calibration", type=Path) parser.add_argument("--holdout-receipt", type=Path) options = parser.parse_args() if sha256(options.archive) != ARCHIVE_SHA: raise SystemExit("The public archive hash differs from the approved bytes.") runner_sha = sha256(__file__) with ZipFile(options.archive) as archive: blocks = input_blocks(archive) if options.holdout_receipt: with options.calibration.open(encoding="utf-8") as file: frozen = json.load(file) result = analyze(archive, blocks, frozen, runner_sha) output = options.holdout_receipt else: result = calibrate(archive, blocks, runner_sha) output = options.calibration with output.open("x", encoding="utf-8") as file: json.dump(result, file, indent=2) file.write("\n") print(output) if __name__ == "__main__": main()