Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
217 changes: 217 additions & 0 deletions backend/scripts/sim_injection_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
"""How many injections does a 3-parameter completeness curve need? (V36, A22.10.2, R-29)

uv run python -m scripts.sim_injection_count # prints the table in A22.14

A true curve is chosen, ``N`` found-or-missed injections are drawn from it, the curve is fitted by
binomial maximum likelihood and bootstrapped, and this is repeated. The curve is

completeness = plateau / (1 + exp(-(log10(S/N) - x50) / width))

A band width is the 84th minus the 16th percentile of the bootstrap curves, in completeness units,
read at the true midpoint (half the plateau) and where the true completeness is 0.90.

Assumptions (not fixed by the spec):

- The true curve is the A22.10.4 example, plus a steeper, a shallower and a higher-plateau one.
- 80% of injections are uniform within 3 widths of the midpoint (the rise) and 20% uniform from
3 to 6 widths above it (the plateau).

Limit: the injections are placed using the true midpoint and width. A real calibration only has an
estimate of them, so its bands are likely wider than these.
"""

from __future__ import annotations

import argparse
from dataclasses import dataclass

import numpy as np
import numpy.typing as npt

Array = npt.NDArray[np.float64]

SEED = 36
COUNTS = (150, 200, 300, 500)
REPEATS = 200
BOOTSTRAPS = 1000
RISE_SHARE = 0.8
TARGET = 0.90

WIDTH_BOUNDS = (0.005, 2.0)
PLATEAU_BOUNDS = (0.01, 1.0)


@dataclass(frozen=True)
class Curve:
name: str
x50: float
width: float
plateau: float


CURVES = (
Curve("spec example", 1.02, 0.11, 0.94),
Curve("steeper", 1.02, 0.06, 0.94),
Curve("shallower", 1.02, 0.20, 0.94),
Curve("higher plateau", 1.02, 0.11, 0.99),
)


def completeness(x: Array, theta: Array) -> Array:
"""Curve values at ``x`` (N,) for parameters ``theta`` (B, 3) = x50, width, plateau."""
x50, width, plateau = theta[:, 0:1], theta[:, 1:2], theta[:, 2:3]
z = np.clip((x - x50) / width, -50.0, 50.0)
out: Array = plateau / (1.0 + np.exp(-z))
return out


def draw(curve: Curve, n: int, rng: np.random.Generator) -> tuple[Array, Array]:
"""``n`` injections: their log10 S/N and whether each was recovered (1.0) or not (0.0)."""
n_rise = round(RISE_SHARE * n)
lo, mid, hi = (curve.x50 + k * curve.width for k in (-3.0, 3.0, 6.0))
x = np.concatenate([rng.uniform(lo, mid, n_rise), rng.uniform(mid, hi, n - n_rise)])
truth = np.array([[curve.x50, curve.width, curve.plateau]])
y = (rng.random(n) < completeness(x, truth)[0]).astype(np.float64)
return x, y


def _log_likelihood(x: Array, y: Array, w: Array, theta: Array) -> Array:
p = np.clip(completeness(x, theta), 1e-10, 1.0 - 1e-10)
out: Array = np.sum(w * (y * np.log(p) + (1.0 - y) * np.log1p(-p)), axis=1)
return out


def _start(x: Array, y: Array, w: Array) -> Array:
"""Best point of a coarse grid for each row of weights; it never looks at the true curve."""
# Fixed starting widths spanning the true widths in CURVES (0.06 to 0.20); the fit itself may
# move anywhere inside WIDTH_BOUNDS, which is far wider on purpose.
grid = np.array(
[
(x50, width, plateau)
for x50 in np.quantile(x, np.linspace(0.05, 0.95, 13))
for width in (0.03, 0.06, 0.12, 0.25)
for plateau in (0.7, 0.85, 0.95, 0.995)
]
)
p = np.clip(completeness(x, grid), 1e-10, 1.0 - 1e-10)
scores = (w * y) @ np.log(p).T + (w * (1.0 - y)) @ np.log1p(-p).T
out: Array = grid[np.argmax(scores, axis=1)]
return out


