"""Evaluate a submitted ephemeris against the project's reserved Kepler data.""" import argparse import ast import csv import gzip import json import math import os 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 measure(rows, period, epoch, duration, offset=0.0): """Compare the window with its local baseline once per observed orbit.""" 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) depths = [median(outside) - median(inside) for inside, outside in windows.values() if len(inside) >= 2 and len(outside) >= 4] 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 folded(rows, period, epoch, duration): """Summarize held-out 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 held-out data" if coverage else "not enough covered events in the held-out data" if score: # A companion eclipse may land away from phase one-half on an eccentric orbit. gap = max(0.18, 2.5 * duration / (24 * period)) eclipses = ({"phase": phase / 40, **measure(rows, period, epoch, duration, phase / 40)} for phase in range(8, 33) if gap <= phase / 40 <= 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 held-out data" 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()