orbitsift 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. orbitsift/__init__.py +2 -0
  2. orbitsift/_native.py +13 -0
  3. orbitsift/ades.py +166 -0
  4. orbitsift/archives/__init__.py +244 -0
  5. orbitsift/archives/cadc.py +97 -0
  6. orbitsift/archives/decam_geom.json +1 -0
  7. orbitsift/archives/eso.py +213 -0
  8. orbitsift/archives/hsc_geom.json +2378 -0
  9. orbitsift/archives/ing.py +70 -0
  10. orbitsift/archives/listing.py +22 -0
  11. orbitsift/archives/noirlab.py +302 -0
  12. orbitsift/archives/ps1.py +59 -0
  13. orbitsift/archives/sdss.py +52 -0
  14. orbitsift/archives/smoka.py +369 -0
  15. orbitsift/blind.py +558 -0
  16. orbitsift/catalog.py +328 -0
  17. orbitsift/cli.py +2200 -0
  18. orbitsift/config.py +85 -0
  19. orbitsift/confirm.py +1030 -0
  20. orbitsift/data/nsc_dr2_k4m_ksb.csv.gz +0 -0
  21. orbitsift/dense.py +788 -0
  22. orbitsift/dynamics.py +235 -0
  23. orbitsift/expindex.py +456 -0
  24. orbitsift/extend.py +690 -0
  25. orbitsift/external.py +204 -0
  26. orbitsift/extract.py +148 -0
  27. orbitsift/growth.py +224 -0
  28. orbitsift/images.py +676 -0
  29. orbitsift/itf.py +154 -0
  30. orbitsift/known.py +716 -0
  31. orbitsift/link.py +509 -0
  32. orbitsift/lov.py +642 -0
  33. orbitsift/mcp_server.py +164 -0
  34. orbitsift/multiyear.py +409 -0
  35. orbitsift/net.py +265 -0
  36. orbitsift/orbit.py +614 -0
  37. orbitsift/plugins.py +97 -0
  38. orbitsift/precovery.py +187 -0
  39. orbitsift/presets/a2.json +85 -0
  40. orbitsift/presets/confirm_v1.json +190 -0
  41. orbitsift/presets/confirm_v2.json +236 -0
  42. orbitsift/presets/lostrec.json +74 -0
  43. orbitsift/recover.py +377 -0
  44. orbitsift/rubin.py +328 -0
  45. orbitsift/survey.py +268 -0
  46. orbitsift/tiles.py +58 -0
  47. orbitsift/unused.py +103 -0
  48. orbitsift/vet.py +304 -0
  49. orbitsift/workflow/__init__.py +5 -0
  50. orbitsift/workflow/models.py +103 -0
  51. orbitsift/workflow/sqlite.py +189 -0
  52. orbitsift-0.1.0.dist-info/METADATA +443 -0
  53. orbitsift-0.1.0.dist-info/RECORD +56 -0
  54. orbitsift-0.1.0.dist-info/WHEEL +4 -0
  55. orbitsift-0.1.0.dist-info/entry_points.txt +3 -0
  56. orbitsift-0.1.0.dist-info/licenses/LICENSE +28 -0
