"""Verify every count with rational boundaries and scalar raw-event classification.""" from bisect import bisect_right from collections import defaultdict from fractions import Fraction from hashlib import file_digest from io import BytesIO import json import math from pathlib import Path, PurePosixPath import re from zipfile import ZipFile import numpy as np from scipy.io import loadmat folder = re.compile(r"05082013_(\d+) t753 a252ap38") filename = re.compile(r"QRNG_([12][12])_(\d+)[.]mat") cutoff = 1000 radius = 18000 def read_input(root): reference = json.loads((root / "full-census.json").read_text(encoding="utf-8")) calibration = json.loads((root / "calibration-quartiles.json").read_text(encoding="utf-8")) with (root / "CH_Bell_Data.zip").open("rb") as stream: assert file_digest(stream, "sha256").hexdigest() == calibration["archiveSha256"] period = int(calibration["medianPeriodBins"]) windows = {station: [Fraction(value) for value in values] for station, values in calibration["gateCentersBins"].items()} return reference, period, windows def absolute_windows(start, end, period, centers): segments = [] span = end - start for center in centers: for shift in (-period, 0, period): low = start + ((center + shift - radius) * span / period) high = start + ((center + shift + radius) * span / period) if low < end and high > start: segments.append((max(start, math.floor(low) + 1), min(end, math.ceil(high)))) return segments def count_clicks(archive, entry, setting, period, windows): channel_label = "channel" + setting time_label = "timetags" + setting data = loadmat(BytesIO(archive.read(entry)), variable_names=[channel_label, time_label]) channel = data[channel_label].reshape(-1) tags = data[time_label].reshape(-1) assert (tags.astype(np.int64) == tags).all() if tags[0] > tags[-1]: tags, channel = tags[::-1], channel[::-1] assert (np.diff(tags) >= 0).all() tags = tags.astype(np.int64) clock = tags[channel == 15].tolist() valid = [abs((b-a) * 200 - period * 200) <= period for a, b in zip(clock, clock[1:])] off = {"1": [], "2": []} edges = {} for station, centers in windows.items(): for hit in tags[channel == int(station)].tolist(): left = bisect_right(clock, hit) - 1 if left < 0 or left >= len(valid) or not valid[left]: continue key = (station, left) if key not in edges: start, end = clock[left], clock[left+1] edges[key] = absolute_windows(start, end, period, centers) if not any(low <= hit < high for low, high in edges[key]): off[station].append(hit) return clock, off def microstructure(clock, off): detail = {} for station, times in off.items(): milliseconds = (np.array(times, dtype=np.int64) - clock[0]) / 6400000 wide = np.floor(milliseconds / 20).astype(int) periods = np.diff(np.array(times, dtype=np.int64)) / 6400 core_bin = int(np.bincount(wide).argmax()) if len(wide) else 0 core = (milliseconds >= core_bin * 20) & (milliseconds < (core_bin + 1) * 20) usable = np.flatnonzero(core) core_gaps = np.diff(np.array(times)[usable]) / 6400 detail[station] = { "clicks": len(times), "shortGapsUs": {x: int((periods <= x).sum()) for x in (0.0, 0.1, 0.5, 1.0, 2.0)}, "max20msStart": core_bin * 20, "max20msClicks": int(core.sum()), "max20msGapQuantilesUs": np.quantile(core_gaps, [0, .01, .1, .5, .9, .99, 1]).tolist() if len(core_gaps) else [], } tags_a = np.asarray(off["1"], dtype=np.int64) tags_b = np.asarray(off["2"], dtype=np.int64) half_widths = {"oneTagBin": 1, "oneNs": 6, "oneHundredNs": 640, "oneUs": 6400} counts = {} for lag in (-50, -20, -10, -5, 0, 5, 10, 20, 50): shifted = tags_a + lag * 6400 counts[lag] = {name: int(np.sum(np.searchsorted(tags_b, shifted + width, side="right") - np.searchsorted(tags_b, shifted - width))) for name, width in half_widths.items()} return {"detectors": detail, "pairCountsByAShiftUs": counts} def main(): import sys root = Path(sys.argv[1]) reference, period, windows = read_input(root) expected = {(int(run), row["id"]): [row["channels"][st]["outside"][1] for st in ("1", "2")] for run, rows in reference["runs"].items() for row in rows} totals = defaultdict(int) flagged = {} visited = set() with ZipFile(root / "CH_Bell_Data.zip") as archive: for entry in archive.infolist(): parts = PurePosixPath(entry.filename).parts if len(parts) != 3 or parts[0] != "CH_Bell_Data": continue run = folder.fullmatch(parts[1]) name = filename.fullmatch(parts[2]) if not run or not name: continue setting, block = name.groups() identifier = (int(run.group(1)), int(block)) assert identifier in expected and identifier not in visited clock, off = count_clicks(archive, entry, setting, period, windows) observed = list(map(len, off.values())) if observed != expected[identifier]: raise ValueError(f"Mismatch in {identifier}: {observed} versus {expected[identifier]}") visited.add(identifier) for station, tags in off.items(): totals[station] += len(tags) if max(observed) >= cutoff: flagged[f"{identifier[0]}:{identifier[1]}"] = microstructure(clock, off) assert visited == expected.keys() and len(visited) == 4450 report = {"allCountsMatch": True, "records": len(visited), "channelOffPulseTotals": dict(totals), "flagged": flagged} with (root / "independent-full-census.json").open("x", encoding="utf-8") as output: json.dump(report, output, indent=2) output.write("\n") print(json.dumps({"allCountsMatch": True, "records": len(visited), "channelOffPulseTotals": dict(totals), "flagged": list(flagged)})) if __name__ == "__main__": main()