Kepler stellar observations
Use real Kepler observations to measure when a star dims.

| 1 | """Evaluate a submitted ephemeris against the project's reserved Kepler data.""" |
| 2 | |
| 3 | import argparse |
| 4 | import ast |
| 5 | import csv |
| 6 | import gzip |
| 7 | import json |
| 8 | import math |
| 9 | import os |
| 10 | from pathlib import Path |
| 11 | from statistics import median |
| 12 | from examples.observe_archive import observation |
| 13 | |
| 14 | ROOT = Path(__file__).resolve().parent |
| 15 | |
| 16 | |
| 17 | def lightcurve(file): |
| 18 | with gzip.open(ROOT / file, "rt", newline="") as handle: |
| 19 | reader = csv.reader(handle) |
| 20 | next(reader) |
| 21 | return [(float(time), int(flux)) for time, flux in reader] |
| 22 | |
| 23 | |
| 24 | def measure(rows, period, epoch, duration, offset=0.0): |
| 25 | """Compare the window with its local baseline once per observed orbit.""" |
| 26 | width = duration / 24 |
| 27 | epoch += offset * period |
| 28 | windows = {} |
| 29 | for time, flux in rows: |
| 30 | cycle = math.floor((time - epoch) / period + 0.5) |
| 31 | distance = abs(time - epoch - cycle * period) |
| 32 | if distance <= width / 2: |
| 33 | windows.setdefault(cycle, ([], []))[0].append(flux) |
| 34 | elif width <= distance <= 2 * width: |
| 35 | windows.setdefault(cycle, ([], []))[1].append(flux) |
| 36 | |
| 37 | depths = [median(outside) - median(inside) for inside, outside in windows.values() |
| 38 | if len(inside) >= 2 and len(outside) >= 4] |
| 39 | if not depths: |
| 40 | return {"events": 0, "depth_ppm": 0.0, "snr": 0.0} |
| 41 | depth = median(depths) |
| 42 | scatter = max(40.0, 1.4826 * median(abs(value - depth) for value in depths)) |
| 43 | return {"events": len(depths), "depth_ppm": round(depth, 1), |
| 44 | "snr": round(depth * math.sqrt(len(depths)) / scatter, 2)} |
| 45 | |
| 46 | |
| 47 | def folded(rows, period, epoch, duration): |
| 48 | """Summarize held-out flux from two durations before to two after the prediction.""" |
| 49 | bins = [[] for _ in range(24)] |
| 50 | outside = [] |
| 51 | for time, flux in rows: |
| 52 | offset = (((time - epoch + period / 2) % period) - period / 2) * 24 |
| 53 | if -2 * duration <= offset < 2 * duration: |
| 54 | bucket = min(len(bins) - 1, int((offset / duration + 2) * len(bins) / 4)) |
| 55 | bins[bucket].append(flux) |
| 56 | if abs(offset) >= duration: |
| 57 | outside.append(flux) |
| 58 | if not outside: |
| 59 | return [] |
| 60 | baseline = median(outside) |
| 61 | return [round(median(values) - baseline, 1) if values else None for values in bins] |
| 62 | |
| 63 | |
| 64 | def inspect(route): |
| 65 | submitted = route / "solve.py" |
| 66 | result = route / "result.json" |
| 67 | for path, limit in ((submitted, 100_000), (result, 8_000)): |
| 68 | if path.is_symlink() or not path.is_file() or not 0 < path.stat().st_size <= limit: |
| 69 | raise ValueError(f"{path.name} must be a plain file between 1 and {limit:,} bytes.") |
| 70 | ast.parse(submitted.read_bytes(), filename="solve.py") |
| 71 | answer = json.loads(result.read_text()) |
| 72 | if not isinstance(answer, dict): |
| 73 | raise ValueError("result.json must contain a JSON object.") |
| 74 | return answer |
| 75 | |
| 76 | |
| 77 | def ephemeris(answer, record): |
| 78 | star = answer.get("star") |
| 79 | numbers = [answer.get(key) for key in ("period_days", "epoch_bkjd", "duration_hours")] |
| 80 | if not all(type(value) in (int, float) and math.isfinite(value) for value in numbers): |
| 81 | raise ValueError("period_days, epoch_bkjd and duration_hours must be finite numbers.") |
| 82 | period, epoch, duration = numbers |
| 83 | if not (0.5 <= period <= 30 and 0.75 <= duration <= min(8, period * 4.32)): |
| 84 | 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.") |
| 85 | if not record["train"]["min_bkjd"] <= epoch <= record["train"]["max_bkjd"]: |
| 86 | raise ValueError("Use an equivalent reference epoch within the training time range, in BKJD.") |
| 87 | return star, period, epoch, duration |
| 88 | |
| 89 | |
| 90 | def signal(rows, star, period, epoch, duration): |
| 91 | primary = measure(rows, period, epoch, duration) |
| 92 | coverage = primary["events"] >= 8 |
| 93 | score = int(coverage and primary["depth_ppm"] >= 150 and primary["snr"] >= 5) |
| 94 | secondary = None |
| 95 | outcome = "not_reproduced" if coverage else "insufficient" |
| 96 | verdict = "no clear recurring dip in the held-out data" if coverage else "not enough covered events in the held-out data" |
| 97 | if score: |
| 98 | # A companion eclipse may land away from phase one-half on an eccentric orbit. |
| 99 | gap = max(0.18, 2.5 * duration / (24 * period)) |
| 100 | eclipses = ({"phase": phase / 40, **measure(rows, period, epoch, duration, phase / 40)} |
| 101 | for phase in range(8, 33) if gap <= phase / 40 <= 1 - gap) |
| 102 | secondary = max((event for event in eclipses if event["events"] >= 8 and event["snr"] >= 5), |
| 103 | key=lambda event: event["depth_ppm"], default=None) |
| 104 | if secondary and secondary["depth_ppm"] >= 0.2 * primary["depth_ppm"]: |
| 105 | score = 0 |
| 106 | verdict = "a second dip is consistent with eclipsing stars" |
| 107 | else: |
| 108 | outcome = "reproduced" |
| 109 | verdict = "recurring dip reproduced in the held-out data" |
| 110 | return {"score": score, "subtasks": {star: score}, "outcome": outcome, "primary": primary, |
| 111 | "folded_ppm": folded(rows, period, epoch, duration), "secondary": secondary, "verdict": verdict} |
| 112 | |
| 113 | |
| 114 | def verify_archival(answer, archive): |
| 115 | star = archive["star"] |
| 116 | if answer.get("star") != star: |
| 117 | raise ValueError("Use the Kepler catalog number assigned on the activity page.") |
| 118 | early, later = archive["early"], archive["later"] |
| 119 | expected = observation(early) |
| 120 | if answer.get("observation") != expected: |
| 121 | raise ValueError("The submitted summary does not match the archival early observations.") |
| 122 | recorded = {"score": 1, "subtasks": {star: 1}, "outcome": "observed", |
| 123 | "early_observation": expected, "later_observation": observation(later), |
| 124 | "source": archive["source"], "source_sha256": archive["source_sha256"], |
| 125 | "ra": archive["ra"], "dec": archive["dec"], "verdict": "archival observation verified"} |
| 126 | if "period_days" in answer: |
| 127 | predicted = signal(later, *ephemeris(answer, {"train": {"min_bkjd": early[0][0], "max_bkjd": early[-1][0]}})) |
| 128 | recorded["signal"] = predicted |
| 129 | recorded["verdict"] += f"; {predicted['verdict']}" |
| 130 | return recorded |
| 131 | |
| 132 | |
| 133 | def verify(route): |
| 134 | input_root = os.environ.get("SS_INPUT") |
| 135 | if input_root and route.resolve() != Path(input_root).resolve() / route.relative_to(input_root): |
| 136 | raise ValueError("The route directory must be in the submitted tree and cannot be a symlink.") |
| 137 | answer = inspect(route) |
| 138 | # The site attaches this file to the approved code archive, outside the submitted tree. |
| 139 | bundle = ROOT / ".shoal" / "kepler-archive.json.gz" |
| 140 | if bundle.is_file(): |
| 141 | with gzip.open(bundle, "rt") as handle: |
| 142 | return verify_archival(answer, json.load(handle)) |
| 143 | targets = json.loads((ROOT / "observations/sources.json").read_text()) |
| 144 | star = answer.get("star") |
| 145 | if not isinstance(star, str) or star not in targets: |
| 146 | raise ValueError("Choose a star from stars.json or select an archive target in the activity.") |
| 147 | record = targets[star] |
| 148 | return signal(lightcurve(record["holdout"]["file"]), *ephemeris(answer, record)) |
| 149 | |
| 150 | |
| 151 | def main(): |
| 152 | parser = argparse.ArgumentParser(description=__doc__) |
| 153 | parser.add_argument("route", type=Path) |
| 154 | parser.add_argument("--metrics", type=Path) |
| 155 | args = parser.parse_args() |
| 156 | try: |
| 157 | evidence = verify(args.route) |
| 158 | except (OSError, OverflowError, SyntaxError, ValueError) as error: |
| 159 | parser.exit(1, f"Verification failed: {error}\n") |
| 160 | if args.metrics: |
| 161 | args.metrics.write_text(json.dumps(evidence) + "\n") |
| 162 | star = next(iter(evidence["subtasks"])) |
| 163 | if evidence["outcome"] == "observed": |
| 164 | print(f"{star}: {evidence['verdict']} ({evidence['early_observation']['samples']} early and " |
| 165 | f"{evidence['later_observation']['samples']} later measurements).") |
| 166 | else: |
| 167 | primary = evidence["primary"] |
| 168 | print(f"{star}: {evidence['verdict']} ({primary['events']} events, " |
| 169 | f"{primary['depth_ppm']:g} ppm, S/N {primary['snr']:g}).") |
| 170 | |
| 171 | |
| 172 | if __name__ == "__main__": |
| 173 | main() |