orbitsift/blind.py ADDED
@@ -0,0 +1,558 @@
1
+ """Blind search for moving sources on registered frames, sealed before a prediction is opened (``orbitsift blindcheck``).
2
+
3
+ A field is a set of frames on one pixel grid with one WCS: a FITS cube (primary HDU n x ny x nx, a table HDU with the
4
+ mid-exposure UTC MJD in ``MJD_UTC``/``MJD_MID``/``MJD`` and optionally ``FILTER``), or a directory of 2-D FITS frames
5
+ (``MJD-MID``, else ``MJD-OBS``/``DATE-OBS`` + ``EXPTIME``/2). Steps, for every field:
6
+
7
+ 1. ``prepare``: background and noise maps (``extract.background_map``), frames in sigma units; difference frames (each
8
+ minus the scaled median of the other frames of its filter: the static sky goes); a mask of static sources; the PSF
9
+ width of each frame from the static sources (``images.gauss_fit``).
10
+ 2. Three searches: ``stack_search`` (median shift-and-stack of the difference frames on a grid of total displacements,
11
+ every direction, faint movers), ``link_search`` (single-frame detections, ``extract.detect``, that are not static,
12
+ linked along straight lines: bright and fast movers), ``slow_search`` (a straight-line fit to every source of the
13
+ median frame: slow movers that look static to the others).
14
+ 3. ``measure``: each candidate's rate refined on stacked stamps, a fixed-width Gaussian fit in every frame, a
15
+ straight-line fit with 3-sigma rejection, the WCS position of every frame, the position at the mean time of the
16
+ used frames with its uncertainty, and the stack S/N of the first and second half of the frames.
17
+ 4. ``inject``: synthetic movers added to the difference frames at a few peak S/N per frame, found again by the stack
18
+ at their rate: the completeness of the search.
19
+ 5. ``seal``: the notes (tracks, weak candidates, completeness, parameters, the input files' sha256) are written with
20
+ their own sha256 BEFORE any prediction is read. ``compare`` refuses notes that changed after sealing and gives the
21
+ measured-minus-predicted offsets of every track against an ephemeris file (``utc`` or ``mjd``, ``ra``, ``dec``).
22
+
23
+ Nothing here touches the network. Pixel positions are 0-based; rates are on the sky ["/h], RA rate times cos(Dec).
24
+ """
25
+ import datetime as _dt
26
+ import hashlib
27
+ import json
28
+ import math
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+ from scipy import ndimage as nd
33
+
34
+ from . import __version__, extract, images
35
+
36
+ PAR = dict(bright=50.0, mesh=32, vmin=1.0, vmax=50.0, step_px=2.0, snr=5.0, link_vmax=150.0, link_nsig=4.5, min_frames=4,
37
+ slow_sig=5.0, inj_levels=(1.0, 1.5, 2.0, 3.0), inj_n=10, seed=1)
38
+
39
+
40
+ # ---------------------------------------------------------------- input
41
+ def _sha(path):
42
+ h = hashlib.sha256()
43
+ with open(path, "rb") as f:
44
+ for b in iter(lambda: f.read(1 << 20), b""):
45
+ h.update(b)
46
+ return h.hexdigest()
47
+
48
+
49
+ def _mid(H):
50
+ """Mid-exposure UTC MJD of a frame header."""
51
+ from astropy.time import Time
52
+ if "MJD-MID" in H:
53
+ return float(H["MJD-MID"])
54
+ t0 = float(H["MJD-OBS"]) if "MJD-OBS" in H else float(Time(str(H["DATE-OBS"]), scale="utc").mjd)
55
+ return t0 + float(H.get("EXPTIME", 0.0)) / 2 / 86400
56
+
57
+
58
+ def load_field(path):
59
+ """A FITS cube with a time table, or a directory of 2-D frames -> dict(name, im (n, ny, nx), mjd, filt, wcs, files)."""
60
+ from astropy.io import fits
61
+ from astropy.wcs import WCS
62
+ p = Path(path)
63
+ if p.is_dir():
64
+ files = sorted(f for f in p.iterdir() if f.name.endswith((".fits", ".fit", ".fits.fz", ".fits.gz")))
65
+ ims, mjd, filt, wcs = [], [], [], None
66
+ for f in files:
67
+ with fits.open(f) as h:
68
+ hdu = next(x for x in h if x.data is not None and x.data.ndim == 2)
69
+ ims.append(hdu.data.astype(float))
70
+ mjd.append(_mid(hdu.header))
71
+ filt.append(str(hdu.header.get("FILTER", "")).strip())
72
+ wcs = wcs or WCS(hdu.header).celestial
73
+ if len({i.shape for i in ims}) != 1:
74
+ raise ValueError(f"{path}: frames of different sizes (they must be registered on one grid)")
75
+ im = np.array(ims)
76
+ else:
77
+ files = [p]
78
+ with fits.open(p) as h:
79
+ im = h[0].data.astype(float)
80
+ if im.ndim != 3:
81
+ raise ValueError(f"{path}: the primary HDU is not a cube (n, ny, nx); give a directory of frames instead")
82
+ wcs = WCS(h[0].header).celestial
83
+ t = next(x for x in h[1:] if hasattr(x, "columns"))
84
+ col = next((c for c in ("MJD_UTC", "MJD_MID", "MJD") if c in t.columns.names), None)
85
+ if col is None:
86
+ raise ValueError(f"{path}: the table has no MJD_UTC / MJD_MID / MJD column (mid-exposure UTC)")
87
+ mjd = [float(x) for x in t.data[col]]
88
+ filt = [str(x).strip() for x in t.data["FILTER"]] if "FILTER" in t.columns.names else [""] * len(mjd)
89
+ o = np.argsort(mjd)
90
+ return dict(name=p.name.split(".")[0], im=im[o], mjd=np.asarray(mjd)[o], filt=[filt[k] for k in o], wcs=wcs,
91
+ files=[dict(path=str(f), sha256=_sha(f)) for f in files])
92
+
93
+
94
+ def jacobian(wcs, shape):
95
+ """2x2 arcsec per px at the centre: columns d(East, North)/dx and /dy."""
96
+ cy, cx = (shape[0] - 1) / 2, (shape[1] - 1) / 2
97
+ a = wcs.pixel_to_world_values([cx - .5, cx + .5, cx, cx], [cy, cy, cy - .5, cy + .5])
98
+ ra, de = np.asarray(a[0]), np.asarray(a[1])
99
+ cd = math.cos(math.radians(de.mean()))
100
+ dE = ((ra[[1, 3]] - ra[[0, 2]] + 180) % 360 - 180) * cd * 3600
101
+ return np.array([dE, (de[[1, 3]] - de[[0, 2]]) * 3600])
102
+
103
+
104
+ # ---------------------------------------------------------------- preparation
105
+ def prepare(F, par=PAR):
106
+ im = F["im"]
107
+ n = len(im)
108
+ bad = ~np.isfinite(im)
109
+ norm = np.zeros_like(im)
110
+ for k in range(n):
111
+ back, noise = extract.background_map(im[k], bad[k], par["mesh"])
112
+ norm[k] = np.where(bad[k], 0.0, (im[k] - back) / noise)
113
+ diff = np.zeros_like(norm)
114
+ filt = np.array(F["filt"])
115
+ for k in range(n):
116
+ same = [j for j in np.nonzero(filt == filt[k])[0] if j != k]
117
+ ref = np.median(norm[same if len(same) >= 2 else [j for j in range(n) if j != k]], 0)
118
+ m = ref > 5
119
+ diff[k] = norm[k] - (np.sum(norm[k][m] * ref[m]) / np.sum(ref[m] ** 2) if m.any() else 1.0) * ref
120
+ med = nd.gaussian_filter(np.median(norm, 0), 1.0)
121
+ med /= 1.4826 * np.median(np.abs(med - np.median(med)))
122
+ t = (F["mjd"] - F["mjd"].mean()) * 24
123
+ J = jacobian(F["wcs"], im.shape[1:])
124
+ F.update(norm=norm, diff=diff, med=med, mask=nd.binary_dilation(med > 4, iterations=3), tc=t, J=J, Ji=np.linalg.inv(J),
125
+ bright=nd.binary_dilation(med > par["bright"], iterations=3),
126
+ ps=float(math.sqrt(abs(np.linalg.det(J)))), bad=bad)
127
+ F["psf"] = psf_sigmas(F)
128
+ return F
129
+
130
+
131
+ def psf_sigmas(F, default=1.5):
132
+ """Gaussian sigma [px] of each frame: median over the bright isolated static sources."""
133
+ med = F["med"]
134
+ pk = np.argwhere((med == nd.maximum_filter(med, 9)) & (med > 15))
135
+ out = []
136
+ for k, d in enumerate(F["norm"]):
137
+ s = []
138
+ for y, x in pk[:40]:
139
+ st, o = images.stamp(d, x, y, 7)
140
+ if st is None:
141
+ continue
142
+ try:
143
+ with np.errstate(invalid="ignore"):
144
+ p, _, _ = images.gauss_fit(st, x - o[0], y - o[1], 1.5, 1.0, free_s=True, R=6)
145
+ except Exception:
146
+ continue
147
+ if 0.5 < abs(p[3]) < 6 and abs(p[1] - (x - o[0])) < 2:
148
+ s.append(abs(p[3]))
149
+ out.append(float(np.median(s)) if s else default)
150
+ return out
151
+
152
+
153
+ def stack_input(F, diff=None, mask=True):
154
+ """Difference frames clipped, smoothed (sigma 1 px) and, for the search, with the static sources set to 0 (the
155
+ stamps of ``measure`` keep them: a slow mover sits on its own mask)."""
156
+ d = np.clip(F["diff"] if diff is None else diff, -5, 8)
157
+ d = np.array([nd.gaussian_filter(x, 1.0) for x in d])
158
+ if mask:
159
+ d[:, F["mask"]] = 0.0
160
+ return d
161
+
162
+
163
+ def rates(F, par=PAR):
164
+ """Grid of rates [px/h]: total displacements over the sequence in steps of ``step_px``, |rate| in [vmin, vmax]."""
165
+ L = np.ptp(F["tc"])
166
+ D = par["vmax"] / F["ps"] * L
167
+ g = np.arange(-math.floor(D / par["step_px"]), math.floor(D / par["step_px"]) + 1) * par["step_px"] / L
168
+ vx, vy = np.meshgrid(g, g)
169
+ v = np.c_[vx.ravel(), vy.ravel()]
170
+ sky = np.hypot(*(F["J"] @ v.T))
171
+ return v[(sky >= par["vmin"]) & (sky <= par["vmax"])]
172
+
173
+
174
+ def _stack(d, tc, vx, vy):
175
+ """Median of the frames rolled by the integer shifts of rate (vx, vy) [px/h]; valid core margin [px]."""
176
+ sx, sy = np.round(vx * tc).astype(int), np.round(vy * tc).astype(int)
177
+ st = np.median([np.roll(d[k], (-sy[k], -sx[k]), (0, 1)) for k in range(len(d))], 0)
178
+ return st, int(max(np.abs(sx).max(), np.abs(sy).max())) + 6
179
+
180
+
181
+ def stack_search(F, d, par=PAR, v=None, per_rate=3):
182
+ """Peaks of the shift-and-stack over the rate grid -> list of (snr, vx, vy, x, y) at the mean time."""
183
+ out = []
184
+ for vx, vy in (rates(F, par) if v is None else v):
185
+ st, m = _stack(d, F["tc"], vx, vy)
186
+ if 2 * m >= min(st.shape) - 10:
187
+ continue
188
+ core = st[m:-m, m:-m].copy()
189
+ sg = _noise(core)
190
+ if not sg > 0:
191
+ continue
192
+ for _ in range(per_rate):
193
+ y, x = np.unravel_index(np.argmax(core), core.shape)
194
+ if core[y, x] < par["snr"] * sg:
195
+ break
196
+ out.append((float(core[y, x] / sg), float(vx), float(vy), float(x + m), float(y + m)))
197
+ core[max(y - 4, 0):y + 5, max(x - 4, 0):x + 5] = -np.inf
198
+ return _dedupe(out)
199
+
200
+
201
+ def _noise(a):
202
+ """Robust sigma of a stack, without the pixels that are exactly 0 (masked static sources)."""
203
+ a = a[(a != 0) & np.isfinite(a)]
204
+ return 1.4826 * float(np.median(np.abs(a - np.median(a)))) if a.size > 20 else 0.0
205
+
206
+
207
+ def _dedupe(c, r=4.0):
208
+ keep = []
209
+ for p in sorted(c, key=lambda q: -q[0]):
210
+ if not any(abs(p[3] - q[3]) < r and abs(p[4] - q[4]) < r for q in keep):
211
+ keep.append(p)
212
+ return keep
213
+
214
+
215
+ def link_search(F, par=PAR, max_transients=600):
216
+ """Single-frame detections that are not static, linked along straight lines -> (n frames, vx, vy, x, y), note."""
217
+ n, tc = len(F["norm"]), F["tc"]
218
+ det = []
219
+ for k in range(n):
220
+ x, y, *_ = extract.detect(F["norm"][k], F["bad"][k], par["link_nsig"], par["mesh"])
221
+ det += [(k, a, b) for a, b in zip(x, y)]
222
+ det = np.array(det).reshape(-1, 3)
223
+ need = max(2, math.ceil(0.4 * (n - 1)))
224
+ static = np.array([len(set(det[(det[:, 0] != k) & (np.hypot(det[:, 1] - x, det[:, 2] - y) < 2), 0])) >= need
225
+ for k, x, y in det], bool) if len(det) else np.zeros(0, bool)
226
+ tr = det[~static]
227
+ if len(tr) > max_transients:
228
+ return [], f"{len(tr)} transient detections: linking skipped (more than {max_transients})"
229
+ out = []
230
+ for i in range(len(tr)):
231
+ for j in range(i + 1, len(tr)):
232
+ A, B = tr[i], tr[j]
233
+ if A[0] == B[0]:
234
+ continue
235
+ dt = tc[int(B[0])] - tc[int(A[0])]
236
+ vx, vy = (B[1] - A[1]) / dt, (B[2] - A[2]) / dt
237
+ sky = np.hypot(*(F["J"] @ [vx, vy]))
238
+ if not par["vmin"] <= sky <= par["link_vmax"]:
239
+ continue
240
+ px = A[1] + vx * (tc[tr[:, 0].astype(int)] - tc[int(A[0])])
241
+ py = A[2] + vy * (tc[tr[:, 0].astype(int)] - tc[int(A[0])])
242
+ sup = set(tr[np.hypot(tr[:, 1] - px, tr[:, 2] - py) < 1.5, 0].astype(int))
243
+ if len(sup) >= par["min_frames"]:
244
+ out.append((float(len(sup)), float(vx), float(vy), float(A[1] - vx * tc[int(A[0])]), float(A[2] - vy * tc[int(A[0])])))
245
+ return _dedupe(out), f"{len(det)} detections, {int(static.sum())} static, {len(tr)} transient"
246
+
247
+
248
+ def line(t, x, y, floor):
249
+ """Straight line x(t), y(t) with 3-sigma rejection (sigma: robust, at least ``floor`` px) -> (cx, cy, used)."""
250
+ use = np.ones(len(t), bool)
251
+ for _ in range(5):
252
+ A = np.c_[np.ones(use.sum()), t[use]]
253
+ cx, cy = np.linalg.lstsq(A, x[use], rcond=None)[0], np.linalg.lstsq(A, y[use], rcond=None)[0]
254
+ res = np.hypot(x - cx[0] - cx[1] * t, y - cy[0] - cy[1] * t)
255
+ new = res < 3 * max(1.4826 * np.median(res[use]), floor)
256
+ if new.sum() < 3 or (new == use).all():
257
+ break
258
+ use = new
259
+ return cx, cy, use
260
+
261
+
262
+ def frame_positions(F, k, x, y, h=6, tol=2.0, arr="norm"):
263
+ """Fixed-width Gaussian fit in frame k (``arr``: "norm" background removed, "diff" static sky removed) near (x, y)
264
+ -> (x, y, ex, ey, snr) or None (moved more than ``tol`` px)."""
265
+ st, o = images.stamp(F[arr][k], x, y, h)
266
+ if st is None:
267
+ return None
268
+ try:
269
+ with np.errstate(invalid="ignore"):
270
+ p, e, _ = images.gauss_fit(st, x - o[0], y - o[1], F["psf"][k], 1.0, R=4)
271
+ except Exception:
272
+ return None
273
+ if not (p[0] > 0 and math.hypot(p[1] - (x - o[0]), p[2] - (y - o[1])) < tol and np.isfinite(e).all()):
274
+ return None
275
+ return p[1] + o[0], p[2] + o[1], e[1], e[2], p[0] / e[0]
276
+
277
+
278
+ def slow_search(F, par=PAR):
279
+ """A straight-line fit to every source of the median frame -> (significance, vx, vy, x, y) of the moving ones."""
280
+ med, tc = F["med"], F["tc"]
281
+ out = []
282
+ for y, x in np.argwhere((med == nd.maximum_filter(med, 7)) & (med > 6)):
283
+ P = [(tc[k],) + q[:2] for k in range(len(tc)) if (q := frame_positions(F, k, x, y, h=8, tol=5.0, arr="norm")) is not None]
284
+ if len(P) < max(par["min_frames"], 0.75 * len(tc)):
285
+ continue
286
+ P = np.array(P)
287
+ cx, cy, use = line(P[:, 0], P[:, 1], P[:, 2], 0.05 / F["ps"])
288
+ P = P[use]
289
+ if len(P) < max(par["min_frames"], 0.75 * len(tc)):
290
+ continue
291
+ rms = math.hypot(np.std(P[:, 1] - cx[0] - cx[1] * P[:, 0]), np.std(P[:, 2] - cy[0] - cy[1] * P[:, 0]))
292
+ sv = rms / math.sqrt(len(P)) / max(np.std(P[:, 0]), 1e-9)
293
+ v = math.hypot(cx[1], cy[1])
294
+ if sv > 0 and v / sv >= par["slow_sig"] and np.hypot(*(F["J"] @ [cx[1], cy[1]])) >= par["vmin"] / 2:
295
+ out.append((float(v / sv), float(cx[1]), float(cy[1]), float(cx[0]), float(cy[0])))
296
+ return _dedupe(out)
297
+
298
+
299
+ # ---------------------------------------------------------------- measurement
300
+ def _stamp_stack(d, tc, x, y, vx, vy, frames, h=12):
301
+ """Median of stamps centred on the moving position (sub-pixel shifts) -> S/N of the peak within 3 px of the centre."""
302
+ S = []
303
+ for k in frames:
304
+ px, py = x + vx * tc[k], y + vy * tc[k]
305
+ st, o = images.stamp(d[k], px, py, h + 1)
306
+ if st is not None:
307
+ S.append(nd.shift(st, (o[1] + h + 1 - py, o[0] + h + 1 - px), order=1)[1:-1, 1:-1])
308
+ if len(S) < 2:
309
+ return 0.0
310
+ st = np.median(S, 0)
311
+ yy, xx = np.mgrid[:st.shape[0], :st.shape[1]]
312
+ r = np.hypot(xx - h, yy - h)
313
+ sg = _noise(st[r > 5])
314
+ return float(st[r <= 3].max() / sg) if sg > 0 else 0.0
315
+
316
+
317
+ def _frames(F, x, y, vx, vy):
318
+ """Frames where a source (S/N >= 3) sits on the moving position -> {k: (x, y, ex, ey, snr)}: fitted on the frame
319
+ (background removed), else on the difference frame (a static source nearby pulled the first fit away). Never on
320
+ a bright static source (median frame above ``bright`` sigma: saturated cores and bleeds change from frame to frame)."""
321
+ P = {}
322
+ ny, nx = F["bright"].shape
323
+ for k, t in enumerate(F["tc"]):
324
+ px, py = x + vx * t, y + vy * t
325
+ if F["bright"][min(max(int(round(py)), 0), ny - 1), min(max(int(round(px)), 0), nx - 1)]:
326
+ continue
327
+ for arr in ("norm", "diff"):
328
+ q = frame_positions(F, k, px, py, arr=arr)
329
+ if q is not None and q[4] >= 3:
330
+ P[k] = q
331
+ break
332
+ return P
333
+
334
+
335
+ def need_frames(n, par=PAR):
336
+ """Frames a track must be measured on: two thirds of the sequence, at least ``min_frames``."""
337
+ return max(par["min_frames"], math.ceil(2 * n / 3))
338
+
339
+
340
+ def measure(F, d, c, par=PAR):
341
+ """A candidate (score, vx, vy, x, y) -> its track dict (status 'track' or 'weak'), or None when it is seen on fewer
342
+ than half the frames it needs. 'track': measured on ``need_frames`` frames, both halves of the frames stack to S/N 4,
343
+ median forced S/N 3 on the difference frames."""
344
+ tc, n = F["tc"], len(F["tc"])
345
+ _, vx, vy, x, y = c
346
+ need = need_frames(n, par)
347
+ if len(_frames(F, x, y, vx, vy)) < need / 2:
348
+ return None
349
+ L = max(np.ptp(tc), 1e-6)
350
+ for half, step in ((2, 1.0), (0.5, 0.5)): # rate refined on stamp stacks: 1 px, then 0.5 px
351
+ snr, vx, vy = max(((_stamp_stack(d, tc, x, y, vx + a / L, vy + b / L, range(n)), vx + a / L, vy + b / L)
352
+ for a in np.arange(-half, half + .01, step) for b in np.arange(-half, half + .01, step)),
353
+ key=lambda q: q[0])
354
+ P = _frames(F, x, y, vx, vy)
355
+ for _ in range(2): # the frames again along the fitted line
356
+ if len(P) < max(3, need / 2):
357
+ return None
358
+ ks = np.array(sorted(P))
359
+ X = np.array([P[k] for k in ks])
360
+ cx, cy, use = line(tc[ks], X[:, 0], X[:, 1], 0.15 / F["ps"])
361
+ Q = _frames(F, cx[0], cy[0], cx[1], cy[1])
362
+ if set(Q) <= set(P):
363
+ break
364
+ P = Q
365
+ wcs = F["wcs"]
366
+ rx, ry = X[:, 0] - (cx[0] + cx[1] * tc[ks]), X[:, 1] - (cy[0] + cy[1] * tc[ks])
367
+ rE, rN = F["J"] @ np.vstack([rx, ry])
368
+ tm = float(tc[ks[use]].mean())
369
+ ra0, de0 = (float(v) for v in wcs.pixel_to_world_values(cx[0] + cx[1] * tm, cy[0] + cy[1] * tm))
370
+ nu = int(use.sum())
371
+ rms_e, rms_n = (float(np.sqrt(np.sum(r[use] ** 2) / max(nu - 2, 1))) for r in (rE, rN))
372
+ vE, vN = F["J"] @ [cx[1], cy[1]]
373
+ half = [ks[use][:nu // 2], ks[use][nu // 2:]]
374
+ halves = [_stamp_stack(d, tc, cx[0], cy[0], cx[1], cy[1], h) for h in half]
375
+ mjd_m = float(F["mjd"].mean() + tm / 24)
376
+ frames = []
377
+ for j, k in enumerate(ks):
378
+ a, b = wcs.pixel_to_world_values(X[j, 0], X[j, 1])
379
+ frames.append(dict(k=int(k), utc=_utc(F["mjd"][k]), mjd=float(F["mjd"][k]), filt=F["filt"][k], x=float(X[j, 0]),
380
+ y=float(X[j, 1]), ra=float(a), dec=float(b), snr=float(X[j, 4]), resid_ra=float(rE[j]),
381
+ resid_dec=float(rN[j]), used=bool(use[j])))
382
+ dsnr = [] # forced S/N on the difference frames: a static
383
+ for j in np.nonzero(use)[0]: # streak (bleed trail, bad row) fits along any rate
384
+ st, o = images.stamp(F["diff"][ks[j]], X[j, 0], X[j, 1], 8) # but is gone once the static sky is removed
385
+ if st is not None:
386
+ f, e = images.psf_flux(st, X[j, 0] - o[0], X[j, 1] - o[1], F["psf"][ks[j]], 1.0)
387
+ dsnr.append(f / e)
388
+ diff_snr = float(np.median(dsnr)) if dsnr else 0.0
389
+ ok = nu >= need and min(halves) >= 4 and diff_snr >= 3
390
+ return dict(field=F["name"], status="track" if ok else "weak", utc_mean=_utc(mjd_m), mjd_mean=mjd_m, ra=ra0, dec=de0,
391
+ sigma_ra=rms_e / math.sqrt(nu), sigma_dec=rms_n / math.sqrt(nu), rate_ra=float(vE), rate_dec=float(vN),
392
+ rate=float(math.hypot(vE, vN)), pa=float(math.degrees(math.atan2(vE, vN)) % 360), rms_ra=rms_e,
393
+ rms_dec=rms_n, n_used=nu, n_frames=n, stack_snr=snr, halves_snr=halves, diff_snr=diff_snr,
394
+ x_mid=float(cx[0] + cx[1] * tm), y_mid=float(cy[0] + cy[1] * tm), x0=float(cx[0]), y0=float(cy[0]),
395
+ frames=frames)
396
+
397
+
398
+ def _utc(mjd):
399
+ t = _dt.datetime(1858, 11, 17) + _dt.timedelta(days=float(mjd))
400
+ return t.isoformat(timespec="milliseconds")
401
+
402
+
403
+ def inject(F, par=PAR):
404
+ """Completeness of the whole chain: synthetic movers (Gaussian, peak S/N per frame = level) added to the frames, the
405
+ stack at their rate, then ``measure``; recovered = measured as a 'track' within 2 px of where it was put."""
406
+ rng = np.random.default_rng(par["seed"])
407
+ V = rates(F, par)
408
+ ny, nx = F["norm"].shape[1:]
409
+ tc = F["tc"]
410
+ yy, xx = np.mgrid[:ny, :nx]
411
+ out = []
412
+ for lev in par["inj_levels"]:
413
+ hit, tried = 0, 0
414
+ for _ in range(par["inj_n"]):
415
+ vx, vy = V[rng.integers(len(V))]
416
+ m = int(max(abs(vx), abs(vy)) * np.abs(tc).max()) + 12
417
+ if 2 * m >= min(nx, ny) - 4:
418
+ continue
419
+ x0, y0 = rng.uniform(m, nx - m), rng.uniform(m, ny - m)
420
+ add = np.array([lev * np.exp(-((xx - x0 - vx * t) ** 2 + (yy - y0 - vy * t) ** 2) / (2 * s * s))
421
+ for t, s in zip(tc, F["psf"])])
422
+ G = dict(F, norm=F["norm"] + add, diff=F["diff"] + add)
423
+ d = stack_input(G)
424
+ st, mm = _stack(d, tc, vx, vy)
425
+ core = st[mm:-mm, mm:-mm]
426
+ sg = _noise(core)
427
+ xi, yi = int(round(x0)), int(round(y0))
428
+ box = st[yi - 3:yi + 4, xi - 3:xi + 4]
429
+ j = np.unravel_index(np.argmax(box), box.shape)
430
+ tried += 1
431
+ if box[j] >= par["snr"] * sg:
432
+ t = measure(G, stack_input(G, mask=False), (box[j] / sg, vx, vy, xi - 3 + j[1], yi - 3 + j[0]), par)
433
+ hit += bool(t and t["status"] == "track" and math.hypot(t["x0"] - x0, t["y0"] - y0) < 2)
434
+ out.append(dict(peak_snr_per_frame=lev, injected=tried, recovered=hit))
435
+ return out
436
+
437
+
438
+ # ---------------------------------------------------------------- run, seal, compare
439
+ def run(paths, par=None, log=print):
440
+ """Blind search of every field -> notes dict (not yet sealed)."""
441
+ par = dict(PAR, **(par or {}))
442
+ fields, tracks, weak = [], [], []
443
+ for path in paths:
444
+ F = prepare(load_field(path), par)
445
+ d, du = stack_input(F), stack_input(F, mask=False)
446
+ found = {"stack": stack_search(F, d, par), "slow": slow_search(F, par)}
447
+ found["link"], note = link_search(F, par)
448
+ cands = []
449
+ for how, cs in found.items():
450
+ for c in cs:
451
+ t = measure(F, du, c, par)
452
+ if t is None:
453
+ continue
454
+ twin = next((u for u in cands if math.hypot(u["x0"] - t["x0"], u["y0"] - t["y0"]) < 3
455
+ and math.hypot(u["rate_ra"] - t["rate_ra"], u["rate_dec"] - t["rate_dec"]) < 3), None)
456
+ if twin is None:
457
+ cands.append(dict(t, found_by=[how]))
458
+ elif how not in twin["found_by"]:
459
+ twin["found_by"].append(how)
460
+ comp = inject(F, par) if par["inj_n"] else []
461
+ ny, nx = F["norm"].shape[1:]
462
+ cra, cde = (float(v) for v in F["wcs"].pixel_to_world_values((nx - 1) / 2, (ny - 1) / 2))
463
+ fields.append(dict(name=F["name"], files=F["files"], n_frames=len(F["mjd"]), utc_first=_utc(F["mjd"][0]),
464
+ utc_last=_utc(F["mjd"][-1]), ra=cra, dec=cde, nx=nx, ny=ny, pixscale=F["ps"],
465
+ psf_fwhm_arcsec=float(np.median(F["psf"]) * 2.3548 * F["ps"]), filters=sorted(set(F["filt"])),
466
+ frames=[dict(utc=_utc(m), mjd=float(m), filt=f) for m, f in zip(F["mjd"], F["filt"])],
467
+ wcs={k: v for k, v in F["wcs"].to_header().items()},
468
+ candidates={k: len(v) for k, v in found.items()}, link_note=note, completeness=comp))
469
+ tracks += [c for c in cands if c["status"] == "track"]
470
+ weak += sorted([c for c in cands if c["status"] == "weak"], key=lambda t: -t["stack_snr"])[:20] # ponytail: top 20
471
+ log(f"{F['name']}: {len(F['mjd'])} frames, candidates {fields[-1]['candidates']}, "
472
+ f"{sum(c['status'] == 'track' for c in cands)} track(s), {sum(c['status'] == 'weak' for c in cands)} weak; "
473
+ + ", ".join(f"{c['recovered']}/{c['injected']} at {c['peak_snr_per_frame']}" for c in comp))
474
+ return dict(schema="orbitsift/blindcheck/1", orbitsift=__version__, params=par, fields=fields,
475
+ tracks=sorted(tracks, key=lambda t: -t["stack_snr"]), weak=sorted(weak, key=lambda t: -t["stack_snr"]))
476
+
477
+
478
+ def seal(notes, path):
479
+ """Write the notes and <path>.sha256 (hash, file name, UTC time): the record that they existed before a prediction."""
480
+ notes = dict(notes, sealed_utc=_dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds"))
481
+ Path(path).write_text(json.dumps(notes, indent=1) + "\n")
482
+ h = _sha(path)
483
+ Path(str(path) + ".sha256").write_text(f"{h} {Path(path).name} {notes['sealed_utc']}\n")
484
+ return h
485
+
486
+
487
+ def verify(path):
488
+ """sha256 of the notes, or ValueError if they changed after sealing (or were never sealed)."""
489
+ seal_file = Path(str(path) + ".sha256")
490
+ if not seal_file.exists():
491
+ raise ValueError(f"{path}: no {seal_file.name}: these notes were never sealed")
492
+ want, h = seal_file.read_text().split()[0], _sha(path)
493
+ if h != want:
494
+ raise ValueError(f"{path}: sha256 {h[:16]}... differs from the seal {want[:16]}...: the notes changed after sealing")
495
+ return h
496
+
497
+
498
+ def read_ephemeris(path):
499
+ """CSV with a header: ra, dec [deg] and mjd (UTC) or utc (ISO) -> (mjd, ra, dec) sorted by time."""
500
+ import csv
501
+ from astropy.time import Time
502
+ with open(path, newline="") as f:
503
+ R = list(csv.DictReader(f))
504
+ if not R or not {"ra", "dec"} <= set(R[0]):
505
+ raise ValueError(f"{path}: needs a header with ra, dec and mjd or utc")
506
+ mjd = [float(r["mjd"]) if r.get("mjd") else float(Time(r["utc"].rstrip("Z"), scale="utc").mjd) for r in R]
507
+ o = np.argsort(mjd)
508
+ return np.array(mjd)[o], np.array([float(r["ra"]) for r in R])[o], np.array([float(r["dec"]) for r in R])[o]
509
+
510
+
511
+ def _interp(E, mjd):
512
+ t, ra, de = E
513
+ if not (t[0] - 2e-5 <= mjd <= t[-1] + 2e-5):
514
+ return None
515
+ if len(t) == 1:
516
+ return float(ra[0]), float(de[0])
517
+ return float(np.interp(mjd, t, np.unwrap(ra, period=360)) % 360), float(np.interp(mjd, t, de))
518
+
519
+
520
+ def compare(notes_path, ephem_path, tol=2.0):
521
+ """Measured minus predicted for every track and weak candidate of sealed notes (verified first)."""
522
+ from astropy.wcs import WCS
523
+ h = verify(notes_path)
524
+ N = json.loads(Path(notes_path).read_text())
525
+ E = read_ephemeris(ephem_path)
526
+ out = []
527
+ for t in N["tracks"] + N["weak"]:
528
+ R = []
529
+ for f in t["frames"]:
530
+ p = _interp(E, f["mjd"])
531
+ if p is None or not f["used"]:
532
+ continue
533
+ dra = ((f["ra"] - p[0] + 180) % 360 - 180) * math.cos(math.radians(f["dec"])) * 3600
534
+ R.append(dict(k=f["k"], utc=f["utc"], dra=dra, ddec=(f["dec"] - p[1]) * 3600))
535
+ if not R:
536
+ continue
537
+ a, b = np.array([r["dra"] for r in R]), np.array([r["ddec"] for r in R])
538
+ p0, p1 = _interp(E, R[0] and t["frames"][0]["mjd"]), _interp(E, t["frames"][-1]["mjd"])
539
+ prate = None
540
+ if p0 and p1 and t["frames"][-1]["mjd"] > t["frames"][0]["mjd"]:
541
+ dt = (t["frames"][-1]["mjd"] - t["frames"][0]["mjd"]) * 24
542
+ prate = [((p1[0] - p0[0] + 180) % 360 - 180) * math.cos(math.radians(p0[1])) * 3600 / dt, (p1[1] - p0[1]) * 3600 / dt]
543
+ out.append(dict(field=t["field"], status=t["status"], utc_mean=t["utc_mean"], rate=[t["rate_ra"], t["rate_dec"]],
544
+ predicted_rate=prate, n=len(R), mean_dra=float(a.mean()), mean_ddec=float(b.mean()),
545
+ mean_sep=float(np.hypot(a, b).mean()), rows=R))
546
+ out.sort(key=lambda r: r["mean_sep"])
547
+ where = []
548
+ for F in N["fields"]:
549
+ m = (F["frames"][0]["mjd"] + F["frames"][-1]["mjd"]) / 2
550
+ p = _interp(E, m)
551
+ if p is None:
552
+ continue
553
+ x, y = (float(v) for v in WCS(F["wcs"]).world_to_pixel_values(p[0], p[1]))
554
+ where.append(dict(field=F["name"], x=x, y=y, inside=bool(0 <= x < F["nx"] and 0 <= y < F["ny"])))
555
+ match = [r for r in out if r["mean_sep"] <= tol and r["status"] == "track"]
556
+ verdict = "match" if len(match) == 1 else "ambiguous" if match else "no_match"
557
+ return dict(verdict=verdict, notes_sha256=h, ephemeris=str(ephem_path), ephemeris_sha256=_sha(ephem_path), tol=tol,
558
+ sealed_utc=N.get("sealed_utc"), predicted_in=where, tracks=out)