"""Measure sub-100 ns timestamp spacing against all unaffected detector blocks.""" import importlib.util import json from pathlib import Path from zipfile import ZipFile import numpy as np def load(name, path): spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def side_profile(tags): gap = np.diff(tags) return {"sampleSize": len(gap), "atMost100Ns": int(np.count_nonzero(gap <= 640)), "from5To25Ns": int(np.count_nonzero((gap >= 32) & (gap <= 160))), "minimumNs": float(gap.min() / 6.4) if len(gap) else None} def main(): import sys root = Path(sys.argv[1]) timing = load("timing", Path(sys.argv[2])) recheck = load("recheck", Path(sys.argv[3])) cal = json.loads((root / "calibration-quartiles.json").read_text(encoding="utf-8")) source = root / "CH_Bell_Data.zip" assert timing.sha256(source) == cal["archiveSha256"] assert timing.sha256(Path(sys.argv[2])) == cal["runnerSha256"] flags = json.loads((root / "independent-full-census.json").read_text(encoding="utf-8"))["flagged"] period = cal["medianPeriodBins"] results = [] with ZipFile(source) as archive: inputs = dict(recheck.matching_runs(archive, timing)) inputs[15] = timing.input_blocks(archive) for run, blocks in sorted(inputs.items()): for block in sorted(blocks): marks, clicks = timing.read_block(archive, block) widths = np.diff(marks) valid_widths = np.abs(widths - period) <= timing.GAP_TOLERANCE * period record = {"run": run, "id": block[0], "channels": {}} for st, tags in clicks.items(): preceding = np.searchsorted(marks, tags, side="right") - 1 complete = (preceding >= 0) & (preceding < len(widths)) retained = valid_widths[preceding[complete]] tags = tags[complete][retained] preceding = preceding[complete][retained] phases = (tags - marks[preceding]) * period / widths[preceding] peaks = np.asarray(cal["gateCentersBins"][str(st)]) distance = np.min(np.abs((phases[:, None] - peaks + period / 2) % period - period / 2), axis=1) outside = distance >= timing.GATE_WIDTH tags_off = tags[outside] fast = side_profile(tags_off) tagged = flags.get(f"{run}:{block[0]}", {}).get("detectors", {}).get(str(st)) if tagged: assert tagged["clicks"] == len(tags_off) and tagged["shortGapsUs"]["0.1"] == fast["atMost100Ns"] row = {"offClicks": len(tags_off), "offGaps": fast, "allGaps": side_profile(tags), "flagged": len(tags_off) >= 1000} if len(tags_off) >= 1000: ms = (tags_off - marks[0]) * timing.TICK_US / 1000 row["peakTimingMs"] = {width: int(np.bincount(np.floor(ms / width).astype(int)).argmax()) * width for width in (1, 2, 5, 10, 20)} gap_range = np.diff(tags_off) fast_tail = np.bincount(gap_range[gap_range <= 640], minlength=641) row["atMost100NsHistogram"] = fast_tail.tolist() record["channels"][str(st)] = row results.append(record) assert len(results) == 4450 summary = {} for st in ("1", "2"): station = [row["channels"][st] for row in results] summary[st] = { "flagged": {key: sum(outcome["offGaps"][key] for outcome in station if outcome["flagged"]) for key in ("sampleSize", "atMost100Ns", "from5To25Ns")}, "other": {key: sum(outcome["offGaps"][key] for outcome in station if not outcome["flagged"]) for key in ("sampleSize", "atMost100Ns", "from5To25Ns")}, } flagged_records = [row for row in results if any(st["flagged"] for st in row["channels"].values())] summary["peakTimingForDualStationFlagsMs"] = [ {"run": row["run"], "id": row["id"], "differenceBMinusA": {str(width): row["channels"]["2"]["peakTimingMs"][width] - row["channels"]["1"]["peakTimingMs"][width] for width in (1, 2, 5, 10, 20)}} for row in flagged_records if all(st["flagged"] for st in row["channels"].values()) ] with (root / "fast-spacing-audit.json").open("x", encoding="utf-8") as output: json.dump({"summary": summary, "flaggedRecords": flagged_records, "allRecords": results}, output, separators=(",", ":")) output.write("\n") print(json.dumps(summary, indent=2)) if __name__ == "__main__": main()