"""Evaluate a submitted ephemeris against the project's later Kepler observations.""" import argparse import ast import csv import gzip import json import math import os from bisect import bisect_left, bisect_right from itertools import combinations from pathlib import Path from statistics import median from examples.observe_archive import observation ROOT = Path(__file__).resolve().parent def lightcurve(file): with gzip.open(ROOT / file, "rt", newline="") as handle: reader = csv.reader(handle) next(reader) return [(float(time), int(flux)) for time, flux in reader] def dips(rows, period, epoch, duration, offset=0.0): """Each observed orbit's baseline median minus its in-window median, by orbit number from the epoch.""" width = duration / 24 epoch += offset * period windows = {} for time, flux in rows: cycle = math.floor((time - epoch) / period + 0.5) distance = abs(time - epoch - cycle * period) if distance <= width / 2: windows.setdefault(cycle, ([], []))[0].append(flux) elif width <= distance <= 2 * width: windows.setdefault(cycle, ([], []))[1].append(flux) return {cycle: median(outside) - median(inside) for cycle, (inside, outside) in windows.items() if len(inside) >= 2 and len(outside) >= 4} def measure(rows, period, epoch, duration, offset=0.0): """Compare the window with its local baseline once per observed orbit.""" depths = list(dips(rows, period, epoch, duration, offset).values()) if not depths: return {"events": 0, "depth_ppm": 0.0, "snr": 0.0} depth = median(depths) scatter = max(40.0, 1.4826 * median(abs(value - depth) for value in depths)) return {"events": len(depths), "depth_ppm": round(depth, 1), "snr": round(depth * math.sqrt(len(depths)) / scatter, 2)} def odd_even(depths): """Kepler Data Validation's odd/even depth test, run on odd and even orbits and again on every third orbit. With half or a third of the true period, only every second or third window holds the dip, and the median over all windows can still pass. So the per-orbit dips are split by orbit number modulo 2 and then modulo 3, and each pair of groups is compared with a rank-sum (Mann-Whitney) test: it needs no noise model, and the few windows a data gap cuts short do not move it. A pair more than 5 standard deviations apart, the bar the S/N also uses, means the dip does not recur every orbit. Groups under 18 events each cannot reach that bar, so a short series passes this test untested. Returns the modulus and the two groups' median dips, deeper first, or None. """ for every in (2, 3): groups = [[depth for cycle, depth in depths.items() if cycle % every == rest] for rest in range(every)] for one, other in combinations(groups, 2): if not one or not other: continue ranked = sorted(other) # How often a dip in `one` is deeper than a dip in `other`, ties counting half. deeper = sum(bisect_left(ranked, depth) + bisect_right(ranked, depth) for depth in one) / 2 n, m = len(one), len(other) if abs(deeper - n * m / 2) > 5 * math.sqrt(n * m * (n + m + 1) / 12): return every, *sorted((median(one), median(other)), reverse=True) return None def folded(rows, period, epoch, duration): """Summarize the later window's flux from two durations before to two after the prediction.""" bins = [[] for _ in range(24)] outside = [] for time, flux in rows: offset = (((time - epoch + period / 2) % period) - period / 2) * 24 if -2 * duration <= offset < 2 * duration: bucket = min(len(bins) - 1, int((offset / duration + 2) * len(bins) / 4)) bins[bucket].append(flux) if abs(offset) >= duration: outside.append(flux) if not outside: return [] baseline = median(outside) return [round(median(values) - baseline, 1) if values else None for values in bins] def inspect(route): submitted = route / "solve.py" result = route / "result.json" for path, limit in ((submitted, 100_000), (result, 8_000)): if path.is_symlink() or not path.is_file() or not 0 < path.stat().st_size <= limit: raise ValueError(f"{path.name} must be a plain file between 1 and {limit:,} bytes.") ast.parse(submitted.read_bytes(), filename="solve.py") answer = json.loads(result.read_text()) if not isinstance(answer, dict): raise ValueError("result.json must contain a JSON object.") return answer def ephemeris(answer, record): star = answer.get("star") numbers = [answer.get(key) for key in ("period_days", "epoch_bkjd", "duration_hours")] if not all(type(value) in (int, float) and math.isfinite(value) for value in numbers): raise ValueError("period_days, epoch_bkjd and duration_hours must be finite numbers.") period, epoch, duration = numbers if not (0.5 <= period <= 30 and 0.75 <= duration <= min(8, period * 4.32)): raise ValueError("Use a period from 0.5 to 30 days and a duration from 0.75 to 8 hours, at most 18% of the period.") if not record["train"]["min_bkjd"] <= epoch <= record["train"]["max_bkjd"]: raise ValueError("Use an equivalent reference epoch within the training time range, in BKJD.") return star, period, epoch, duration def signal(rows, star, period, epoch, duration): primary = measure(rows, period, epoch, duration) coverage = primary["events"] >= 8 score = int(coverage and primary["depth_ppm"] >= 150 and primary["snr"] >= 5) secondary = None outcome = "not_reproduced" if coverage else "insufficient" verdict = "no clear recurring dip in the later observations" if coverage else "not enough covered events in the later observations" uneven = odd_even(dips(rows, period, epoch, duration)) if score else None if uneven: every, deeper, shallower = uneven score = 0 verdict = (f"odd and even events differ ({round(deeper)} vs {round(shallower)} ppm): " "the period looks like half the true one" if every == 2 else f"events in every third orbit differ ({round(deeper)} vs {round(shallower)} ppm): " "the period looks like a third of the true one") elif score: # A companion eclipse may land away from phase one-half on an eccentric orbit. With m times the true period # the same dip returns at phase k/m; an even grid finer than half the window finds a dip anywhere else. width = duration / (24 * period) gap = max(0.18, 2.5 * width) steps = math.floor(2 / width) + 1 phases = {k / m for m in range(2, 6) for k in range(1, m)} | {k / steps for k in range(1, steps)} eclipses = ({"phase": round(phase, 4), **measure(rows, period, epoch, duration, phase)} for phase in sorted(phases) if gap <= phase <= 1 - gap) secondary = max((event for event in eclipses if event["events"] >= 8 and event["snr"] >= 5), key=lambda event: event["depth_ppm"], default=None) if secondary and secondary["depth_ppm"] >= 0.2 * primary["depth_ppm"]: score = 0 verdict = "a second dip is consistent with eclipsing stars" else: outcome = "reproduced" verdict = "recurring dip reproduced in the later observations" return {"score": score, "subtasks": {star: score}, "outcome": outcome, "primary": primary, "folded_ppm": folded(rows, period, epoch, duration), "secondary": secondary, "verdict": verdict} def verify_archival(answer, archive): star = archive["star"] if answer.get("star") != star: raise ValueError("Use the Kepler catalog number assigned on the activity page.") early, later = archive["early"], archive["later"] expected = observation(early) if answer.get("observation") != expected: raise ValueError("The submitted summary does not match the archival early observations.") recorded = {"score": 1, "subtasks": {star: 1}, "outcome": "observed", "early_observation": expected, "later_observation": observation(later), "source": archive["source"], "source_sha256": archive["source_sha256"], "ra": archive["ra"], "dec": archive["dec"], "verdict": "archival observation verified"} if "period_days" in answer: predicted = signal(later, *ephemeris(answer, {"train": {"min_bkjd": early[0][0], "max_bkjd": early[-1][0]}})) recorded["signal"] = predicted recorded["verdict"] += f"; {predicted['verdict']}" return recorded def verify(route): input_root = os.environ.get("SS_INPUT") if input_root and route.resolve() != Path(input_root).resolve() / route.relative_to(input_root): raise ValueError("The route directory must be in the submitted tree and cannot be a symlink.") answer = inspect(route) # The site attaches this file to the approved code archive, outside the submitted tree. bundle = ROOT / ".shoal" / "kepler-archive.json.gz" if bundle.is_file(): with gzip.open(bundle, "rt") as handle: return verify_archival(answer, json.load(handle)) targets = json.loads((ROOT / "observations/sources.json").read_text()) star = answer.get("star") if not isinstance(star, str) or star not in targets: raise ValueError("Choose a star from stars.json or select an archive target in the activity.") record = targets[star] return signal(lightcurve(record["holdout"]["file"]), *ephemeris(answer, record)) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("route", type=Path) parser.add_argument("--metrics", type=Path) args = parser.parse_args() try: evidence = verify(args.route) except (OSError, OverflowError, SyntaxError, ValueError) as error: parser.exit(1, f"Verification failed: {error}\n") if args.metrics: args.metrics.write_text(json.dumps(evidence) + "\n") star = next(iter(evidence["subtasks"])) if evidence["outcome"] == "observed": print(f"{star}: {evidence['verdict']} ({evidence['early_observation']['samples']} early and " f"{evidence['later_observation']['samples']} later measurements).") else: primary = evidence["primary"] print(f"{star}: {evidence['verdict']} ({primary['events']} events, " f"{primary['depth_ppm']:g} ppm, S/N {primary['snr']:g}).") if __name__ == "__main__": main()