def fit(x: Array, y: Array, w: Array, iterations: int = 60) -> Array:
"""Binomial maximum likelihood, one fit per row of weights ``w`` (B, N). Returns (B, 3).

Damped Fisher scoring inside the bounds, all rows at once; a row stops once a step no longer
moves it.
"""
lower = np.array([x.min() - 0.5, WIDTH_BOUNDS[0], PLATEAU_BOUNDS[0]])
upper = np.array([x.max() + 0.5, WIDTH_BOUNDS[1], PLATEAU_BOUNDS[1]])
theta = np.clip(_start(x, y, w), lower, upper)
score = _log_likelihood(x, y, w, theta)
damping = np.full(len(w), 1e-3)
rows = np.arange(len(w))
for _ in range(iterations):
at, wr = theta[rows], w[rows]
z = np.clip((x - at[:, 0:1]) / at[:, 1:2], -50.0, 50.0)
s = 1.0 / (1.0 + np.exp(-z))
p = np.clip(at[:, 2:3] * s, 1e-10, 1.0 - 1e-10)
slope = at[:, 2:3] * s * (1.0 - s) / at[:, 1:2]
jac = np.stack([-slope, -slope * z, s], axis=2)
variance = p * (1.0 - p)
grad = np.einsum("bn,bnk->bk", wr * (y - p) / variance, jac)
info = np.matmul((jac * (wr / variance)[:, :, None]).transpose(0, 2, 1), jac)
# A parameter sitting on a bound and pushing outwards is held there for this step.
held = ((at <= lower) & (grad < 0)) | ((at >= upper) & (grad > 0))
grad = np.where(held, 0.0, grad)
free = ~held
info = info * (free[:, :, None] & free[:, None, :])
diagonal = np.einsum("bkk->bk", info)
ridge = damping[rows, None] * (diagonal + 1.0) + held
step = np.linalg.solve(info + ridge[:, :, None] * np.eye(3), grad[:, :, None])[:, :, 0]
trial = np.clip(at + step, lower, upper)
trial_score = _log_likelihood(x, y, wr, trial)
better = trial_score > score[rows]
theta[rows] = np.where(better[:, None], trial, at)
score[rows] = np.where(better, trial_score, score[rows])
damping[rows] = np.clip(
np.where(better, damping[rows] / 3.0, damping[rows] * 5.0), 1e-9, 1e9
)
rows = rows[np.abs(trial - at).max(axis=1) > 1e-5]
if rows.size == 0:
break
return theta


@dataclass(frozen=True)
class Result:
midpoint_median: float
midpoint_p90: float
midpoint_coverage: float
target_median: float
target_p90: float
target_coverage: float


def simulate(curve: Curve, n: int, repeats: int, bootstraps: int, seed: int = SEED) -> Result:
"""Band widths over ``repeats`` independent sets of ``n`` injections.

``coverage`` is the share of repeats whose 16 to 84% band holds the true value (nominally 0.68).
"""
share = TARGET / curve.plateau
x_target = curve.x50 + curve.width * np.log(share / (1.0 - share))
at = np.array([curve.x50, x_target])
truth = np.array([curve.plateau / 2.0, TARGET])
widths = np.empty((repeats, 2))
holds = np.empty((repeats, 2))
key = [seed, *(round(v * 1000) for v in (curve.x50, curve.width, curve.plateau)), n]
for r in range(repeats):
rng = np.random.default_rng([*key, r])
x, y = draw(curve, n, rng)
# Resampling the injections with replacement, written as how often each one is picked.
w = rng.multinomial(n, np.full(n, 1.0 / n), size=bootstraps).astype(np.float64)
lo, hi = np.quantile(completeness(at, fit(x, y, w)), [0.16, 0.84], axis=0)
widths[r] = hi - lo
holds[r] = (lo <= truth) & (truth <= hi)
median = np.median(widths, axis=0)
p90 = np.quantile(widths, 0.9, axis=0)
coverage = holds.mean(axis=0)
return Result(
float(median[0]),
float(p90[0]),
float(coverage[0]),
float(median[1]),
float(p90[1]),
float(coverage[1]),
)


