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

| 1 | """Evaluate a submitted ephemeris against the project's later Kepler observations.""" |
| 2 | |
| 3 | import argparse |
| 4 | import ast |
| 5 | import csv |
| 6 | import gzip |
| 7 | import json |
| 8 | import math |
| 9 | import os |
| 10 | from bisect import bisect_left, bisect_right |
| 11 | from itertools import combinations |
| 12 | from pathlib import Path |
| 13 | from statistics import median |
| 14 | from examples.observe_archive import observation |
| 15 | |
| 16 | ROOT = Path(__file__).resolve().parent |
| 17 | |
| 18 | |
| 19 | def lightcurve(file): |
| 20 | with gzip.open(ROOT / file, "rt", newline="") as handle: |
| 21 | reader = csv.reader(handle) |
| 22 | next(reader) |
| 23 | return [(float(time), int(flux)) for time, flux in reader] |
| 24 | |
| 25 | |
| 26 | def dips(rows, period, epoch, duration, offset=0.0): |
| 27 | """Each observed orbit's baseline median minus its in-window median, by orbit number from the epoch.""" |
| 28 | width = duration / 24 |
| 29 | epoch += offset * period |
| 30 | windows = {} |
| 31 | for time, flux in rows: |
| 32 | cycle = math.floor((time - epoch) / period + 0.5) |
| 33 | distance = abs(time - epoch - cycle * period) |
| 34 | if distance <= width / 2: |
| 35 | windows.setdefault(cycle, ([], []))[0].append(flux) |
| 36 | elif width <= distance <= 2 * width: |
| 37 | windows.setdefault(cycle, ([], []))[1].append(flux) |
| 38 | return {cycle: median(outside) - median(inside) for cycle, (inside, outside) in windows.items() |
| 39 | if len(inside) >= 2 and len(outside) >= 4} |
| 40 | |
| 41 | |
| 42 | def measure(rows, period, epoch, duration, offset=0.0): |
| 43 | """Compare the window with its local baseline once per observed orbit.""" |
| 44 | depths = list(dips(rows, period, epoch, duration, offset).values()) |
| 45 | if not depths: |
| 46 | return {"events": 0, "depth_ppm": 0.0, "snr": 0.0} |
| 47 | depth = median(depths) |
| 48 | scatter = max(40.0, 1.4826 * median(abs(value - depth) for value in depths)) |
| 49 | return {"events": len(depths), "depth_ppm": round(depth, 1), |
| 50 | "snr": round(depth * math.sqrt(len(depths)) / scatter, 2)} |
| 51 | |
| 52 | |
| 53 | def odd_even(depths): |
| 54 | """Kepler Data Validation's odd/even depth test, run on odd and even orbits and again on every third orbit. |
| 55 | |
| 56 | With half or a third of the true period, only every second or third window holds the dip, and the median over |
| 57 | all windows can still pass. So the per-orbit dips are split by orbit number modulo 2 and then modulo 3, and each |
| 58 | pair of groups is compared with a rank-sum (Mann-Whitney) test: it needs no noise model, and the few windows a |
| 59 | data gap cuts short do not move it. A pair more than 5 standard deviations apart, the bar the S/N also uses, |
| 60 | means the dip does not recur every orbit. Groups under 18 events each cannot reach that bar, so a short series |
| 61 | passes this test untested. Returns the modulus and the two groups' median dips, deeper first, or None. |
| 62 | """ |
| 63 | for every in (2, 3): |
| 64 | groups = [[depth for cycle, depth in depths.items() if cycle % every == rest] for rest in range(every)] |
| 65 | for one, other in combinations(groups, 2): |
| 66 | if not one or not other: |
| 67 | continue |
| 68 | ranked = sorted(other) |
| 69 | # How often a dip in `one` is deeper than a dip in `other`, ties counting half. |
| 70 | deeper = sum(bisect_left(ranked, depth) + bisect_right(ranked, depth) for depth in one) / 2 |
| 71 | n, m = len(one), len(other) |
| 72 | if abs(deeper - n * m / 2) > 5 * math.sqrt(n * m * (n + m + 1) / 12): |
| 73 | return every, *sorted((median(one), median(other)), reverse=True) |
| 74 | return None |
| 75 | |
| 76 | |
| 77 | def folded(rows, period, epoch, duration): |
| 78 | """Summarize the later window's flux from two durations before to two after the prediction.""" |
| 79 | bins = [[] for _ in range(24)] |
| 80 | outside = [] |
| 81 | for time, flux in rows: |
| 82 | offset = (((time - epoch + period / 2) % period) - period / 2) * 24 |
| 83 | if -2 * duration <= offset < 2 * duration: |
| 84 | bucket = min(len(bins) - 1, int((offset / duration + 2) * len(bins) / 4)) |
| 85 | bins[bucket].append(flux) |
| 86 | if abs(offset) >= duration: |
| 87 | outside.append(flux) |
| 88 | if not outside: |
| 89 | return [] |
| 90 | baseline = median(outside) |
| 91 | return [round(median(values) - baseline, 1) if values else None for values in bins] |
| 92 | |
| 93 | |
| 94 | def inspect(route): |
| 95 | submitted = route / "solve.py" |
| 96 | result = route / "result.json" |
| 97 | for path, limit in ((submitted, 100_000), (result, 8_000)): |
| 98 | if path.is_symlink() or not path.is_file() or not 0 < path.stat().st_size <= limit: |
| 99 | raise ValueError(f"{path.name} must be a plain file between 1 and {limit:,} bytes.") |
| 100 | ast.parse(submitted.read_bytes(), filename="solve.py") |
| 101 | answer = json.loads(result.read_text()) |
| 102 | if not isinstance(answer, dict): |
| 103 | raise ValueError("result.json must contain a JSON object.") |
| 104 | return answer |
| 105 | |
| 106 | |
| 107 | def ephemeris(answer, record): |
| 108 | star = answer.get("star") |
| 109 | numbers = [answer.get(key) for key in ("period_days", "epoch_bkjd", "duration_hours")] |
| 110 | if not all(type(value) in (int, float) and math.isfinite(value) for value in numbers): |
| 111 | raise ValueError("period_days, epoch_bkjd and duration_hours must be finite numbers.") |
| 112 | period, epoch, duration = numbers |
| 113 | if not (0.5 <= period <= 30 and 0.75 <= duration <= min(8, period * 4.32)): |
| 114 | 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.") |
| 115 | if not record["train"]["min_bkjd"] <= epoch <= record["train"]["max_bkjd"]: |
| 116 | raise ValueError("Use an equivalent reference epoch within the training time range, in BKJD.") |
| 117 | return star, period, epoch, duration |
| 118 | |
| 119 | |
| 120 | def signal(rows, star, period, epoch, duration): |
| 121 | primary = measure(rows, period, epoch, duration) |
| 122 | coverage = primary["events"] >= 8 |
| 123 | score = int(coverage and primary["depth_ppm"] >= 150 and primary["snr"] >= 5) |
| 124 | secondary = None |
| 125 | outcome = "not_reproduced" if coverage else "insufficient" |
| 126 | verdict = "no clear recurring dip in the later observations" if coverage else "not enough covered events in the later observations" |
| 127 | uneven = odd_even(dips(rows, period, epoch, duration)) if score else None |
| 128 | if uneven: |
| 129 | every, deeper, shallower = uneven |
| 130 | score = 0 |
| 131 | verdict = (f"odd and even events differ ({round(deeper)} vs {round(shallower)} ppm): " |
| 132 | "the period looks like half the true one" if every == 2 else |
| 133 | f"events in every third orbit differ ({round(deeper)} vs {round(shallower)} ppm): " |
| 134 | "the period looks like a third of the true one") |
| 135 | elif score: |
| 136 | # A companion eclipse may land away from phase one-half on an eccentric orbit. With m times the true period |
| 137 | # the same dip returns at phase k/m; an even grid finer than half the window finds a dip anywhere else. |
| 138 | width = duration / (24 * period) |
| 139 | gap = max(0.18, 2.5 * width) |
| 140 | steps = math.floor(2 / width) + 1 |
| 141 | phases = {k / m for m in range(2, 6) for k in range(1, m)} | {k / steps for k in range(1, steps)} |
| 142 | eclipses = ({"phase": round(phase, 4), **measure(rows, period, epoch, duration, phase)} |
| 143 | for phase in sorted(phases) if gap <= phase <= 1 - gap) |
| 144 | secondary = max((event for event in eclipses if event["events"] >= 8 and event["snr"] >= 5), |
| 145 | key=lambda event: event["depth_ppm"], default=None) |
| 146 | if secondary and secondary["depth_ppm"] >= 0.2 * primary["depth_ppm"]: |
| 147 | score = 0 |
| 148 | verdict = "a second dip is consistent with eclipsing stars" |
| 149 | else: |
| 150 | outcome = "reproduced" |
| 151 | verdict = "recurring dip reproduced in the later observations" |
| 152 | return {"score": score, "subtasks": {star: score}, "outcome": outcome, "primary": primary, |
| 153 | "folded_ppm": folded(rows, period, epoch, duration), "secondary": secondary, "verdict": verdict} |
| 154 | |
| 155 | |
| 156 | def verify_archival(answer, archive): |
| 157 | star = archive["star"] |
| 158 | if answer.get("star") != star: |
| 159 | raise ValueError("Use the Kepler catalog number assigned on the activity page.") |
| 160 | early, later = archive["early"], archive["later"] |
| 161 | expected = observation(early) |
| 162 | if answer.get("observation") != expected: |
| 163 | raise ValueError("The submitted summary does not match the archival early observations.") |
| 164 | recorded = {"score": 1, "subtasks": {star: 1}, "outcome": "observed", |
| 165 | "early_observation": expected, "later_observation": observation(later), |
| 166 | "source": archive["source"], "source_sha256": archive["source_sha256"], |
| 167 | "ra": archive["ra"], "dec": archive["dec"], "verdict": "archival observation verified"} |
| 168 | if "period_days" in answer: |
| 169 | predicted = signal(later, *ephemeris(answer, {"train": {"min_bkjd": early[0][0], "max_bkjd": early[-1][0]}})) |
| 170 | recorded["signal"] = predicted |
| 171 | recorded["verdict"] += f"; {predicted['verdict']}" |
| 172 | return recorded |
| 173 | |
| 174 | |
| 175 | def verify(route): |
| 176 | input_root = os.environ.get("SS_INPUT") |
| 177 | if input_root and route.resolve() != Path(input_root).resolve() / route.relative_to(input_root): |
| 178 | raise ValueError("The route directory must be in the submitted tree and cannot be a symlink.") |
| 179 | answer = inspect(route) |
| 180 | # The site attaches this file to the approved code archive, outside the submitted tree. |
| 181 | bundle = ROOT / ".shoal" / "kepler-archive.json.gz" |
| 182 | if bundle.is_file(): |
| 183 | with gzip.open(bundle, "rt") as handle: |
| 184 | return verify_archival(answer, json.load(handle)) |
| 185 | targets = json.loads((ROOT / "observations/sources.json").read_text()) |
| 186 | star = answer.get("star") |
| 187 | if not isinstance(star, str) or star not in targets: |
| 188 | raise ValueError("Choose a star from stars.json or select an archive target in the activity.") |
| 189 | record = targets[star] |
| 190 | return signal(lightcurve(record["holdout"]["file"]), *ephemeris(answer, record)) |
| 191 | |
| 192 | |
| 193 | def main(): |
| 194 | parser = argparse.ArgumentParser(description=__doc__) |
| 195 | parser.add_argument("route", type=Path) |
| 196 | parser.add_argument("--metrics", type=Path) |
| 197 | args = parser.parse_args() |
| 198 | try: |
| 199 | evidence = verify(args.route) |
| 200 | except (OSError, OverflowError, SyntaxError, ValueError) as error: |
| 201 | parser.exit(1, f"Verification failed: {error}\n") |
| 202 | if args.metrics: |
| 203 | args.metrics.write_text(json.dumps(evidence) + "\n") |
| 204 | star = next(iter(evidence["subtasks"])) |
| 205 | if evidence["outcome"] == "observed": |
| 206 | print(f"{star}: {evidence['verdict']} ({evidence['early_observation']['samples']} early and " |
| 207 | f"{evidence['later_observation']['samples']} later measurements).") |
| 208 | else: |
| 209 | primary = evidence["primary"] |
| 210 | print(f"{star}: {evidence['verdict']} ({primary['events']} events, " |
| 211 | f"{primary['depth_ppm']:g} ppm, S/N {primary['snr']:g}).") |
| 212 | |
| 213 | |
| 214 | if __name__ == "__main__": |
| 215 | main() |