"""Score the published CH terms on the predefined replacement time gates.""" import argparse import importlib.util import json from pathlib import Path, PurePosixPath from zipfile import ZipFile import numpy as np def load_timing_runner(path): spec = importlib.util.spec_from_file_location("timing", path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def classify(timing, marks, observations, calibration): cycle = calibration["medianPeriodBins"] widths = np.diff(marks) eligible = np.abs(widths - cycle) <= cycle * timing.GAP_TOLERANCE number_of_slots = 2 * int(eligible.sum()) hits = {"pulses": {}, "controls": {}} for station in timing.STATIONS: clicks = observations[station] index = np.searchsorted(marks, clicks, side="right") - 1 internal = (index >= 0) & (index < len(widths)) valid = eligible[index[internal]] ix = index[internal][valid] phase = (clicks[internal][valid] - marks[ix]) / widths[ix] * cycle for label, move in (("pulses", 0), ("controls", cycle / 4)): frames = [ 2 * ix[timing.clock_window(phase, center + move, cycle)] + offset for offset, center in enumerate(calibration["gateCentersBins"][str(station)]) ] hits[label][station] = np.unique(np.concatenate(frames)) rows = {} for label, detectors in hits.items(): station_a, station_b = detectors[1], detectors[2] joined = np.intersect1d(station_a, station_b, assume_unique=True) rows[label] = [number_of_slots, len(station_a), len(station_b), len(joined)] return rows def score(table): """Table rows are 11, 12, 21, 22. Columns give N, A, B and both.""" trials, a, b, joined = table.T.astype(float) if (trials == 0).any(): return None rates = joined / trials a_rate = a[:2].sum() / trials[:2].sum() b_rate = b[::2].sum() / trials[::2].sum() coincidence_term = float(sum(rates[:3]) - rates[3]) single_term = float(a_rate + b_rate) return {"coincidenceRates": rates.tolist(), "pooledFirstSettingSingles": [float(a_rate), float(b_rate)], "difference": coincidence_term - single_term, "normalizedRatio": coincidence_term / single_term if single_term else None} def summarize(blocks): total = blocks.sum(axis=0) result = score(total) if result is None: raise ValueError("The selected blocks lack a setting.") groups = blocks.reshape(-1, 10, 4, 4).sum(axis=1) generator = np.random.default_rng(20261129) sampled = generator.integers(0, len(groups), size=(4096, len(groups))) resamples = [score(groups[indices].sum(axis=0)) for indices in sampled] usable = [item for item in resamples if item is not None] result["blockResamplePercentiles"] = np.quantile([item["difference"] for item in usable], [0.025, 0.5, 0.975]).tolist() result["resamplesScored"] = len(usable) result["observedCounts"] = { key: dict(zip(["trials", "aClicks", "bClicks", "coincidences"], row.tolist())) for key, row in zip(["11", "12", "21", "22"], total) } return result def known_widths(archive, timing, blocks, calibration): other = [] for entry in archive.infolist(): filename = PurePosixPath(entry.filename) if filename.parent.name != "05082013_17 t753 a252ap38": continue match = timing.NAME.fullmatch(filename.name) if match: setting, index = match.groups() other.append((int(index), setting, entry)) if len(other) != 300 or len({block[0] for block in other}) != 300: raise ValueError("Run 17 must contain 300 distinct setting blocks.") widths = (12000, 18000, 24000, 36000) settings = ["11", "12", "21", "22"] result = {} original_width = timing.GATE_WIDTH try: for group, chosen in (("run15Holdout", blocks[30:]), ("run17", other)): totals = {width: np.zeros((4, 4), dtype=np.int64) for width in widths} for block in chosen: marks, observations = timing.read_block(archive, block) for width in widths: timing.GATE_WIDTH = width totals[width][settings.index(block[1])] += classify(timing, marks, observations, calibration)["pulses"] result[group] = [dict(windowTimebins=width, windowUs=width * timing.TICK_US, blocks=len(chosen), counts=totals[width].tolist(), **score(totals[width])) for width in widths] finally: timing.GATE_WIDTH = original_width return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("calibration", type=Path) parser.add_argument("existing_runner", type=Path) parser.add_argument("output", type=Path) parser.add_argument("--width-check", action="store_true") options = parser.parse_args() timing = load_timing_runner(options.existing_runner) with options.calibration.open(encoding="utf-8") as stream: calibration = json.load(stream) if timing.sha256(options.archive) != calibration["archiveSha256"] or timing.sha256(options.existing_runner) != calibration["runnerSha256"]: raise SystemExit("The archive or frozen timing runner changed.") rows = {"pulses": [], "controls": []} factors = {key: index for index, key in enumerate(["11", "12", "21", "22"])} with ZipFile(options.archive) as archive: blocks = timing.input_blocks(archive) if calibration["calibratedBlocks"] != [block[0] for block in blocks[:30]]: raise SystemExit("The predefined calibration block list changed.") if options.width_check: result = known_widths(archive, timing, blocks, calibration) with options.output.open("x", encoding="utf-8") as stream: json.dump(result, stream, indent=2) stream.write("\n") print(options.output) return for block in blocks[30:]: marks, observations = timing.read_block(archive, block) by_window = classify(timing, marks, observations, calibration) for label, counts in by_window.items(): matrix = np.zeros((4, 4), dtype=np.int64) matrix[factors[block[1]]] = counts rows[label].append(matrix) result = {"archiveSha256": calibration["archiveSha256"], "stream": calibration["run"], "holdoutBlocks": len(blocks[30:]), "subsamples": 27, "blocksPerSubsample": 10, "results": {label: summarize(np.stack(matrices)) for label, matrices in rows.items()}} with options.output.open("x", encoding="utf-8") as stream: json.dump(result, stream, indent=2) stream.write("\n") print(options.output) if __name__ == "__main__": main()