"""Explain the weak second harmonic in two archived detector records.""" import argparse import importlib.util import json from pathlib import Path, PurePosixPath from zipfile import ZipFile import numpy as np PAIRS = ((5, 4), (9, 8)) TRAINING_BLOCKS = 50 def original_runner(path): spec = importlib.util.spec_from_file_location("timing", path) timing = importlib.util.module_from_spec(spec) spec.loader.exec_module(timing) return timing def load_blocks(archive, timing, calibration): runs = {number: [] for pair in PAIRS for number in pair} by_folder = {f"05082013_{number} t753 a252ap38": number for number in runs} for item in archive.infolist(): name = PurePosixPath(item.filename) run = by_folder.get(name.parent.name) match = timing.NAME.fullmatch(name.name) if run and match and name.parts[0] == "CH_Bell_Data": settings, clock = match.groups() runs[run].append((int(clock), settings, item)) period = calibration["medianPeriodBins"] phase_rows = {} for run, blocks in runs.items(): phase_rows[run] = {station: [] for station in timing.STATIONS} for block in sorted(blocks): marks, observed = timing.read_block(archive, block) record, _ = timing.folded_tags(marks, observed, period) for station in timing.STATIONS: phases = record["stations"][station]["phases"] centers = calibration["gateCentersBins"][str(station)] narrow = np.logical_or.reduce([timing.clock_window(phases, center, period) for center in centers]) wide = np.logical_or.reduce([np.abs((phases - center + period / 2) % period - period / 2) < timing.GATE_WIDTH for center in centers]) phasors = np.exp(4j * np.pi * phases / period) histogram, _ = timing.distribution(phases, period) phase_rows[run][station].append({"blockId": block[0], "settings": block[1], "setting": block[1][station - 1], "count": len(phases), "narrow": int(narrow.sum()), "wide": int(wide.sum()), "z": phasors.sum(), "in": phasors[narrow].sum(), "far": phasors[~wide].sum(), "histogram": histogram}) return phase_rows def aggregate(rows): return {key: sum(row[key] for row in rows) for key in ("count", "narrow", "wide", "z", "in", "far")} def overview(rows): total = aggregate(rows) within_sum = sum(abs(row["z"]) for row in rows) pooled = total["z"] / total["count"] wide = (total["z"] - total["far"]) / total["wide"] far = total["far"] / (total["count"] - total["wide"]) return {"blocks": len(rows), "clicks": total["count"], "narrowClicks": total["narrow"], "wideClicks": total["wide"], "farClicksPerBlock": (total["count"] - total["wide"]) / len(rows), "insideClicksPerBlock": total["wide"] / len(rows), "pooledSecondHarmonic": abs(total["z"]) / total["count"], "weightedWithinBlockMagnitude": within_sum / total["count"], "phaseAgreementAcrossBlocks": abs(total["z"]) / within_sum, "insideNarrowMagnitude": abs(total["in"]) / total["narrow"], "insideWideMagnitude": abs(wide), "farMagnitude": abs(far), "meanPhasor": [pooled.real, pooled.imag], "insideWidePhasor": [wide.real, wide.imag], "farPhasor": [far.real, far.imag]} def predict(rows, reference): here = aggregate(rows[:TRAINING_BLOCKS]) before = aggregate(reference[:TRAINING_BLOCKS]) tests = [] for start in range(TRAINING_BLOCKS, len(rows), TRAINING_BLOCKS): test = aggregate(rows[start:start + TRAINING_BLOCKS]) share = test["narrow"] / test["count"] measured = test["z"] / test["count"] def mixture(fit): pulse = fit["in"] / fit["narrow"] background = (fit["z"] - fit["in"]) / (fit["count"] - fit["narrow"]) return share * pulse + (1 - share) * background tests.append({"startBlock": start + 1, "endBlock": min(start + TRAINING_BLOCKS, len(rows)), "insideShare": share, "measuredMagnitude": abs(measured), "constantError": abs(measured - here["z"] / here["count"]), "ownMixtureError": abs(measured - mixture(here)), "referenceMixtureError": abs(measured - mixture(before))}) return tests def setting_differences(rows): def far_rate(group): return float(np.mean([row["count"] - row["wide"] for row in group])) strata = [] for start in range(0, len(rows), 20): block = rows[start:start + 20] for a in ("1", "2"): b1 = [row for row in block if row["settings"] == a + "1"] b2 = [row for row in block if row["settings"] == a + "2"] if b1 and b2: strata.append({"startBlock": start + 1, "aSetting": a, "counts": [len(b1), len(b2)], "differenceB1MinusB2": far_rate(b1) - far_rate(b2)}) # All three lag estimates use the same interior outcome blocks. lags = {} for lag in (-1, 0, 1): b1 = [rows[index] for index in range(1, len(rows) - 1) if rows[index + lag]["settings"][1] == "1"] b2 = [rows[index] for index in range(1, len(rows) - 1) if rows[index + lag]["settings"][1] == "2"] lags[str(lag)] = far_rate(b1) - far_rate(b2) return {"strata": strata, "unavailableStrata": 2 * ((len(rows) + 19) // 20) - len(strata), "settingLagDifferences": lags} def mask_model(calibration, timing, station, selected, reference): period = calibration["medianPeriodBins"] width = 2 * timing.GATE_WIDTH inside_measure = 2 * width / period sinc = float(np.sinc(2 * width / period)) edges = calibration["gateCentersBins"][str(station)] uniform_far = -width / period * sinc * np.exp(4j * np.pi * np.array(edges) / period).sum() / (1 - inside_measure) observed_wide_share = selected["wideClicks"] / selected["clicks"] predicted = observed_wide_share * complex(*reference["insideWidePhasor"]) + (1 - observed_wide_share) * uniform_far observed = complex(*selected["meanPhasor"]) return {"uniformOutsideMagnitude": abs(uniform_far), "observedOutsideMagnitude": selected["farMagnitude"], "predictedFullMagnitude": abs(predicted), "observedFullMagnitude": abs(observed), "complexPredictionError": abs(observed - predicted)} def burst_check(samples): detector_a, detector_b = samples[1], samples[2] far = lambda row: row["count"] - row["wide"] ranked = sorted(enumerate(detector_b), key=lambda pair: (-far(pair[1]), pair[0])) assert len(detector_a) == len(detector_b) total = sum(map(far, detector_b)) leading = [{"position": position + 1, "blockId": row["blockId"], "bSetting": row["setting"], "aFar": far(detector_a[position]), "bFar": far(row), "bShare": far(row) / total} for position, row in ranked[:3]] diagnostic = [] for count in (0, 1, 3): omitted = {position for position, _ in ranked[:count]} kept = [row for index, row in enumerate(detector_b) if index not in omitted] setting_rates = {setting: overview([row for row in kept if row["setting"] == setting])["farClicksPerBlock"] for setting in ("1", "2")} diagnostic.append({"omittedBlocks": count, "secondHarmonic": overview(kept)["pooledSecondHarmonic"], "farRateByBSetting": setting_rates, "totalFar": sum(map(far, kept))}) chronology = [{"blockId": row["blockId"], "bSetting": row["setting"], "bFar": far(row), "aFar": far(a)} for row, a in zip(detector_b, detector_a)] return {"ranked": leading, "trims": diagnostic, "chronology": chronology} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("calibration", type=Path) parser.add_argument("runner", type=Path) parser.add_argument("output", type=Path) options = parser.parse_args() timing = original_runner(options.runner) with options.calibration.open(encoding="utf-8") as input_file: calibration = json.load(input_file) if timing.sha256(options.archive) != calibration["archiveSha256"] or timing.sha256(options.runner) != calibration["runnerSha256"]: raise SystemExit("Archive or exact calibration runner changed.") with ZipFile(options.archive) as archive: samples = load_blocks(archive, timing, calibration) declared = {4: 500, 5: 200, 8: 200, 9: 200} if any(len(samples[run][1]) != blocks for run, blocks in declared.items()): raise SystemExit("The four original archive runs have unexpected lengths.") report = {"archiveSha256": calibration["archiveSha256"], "calibrationSha256": timing.sha256(options.calibration), "histogramRangeUs": [calibration["medianPeriodBins"] * timing.TICK_US * scale for scale in (-0.25, 0.75)], "comparisons": []} for current, reference in PAIRS: entry = {"run": current, "reference": reference, "stations": {}} for station in timing.STATIONS: first, prior = samples[current][station], samples[reference][station] per_setting = {value: {"run": overview([r for r in first if r["setting"] == value]), "reference": overview([r for r in prior if r["setting"] == value])} for value in ("1", "2")} entry["stations"][str(station)] = {"run": overview(first), "reference": overview(prior), "byLocalSetting": per_setting, "validation": predict(first, prior), "runHistogram": np.stack([r["histogram"] for r in first]).sum(axis=0).tolist(), "referenceHistogram": np.stack([r["histogram"] for r in prior]).sum(axis=0).tolist()} station_result = entry["stations"][str(station)] station_result["compareByBSetting"] = setting_differences(first) station_result["maskModel"] = mask_model(calibration, timing, station, station_result["run"], station_result["reference"]) entry["burstCheck"] = burst_check(samples[current]) entry["referenceBurstCheck"] = burst_check(samples[reference]) report["comparisons"].append(entry) with options.output.open("x", encoding="utf-8") as file: json.dump(report, file, indent=2) file.write("\n") print(options.output) if __name__ == "__main__": main()