"""Inventory off-pulse clicks in every recorded run using frozen timing gates.""" import argparse import importlib.util import json from pathlib import Path from zipfile import ZipFile import numpy as np HALF_WIDTHS = (9000, 18000, 36000) CUTOFFS = (500, 1000, 2000) STATIONS = (1, 2) def module_at(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 measure_block(archive, timing, entry, calibration): block_id, setting, _ = entry marks, clicks = timing.read_block(archive, entry) period = calibration["medianPeriodBins"] record, intervals = timing.folded_tags(marks, clicks, period) widths = np.diff(marks) valid = np.abs(widths - period) <= timing.GAP_TOLERANCE * period result = {"id": block_id, "setting": setting, "clockIntervals": len(widths), "eligibleIntervals": len(intervals), "medianMarkerUs": float(np.median(intervals) * timing.TICK_US), "channels": {}} for station in STATIONS: phases = record["stations"][station]["phases"] centers = calibration["gateCentersBins"][str(station)] distance = np.min(np.abs((phases[:, None] - centers + period / 2) % period - period / 2), axis=1) outside = [int(np.count_nonzero(distance >= radius)) for radius in HALF_WIDTHS] z = np.exp(4j * np.pi * phases / period).sum() channel = {"acceptedClicks": len(phases), "outside": outside, "z": [float(z.real), float(z.imag)]} result["channels"][str(station)] = channel if outside[1] >= CUTOFFS[0]: tags = clicks[station] marker = np.searchsorted(marks, tags, side="right") - 1 complete = (marker >= 0) & (marker < len(widths)) tags = tags[complete][valid[marker[complete]]][distance >= HALF_WIDTHS[1]] seconds = (tags - marks[0]) * timing.TICK_US / 1_000_000 bins = np.floor(seconds / 0.02).astype(int) histogram = np.bincount(bins) peak = int(histogram.argmax()) channel["peak20ms"] = {"startMs": peak * 20, "count": int(histogram[peak]), "histogram": histogram.tolist()} return result def summarize(runs): summary = {"thresholds": {}, "primaryFlags": [], "primaryStatistics": {}, "runStatistics": {}} for station in map(str, STATIONS): channels = [row["channels"][station] for rows in runs.values() for row in rows] summary["thresholds"][station] = { width: {cutoff: sum(row["outside"][position] >= cutoff for row in channels) for cutoff in CUTOFFS} for position, width in enumerate(HALF_WIDTHS) } off = [row["outside"][1] for row in channels] summary["primaryStatistics"][station] = { "median": float(np.median(off)), "total": sum(off), "maximum": max(off), "flaggedClicks": sum(value for value in off if value >= CUTOFFS[1]), } for run, blocks in runs.items(): stats = {} for station in map(str, STATIONS): rows = [row["channels"][station] for row in blocks] flags = [row for row in rows if row["outside"][1] >= CUTOFFS[1]] without = [row for row in rows if row["outside"][1] < CUTOFFS[1]] count = sum(row["acceptedClicks"] for row in rows) full = abs(sum(complex(*row["z"]) for row in rows)) / count restricted = abs(sum(complex(*row["z"]) for row in without)) / sum(row["acceptedClicks"] for row in without) stats[station] = {"offPulseClicks": sum(row["outside"][1] for row in rows), "flaggedBlocks": len(flags), "fullHarmonic": full, "diagnosticHarmonic": restricted} summary["runStatistics"][run] = stats for index, row in enumerate(blocks, 1): if any(channel["outside"][1] >= CUTOFFS[0] for channel in row["channels"].values()): summary["primaryFlags"].append({"run": run, "position": index, **row}) return summary def main(): parser = argparse.ArgumentParser(description=__doc__) for name in ("archive", "calibration", "timing_runner", "cross_run_runner", "output"): parser.add_argument(name, type=Path) args = parser.parse_args() timing = module_at("spark_timing_calibration", args.timing_runner) recheck = module_at("spark_cross_run_calibration", args.cross_run_runner) calibration = json.loads(args.calibration.read_text(encoding="utf-8")) if timing.sha256(args.archive) != calibration["archiveSha256"] or timing.sha256(args.timing_runner) != calibration["runnerSha256"]: raise SystemExit("The calibration requires its verified original source files.") with ZipFile(args.archive) as archive: inventory = dict(recheck.matching_runs(archive, timing)) inventory[15] = timing.input_blocks(archive) if len(inventory) != 20 or sum(map(len, inventory.values())) != 4450: raise SystemExit("Unexpected inventory for the verified archive.") runs = {} for run, entries in sorted(inventory.items()): ordered = sorted(entries) if len({entry[0] for entry in ordered}) != len(ordered): raise SystemExit(f"Repeated acquisition ID in run {run}.") runs[run] = [measure_block(archive, timing, entry, calibration) for entry in ordered] report = {"archiveSha256": calibration["archiveSha256"], "calibrationSha256": timing.sha256(args.calibration), "runnerSha256": timing.sha256(__file__), "gateHalfWidthsBins": HALF_WIDTHS, "cutoffs": CUTOFFS, "blockCount": 4450, "summary": summarize(runs), "runs": runs} with args.output.open("x", encoding="utf-8") as output: json.dump(report, output, separators=(",", ":")) output.write("\n") brief = {key: report["summary"][key] for key in ("thresholds", "primaryStatistics")} brief["flagsAt500"] = [[row["run"], row["id"], *(r["outside"][1] for r in row["channels"].values())] for row in report["summary"]["primaryFlags"]] print(json.dumps(brief, indent=2)) if __name__ == "__main__": main()