def table(repeats: int = REPEATS, bootstraps: int = BOOTSTRAPS) -> str:
lines = [
"| True curve (x50, width, plateau) | Injections | Band at midpoint: median / "
"90th percentile | Holds truth | Band at 0.90: median / 90th percentile | Holds truth |",
"|---|---|---|---|---|---|",
]
for curve in CURVES:
for n in COUNTS:
res = simulate(curve, n, repeats, bootstraps)
lines.append(
f"| {curve.name} ({curve.x50}, {curve.width}, {curve.plateau}) | {n} "
f"| {res.midpoint_median:.3f} / {res.midpoint_p90:.3f} "
f"| {res.midpoint_coverage:.2f} "
f"| {res.target_median:.3f} / {res.target_p90:.3f} "
f"| {res.target_coverage:.2f} |"
)
return "\n".join(lines)


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0] if __doc__ else None)
parser.add_argument("--repeats", type=int, default=REPEATS)
parser.add_argument("--bootstraps", type=int, default=BOOTSTRAPS)
args = parser.parse_args()
print(table(args.repeats, args.bootstraps))


if __name__ == "__main__":
main()
39 changes: 39 additions & 0 deletions backend/tests/test_sim_injection_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""The V36 injection-count simulation (A22.10.2): its fit and its determinism."""

import numpy as np
import pytest

from scripts import sim_injection_count
from scripts.sim_injection_count import CURVES, Curve, draw, fit, simulate, table


@pytest.mark.parametrize("curve", CURVES, ids=lambda c: c.name)
def test_fit_recovers_the_true_curve_on_a_large_sample(curve: Curve) -> None:
x, y = draw(curve, 100_000, np.random.default_rng(1))
x50, width, plateau = fit(x, y, np.ones((1, len(x))))[0]
assert x50 == pytest.approx(curve.x50, abs=0.005)
assert width == pytest.approx(curve.width, rel=0.05)
assert plateau == pytest.approx(curve.plateau, abs=0.005)


def test_same_seed_gives_the_same_result() -> None:
first = simulate(CURVES[0], 150, repeats=3, bootstraps=50)
assert first == simulate(CURVES[0], 150, repeats=3, bootstraps=50)
assert first != simulate(CURVES[0], 150, repeats=3, bootstraps=50, seed=1)


def test_more_injections_give_a_narrower_band() -> None:
few = simulate(CURVES[0], 150, repeats=20, bootstraps=200)
middle = simulate(CURVES[0], 300, repeats=20, bootstraps=200)
many = simulate(CURVES[0], 1500, repeats=20, bootstraps=200)
assert many.midpoint_median < middle.midpoint_median < few.midpoint_median
assert many.target_median < middle.target_median < few.target_median


def test_table_row_matches_the_golden_output(monkeypatch: pytest.MonkeyPatch) -> None:
"""Guards the A22.14 table: if this changes, regenerate the table in the doc too."""
monkeypatch.setattr(sim_injection_count, "CURVES", CURVES[:1])
monkeypatch.setattr(sim_injection_count, "COUNTS", (150,))
assert table(repeats=2, bootstraps=20).splitlines()[-1] == (
"| spec example (1.02, 0.11, 0.94) | 150 | 0.111 / 0.117 | 1.00 | 0.069 / 0.085 | 0.50 |"
)
30 changes: 28 additions & 2 deletions docs/architecture/discovery-hunts.md
Original file line number Diff line number Diff line change
Expand Up @@ -1035,7 +1035,7 @@ Synthetic objects are added to **real** data, the unchanged hunt is run, and the
- **Version 1 is capped (R-22).** 3 to 4 expected-S/N bins and one second-axis bin per hunt where the physics allows, on the shipped reference fields only, about 1,000 injections per field per hunt; the cost of each table (machine hours, downloads) is recorded in it. Finer grids come with later versions.
- **On the user's own patch (R-5, release 2 per R-22).** `POST .../inject` runs the same injection on the run's own data and writes a calibration table tied to the run. The plan shows its time and download before it starts. Every planted object carries A16.5's **Injected** badge wherever it is drawn (R-21) and never enters the run's rows. The bundle then carries the patch's own completeness, which is what a paper needs.

- **A fitted curve, not bins (R-29).** Completeness is fitted as a monotone curve in log expected S/N (a logistic, or the gamma CDF Kepler used in MES (Burke & Catanzarite 2017, KSCI-19111-002; Christiansen et al. 2020, [arXiv:2010.04796](https://arxiv.org/abs/2010.04796); the functional form **[verify]**)) by binomial maximum likelihood, with a bootstrap band. The 3 to 4 bins of R-22 stay as a goodness-of-fit check, drawn as points. Injections are concentrated where the curve rises, not spread evenly. Point intervals: Wilson or the equal-tailed Jeffreys interval for n ≤ 40, with Jeffreys's boundary modification at k = 0 and k = n (L(0) = 0, U(n) = 1, the other limit kept at α/2; check §4.1 before implementing); Wilson, Jeffreys or Agresti-Coull above 40. Clopper-Pearson only where guaranteed minimum coverage is required, since it is otherwise "wastefully conservative" ([Brown, Cai & DasGupta 2001](https://doi.org/10.1214/ss/1009213286), §4; corrected in Atish's third review). The project's 200 per bin is a precision choice, not a validity floor. A 3-parameter curve needing about 150 to 300 injections in the transition is an estimate to confirm by a small simulation in HN-4.
- **A fitted curve, not bins (R-29).** Completeness is fitted as a monotone curve in log expected S/N (a logistic, or the gamma CDF Kepler used in MES (Burke & Catanzarite 2017, KSCI-19111-002; Christiansen et al. 2020, [arXiv:2010.04796](https://arxiv.org/abs/2010.04796); the functional form **[verify]**)) by binomial maximum likelihood, with a bootstrap band. The 3 to 4 bins of R-22 stay as a goodness-of-fit check, drawn as points. Injections are concentrated where the curve rises, not spread evenly. Point intervals: Wilson or the equal-tailed Jeffreys interval for n ≤ 40, with Jeffreys's boundary modification at k = 0 and k = n (L(0) = 0, U(n) = 1, the other limit kept at α/2; check §4.1 before implementing); Wilson, Jeffreys or Agresti-Coull above 40. Clopper-Pearson only where guaranteed minimum coverage is required, since it is otherwise "wastefully conservative" ([Brown, Cai & DasGupta 2001](https://doi.org/10.1214/ss/1009213286), §4; corrected in Atish's third review). The project's 200 per bin is a precision choice, not a validity floor. A 3-parameter curve needs about 150 to 300 injections per curve (the total, 80% of them in the rise), simulated in [A22.14](#a2214-open-items-and-items-to-verify) V36.
- **Stale gates show (R-34).** A gate re-runs whenever an upstream input changes (data release, detrending, thresholds, control seeds), not only per version; a hash of those inputs is part of its label, so a stale gate is visible on the card. While its gate is stale a Validated hunt shows as **Experimental, "gate out of date"** until the gate re-runs (R-53). Kepler re-ran injection on its final pipeline version for DR25.

#### A22.10.3 Purity
Expand Down Expand Up @@ -1283,9 +1283,35 @@ The first draft's research (17 Nov 2026) was at the level of search results and
| V33 | THOR, ZTF, Pan-STARRS and NEOWISE linking criteria, read in full | Open: blocks HN-12 |
| V34 | SPHEREx end-to-end astrometric accuracy: IRSA Explanatory Supplement section 4.2.2 and arXiv:2511.15823 in full | Open: blocks HN-5's error model |
| V35 | The licences of the chosen orbit tools and their dependencies (checked 19 Nov: see R-37); the project licence is D-41 | Open: blocks any pin in HN-12 |
| V36 | A simulation confirming 150 to 300 injections for a 3-parameter completeness curve | Open: blocks HN-4's table format |
| V36 | A simulation confirming 150 to 300 injections for a 3-parameter completeness curve | Simulated (26 Nov 2026, #202; table below). **Proposed: 300 injections per curve.** No target band width is set, so the choice waits for review and still blocks HN-4's table format |
| V37 | The sources marked [verify] in R-29 to R-49 | Partly resolved (Atish's third review, 20 Nov 2026): RO-Crate (Data Science 5(2):97–138), the Software Citation Principles (PeerJ CS 2:e86), Gross & Vitells (EPJC 70, 525), Benjamini & Hochberg (JRSS-B 57, 289), VanderPlas 2018 (ApJS 236, 16), ASSIST's licence (GPL-3), the IVOA ProvenanceDM v1.0 Recommendation (11 Apr 2020) and TESS's 200 s frames are confirmed. Still open: the gamma-CDF form in KSCI-19111-002 §3, Kuchner et al. 2016 on dust (full text), archive limits (R-42), ASCL eligibility (R-40). Blocks registering R-29 to R-49 (HN-0) |

**V36 results (26 Nov 2026, #202).** Reproduced by `uv run python -m scripts.sim_injection_count` in `backend/` (fixed seed). Each row is 200 independent sets of injections, each fitted by binomial maximum likelihood and bootstrapped 1,000 times. A **band** is the width of the 16th to 84th percentile of the fitted curves, in completeness units, read at the true midpoint (half the plateau) and where the true completeness is 0.90. **Holds truth** is the share of sets whose band contains the true value (nominally 0.68).

| True curve (x50, width, plateau) | Injections | Band at midpoint: median / 90th percentile | Holds truth | Band at 0.90: median / 90th percentile | Holds truth |
|---|---|---|---|---|---|
| spec example (1.02, 0.11, 0.94) | 150 | 0.136 / 0.179 | 0.70 | 0.079 / 0.100 | 0.64 |
| spec example (1.02, 0.11, 0.94) | 200 | 0.112 / 0.146 | 0.73 | 0.067 / 0.081 | 0.65 |
| spec example (1.02, 0.11, 0.94) | 300 | 0.091 / 0.111 | 0.65 | 0.054 / 0.064 | 0.70 |
| spec example (1.02, 0.11, 0.94) | 500 | 0.069 / 0.082 | 0.66 | 0.043 / 0.049 | 0.64 |
| steeper (1.02, 0.06, 0.94) | 150 | 0.132 / 0.177 | 0.67 | 0.078 / 0.098 | 0.69 |
| steeper (1.02, 0.06, 0.94) | 200 | 0.112 / 0.143 | 0.66 | 0.066 / 0.080 | 0.66 |
| steeper (1.02, 0.06, 0.94) | 300 | 0.091 / 0.111 | 0.72 | 0.054 / 0.063 | 0.69 |
| steeper (1.02, 0.06, 0.94) | 500 | 0.070 / 0.081 | 0.63 | 0.042 / 0.048 | 0.62 |
| shallower (1.02, 0.2, 0.94) | 150 | 0.133 / 0.179 | 0.71 | 0.081 / 0.099 | 0.65 |
| shallower (1.02, 0.2, 0.94) | 200 | 0.112 / 0.142 | 0.68 | 0.068 / 0.082 | 0.67 |
| shallower (1.02, 0.2, 0.94) | 300 | 0.090 / 0.116 | 0.69 | 0.054 / 0.065 | 0.68 |
| shallower (1.02, 0.2, 0.94) | 500 | 0.069 / 0.079 | 0.67 | 0.041 / 0.047 | 0.63 |
| higher plateau (1.02, 0.11, 0.99) | 150 | 0.129 / 0.167 | 0.62 | 0.068 / 0.085 | 0.62 |
| higher plateau (1.02, 0.11, 0.99) | 200 | 0.108 / 0.129 | 0.69 | 0.060 / 0.073 | 0.66 |
| higher plateau (1.02, 0.11, 0.99) | 300 | 0.088 / 0.102 | 0.70 | 0.049 / 0.057 | 0.69 |
| higher plateau (1.02, 0.11, 0.99) | 500 | 0.067 / 0.075 | 0.66 | 0.038 / 0.044 | 0.66 |

- **150 to 300 is a usable range; the upper end is Proposed.** At 300 the median band is 0.088 to 0.091 wide at the midpoint and 0.049 to 0.054 at 0.90, and nine sets in ten stay within 0.116 at the midpoint. At 150 the medians are 0.129 to 0.136 and 0.068 to 0.081, and the 90th percentile reaches 0.179. At 500 the medians are 0.067 to 0.070 and 0.038 to 0.043.
- **N is the total per curve:** 80% uniform within 3 widths of the midpoint, 20% uniform from 3 to 6 widths above it.
- **Assumed, for review:** "90% completeness" means a completeness of 0.90, not 90% of the plateau; the true curves are the A22.10.4 example (x50 and width in log10 of expected S/N) and three variants of it.
- **Limit:** injections are placed using the true midpoint and width. A real calibration only has estimates of them, so its bands are likely wider.

**Which [verify] item blocks which ticket** (none blocks approval of this proposal):

| Item | Blocks |
Expand Down
Loading