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/confirm.py ADDED
@@ -0,0 +1,1030 @@
1
+ """Confirm a candidate on archival images it was never found on (``orbitsift confirm``).
2
+
3
+ For a track (its rows: ra, dec, UTC mid-exposure MJD, V): an orbit and 400 clones from the rows alone; the exposures
4
+ of the local tables (``expindex``) that hold it, decided here; forced PSF photometry and a shift-and-stack on the
5
+ exposures the rows never used, with 8 local and 24 null tracks and shifted twins; the rows checked on their own
6
+ images; a joint refit, leave-one-opposition-out, the known-object and registry checks; a tiered verdict with frozen
7
+ thresholds (``presets/confirm_v2.json``; ``confirm_v1`` = the same without the per-row tests). Only exposure and
8
+ file ids leave the machine (``net`` strict mode).
9
+
10
+ The rule is the survey's (PREREG_FORCED / FORCED2 / STAGE2 / OTHERARCH, INDEP_REG); the scratch code it ports is
11
+ named in each function.
12
+ """
13
+ import hashlib
14
+ import json
15
+ import math
16
+ import random
17
+
18
+ import numpy as np
19
+ from scipy import ndimage, optimize
20
+
21
+ from . import expindex, extend, growth, images, net, orbit
22
+
23
+ PRESET = "confirm_v2"
24
+
25
+
26
+ def load_rule(over=None, name=PRESET):
27
+ """The frozen rule of the preset with single keys overridden -> (rule, preset dict, modified)."""
28
+ p = growth.preset(name)
29
+ r = dict(p["rule"])
30
+ bad = set(over or {}) - set(r)
31
+ if bad:
32
+ raise ValueError(f"unknown [confirm.rule] key(s): {', '.join(sorted(bad))}")
33
+ r.update(over or {})
34
+ return r, p, growth.rule_sha(r) != p["rule_sha256"]
35
+
36
+
37
+ RULE = growth.preset(PRESET)["rule"]
38
+
39
+
40
+ # ---------------------------------------------------------------- orbit, clones, the exposure plan
41
+ def start(det, rule=RULE, site="W84", T=None):
42
+ """Orbit and clones from the rows alone (sel.plan_one): det = [[ra, dec, mjd, V or None], ...]. With an exposure
43
+ table T, each row is matched to its exposure: 'mid' (within 1 s of the mid time), 'start' (within 1 s of the start:
44
+ moved to mid, as NSC DR2 rows give the start), else 'unmatched' (kept as given). -> dict."""
45
+ d = np.array(sorted([[r[0], r[1], r[2], np.nan if r[3] is None else r[3]] for r in det], key=lambda r: r[2]), float)
46
+ ra, de, t, V = d[:, 0], d[:, 1], d[:, 2].copy(), d[:, 3]
47
+ tc = []
48
+ if T is not None and len(T["exposure"]):
49
+ mid, half = T["mjd_mid"], T["exptime"] / 172800
50
+ o = np.argsort(mid)
51
+ for i, ti in enumerate(t):
52
+ j = o[np.clip(np.searchsorted(mid[o], [ti - half.max() - 1e-4, ti + 1e-4]), 0, len(o))[0]:
53
+ np.clip(np.searchsorted(mid[o], ti + half.max() + 1e-4), 0, len(o))]
54
+ dm, ds = np.abs(mid[j] - ti) * 86400, np.abs(mid[j] - half[j] - ti) * 86400
55
+ if len(j) and dm.min() <= 1:
56
+ tc.append(dict(row=i, time_src="mid", exposure=str(T["exposure"][j[dm.argmin()]])))
57
+ elif len(j) and ds.min() <= 1:
58
+ k = j[ds.argmin()]
59
+ t[i] = mid[k]
60
+ tc.append(dict(row=i, time_src="start", moved_s=round(float(half[k] * 86400), 3), exposure=str(T["exposure"][k])))
61
+ else:
62
+ tc.append(dict(row=i, time_src="unmatched"))
63
+ arc = orbit.Arc(t, ra, de, rule["sigma"], site)
64
+ f = orbit.fit(arc, rule["r_min"], rule["r_max"])
65
+ if f is None:
66
+ return dict(arc=arc, orbit=None, used_mjd=t, time_check=tc)
67
+ S = orbit.sample(arc, f, rule["clones"], seed=rule["clone_seed"])
68
+ jd, obs = orbit.observer(t, site)
69
+ p = orbit.kepler(S[:1, :3], S[:1, 3:], jd - f.t0)[0]
70
+ g = 5 * np.log10(np.linalg.norm(p, axis=1) * np.linalg.norm(p - obs, axis=1))
71
+ ok = np.isfinite(V)
72
+ H, flag = (float(np.mean(V[ok] - g[ok])), None) if ok.any() else (float(rule["V_default"] - np.mean(g)), "no magnitudes: V 23.5")
73
+ return dict(arc=arc, orbit=f, S=S, t0=float(f.t0), state=[float(v) for v in S[0]], H=H, H_flag=flag, used_mjd=t,
74
+ fit_rms=float(f.rms), time_check=tc)
75
+
76
+
77
+ def plan(st, T, rule=RULE, have=(), sites=None):
78
+ """The exposure plan, fixed before any fetch (sel.plan_one + sel2.pick): unused exposures with predicted S/N >=
79
+ snr_pred_min and clone extent <= ext95_max (mode P); per night its per_night best; then at most max_exposures,
80
+ exposures of ``have`` (already measured for this orbit) first, then nights round-robin over the oppositions (gap >
81
+ season_gap d; best predicted night S/N first inside one, oppositions in order of their best night). Exposures with
82
+ q99 up to s_q99_max go to search mode (S); larger clouds are listed for ``extend``. Own exposures (a row's) go to
83
+ the row check. -> dict."""
84
+ E = expindex.covered(T, st["S"], st["t0"], st["H"], st["used_mjd"], rule, sites)
85
+ own = [x for x in E if x["arm"] == "own"]
86
+ U = [x for x in E if x["arm"] == "unused" and x["snr_raw"] >= rule["snr_pred_min"]]
87
+ P = [dict(x, mode="P") for x in U if x["ext_raw"] <= rule["ext95_max"]]
88
+ Sx = [dict(x, mode="S") for x in U if x["ext_raw"] > rule["ext95_max"] and x["q99"] <= rule["s_q99_max"]]
89
+ listed = [x for x in U if x["ext_raw"] > rule["ext95_max"] and x["q99"] > rule["s_q99_max"]]
90
+ by = {}
91
+ for x in sorted(P, key=lambda x: -x["snr_pred"]):
92
+ by.setdefault(x["night"], []).append(x)
93
+ by = {n: v[:rule["per_night"]] for n, v in by.items()}
94
+ take = _pick(by, set(have), rule)
95
+ return dict(exposures=take, search=Sx, own=own, listed=listed, n_eligible_exp=sum(len(v) for v in by.values()),
96
+ n_eligible_nights=len(by), testable=len({x["night"] for x in take}) >= rule["testable_nights"])
97
+
98
+
99
+ def _pick(by, have, rule):
100
+ """sel2.pick: exposures already measured first, then nights round-robin over the oppositions."""
101
+ E = [x for n in by for x in by[n]]
102
+ take = [x for x in sorted(E, key=lambda x: x["mid"]) if x["exposure"] in have]
103
+ got = {x["night"] for x in take}
104
+ ns = sorted(by, key=lambda n: -math.hypot(*[x["snr_pred"] for x in by[n]]))
105
+ seas = []
106
+ for n in sorted(by):
107
+ if seas and n - seas[-1][-1] <= rule["season_gap"]:
108
+ seas[-1].append(n)
109
+ else:
110
+ seas.append([n])
111
+ q = [[n for n in ns if n in s and n not in got] for s in seas]
112
+ q.sort(key=lambda l: ns.index(l[0]) if l else 10 ** 9)
113
+ while len(take) < rule["max_exposures"] and any(q):
114
+ for l in q:
115
+ if l and len(take) + len(by[l[0]]) <= rule["max_exposures"]:
116
+ take += by[l.pop(0)]
117
+ elif l:
118
+ l.pop(0)
119
+ return sorted(take, key=lambda x: x["mid"])
120
+
121
+
122
+ # ---------------------------------------------------------------- measurement
123
+ def tracks(ra, dec, pa, rule=RULE):
124
+ """Track positions (forced.offsets): 0 the prediction, 1-8 the local offsets along / across the motion, then the
125
+ first ``controls`` of extend.CONTROLS (60-120")."""
126
+ c = math.cos(math.radians(dec))
127
+ p = math.radians(pa)
128
+ al, ac = (math.sin(p), math.cos(p)), (math.cos(p), -math.sin(p)) # unit (E, N)
129
+ P = [(0.0, 0.0)] + [(a * al[0] + b * ac[0], a * al[1] + b * ac[1]) for a, b in rule["local_offsets"]] + \
130
+ [tuple(v) for v in extend.CONTROLS[:rule["controls"]]]
131
+ return [(ra + e / 3600 / c, dec + n / 3600) for e, n in P]
132
+
133
+
134
+ def shifted(ra, dec, shift):
135
+ """A sky offset (east, north ["]) applied to a position (forced2.pred)."""
136
+ d = dec + shift[1] / 3600
137
+ return ra + shift[0] / 3600 / math.cos(math.radians(d)), d
138
+
139
+
140
+ def _flux(fr, ra, dec, h):
141
+ """Forced PSF flux and error in units of a G = 23 source, and the stamp (forced.flux)."""
142
+ x, y = fr.sky2pix(ra, dec)
143
+ if not (np.isfinite(x[0]) and np.isfinite(y[0])):
144
+ return None, None
145
+ im, o, sg = extend._stamp(fr, x[0], y[0], h, 12, 3 * fr.psf_s)
146
+ if im is None:
147
+ return None, None
148
+ f, e = images.psf_flux(im, x[0] - o[0], y[0] - o[1], fr.psf_s, sg)
149
+ u = 10 ** (0.4 * (fr.zp - 23.0))
150
+ return (f / u, e / u), (im / u, float(x[0] - o[0]), float(y[0] - o[1]))
151
+
152
+
153
+ def predict(st, mjd, site):
154
+ R, D = orbit.predict(np.array([st["state"]]), st["t0"], np.array([mjd]), site)
155
+ return float(R[0, 0]), float(D[0, 0])
156
+
157
+
158
+ def measure_frame(fr, x, st, rule=RULE, shifts=((0.0, 0.0),)):
159
+ """One calibrated frame, at its own header mid time, for the target and every shift (twins) -> list of
160
+ (record, stamp or None). Record = the survey's forced.py record: f [[flux, err] or None] per track, fit, ..."""
161
+ out = []
162
+ ra0, de0 = predict(st, fr.mid, fr.site)
163
+ for sh in shifts:
164
+ ra, de = shifted(ra0, de0, sh)
165
+ f0, s0 = _flux(fr, ra, de, rule["stamp"] // 2)
166
+ if f0 is None:
167
+ out.append((dict(status="off_ccd"), None))
168
+ continue
169
+ F = [f0] + [_flux(fr, a, d, rule["stamp"] // 2)[0] for a, d in tracks(ra, de, x["pa"], rule)[1:]]
170
+ try:
171
+ m = extend.point(fr, ra, de, rule["fit_radius"])
172
+ except (ValueError, IndexError, np.linalg.LinAlgError):
173
+ m = None
174
+ r = dict(status="measured", ccd=fr.path.split("/")[-1], frame_mid=fr.mid, time_src=getattr(fr, "time_src", ""),
175
+ dt_s=round((fr.mid - x["mid"]) * 86400, 2), filt=fr.filt, exptime=fr.exptime, pixscale=fr.ps,
176
+ fwhm=round(2.355 * fr.psf_s * fr.ps, 3), zp=round(fr.zp, 3), nstar=fr.nstar, wcs_rms=round(fr.wcs_rms, 3),
177
+ ra=ra, dec=de, f=[None if v is None else [float(v[0]), float(v[1])] for v in F], fit=m,
178
+ stamp_xy=[s0[1], s0[2]])
179
+ out.append((r, s0[0].astype(np.float32)))
180
+ return out
181
+
182
+
183
+ # ---------------------------------------------------------------- features and the stack rule (feat.py)
184
+ def _comb(fe):
185
+ fe = [v for v in fe if v is not None and v[1] > 0 and np.isfinite(v[0])]
186
+ if not fe:
187
+ return None
188
+ w = np.array([1 / v[1] ** 2 for v in fe])
189
+ f = np.array([v[0] for v in fe])
190
+ return float((w * f).sum() / w.sum() * math.sqrt(w.sum()))
191
+
192
+
193
+ def _wmed(f, w):
194
+ o = np.argsort(f)
195
+ c = np.cumsum(w[o])
196
+ return float(f[o][np.searchsorted(c, 0.5 * c[-1])])
197
+
198
+
199
+ def keep(M, j, rule=RULE):
200
+ """Outlier clip of track j: drop exposures whose flux is off the inverse-variance weighted median by more than
201
+ clip_err x err + clip_frac x |median| (a star or an artefact under the track on one exposure)."""
202
+ V = [(r, r["f"][j]) for r in M if r["f"][j] is not None and r["f"][j][1] > 0 and np.isfinite(r["f"][j][0])]
203
+ if len(V) < 2:
204
+ return [r for r, _ in V]
205
+ f = np.array([v[0] for _, v in V])
206
+ e = np.array([v[1] for _, v in V])
207
+ m = _wmed(f, 1 / e ** 2)
208
+ return [r for (r, v) in V if abs(v[0] - m) <= rule["clip_err"] * v[1] + rule["clip_frac"] * abs(m)]
209
+
210
+
211
+ def flux_feats(M, j, rule=RULE):
212
+ """S/N_tot, jackknife (min over nights of S/N_tot with that night left out), nights and per-night S/N of track j."""
213
+ M = keep(M, j, rule)
214
+ by = {}
215
+ for r in M:
216
+ by.setdefault(r["plan"]["night"], []).append(r["f"][j])
217
+ tot = _comb([v for l in by.values() for v in l])
218
+ jk = min([_comb([v for n2, l in by.items() if n2 != n for v in l]) or -99 for n in by]) if len(by) >= 2 else None
219
+ sn = {n: _comb(l) for n, l in by.items()}
220
+ return tot, jk, sum((s or -99) >= 3 for s in sn.values()), sn
221
+
222
+
223
+ def stack(M, Z, size=51):
224
+ """Inverse-variance weighted mean of the stamps, each shifted so its prediction is at the centre; weighted PSF
225
+ sigma [px]."""
226
+ c = size // 2
227
+ acc, wt, sg = np.zeros((size, size)), 0.0, []
228
+ for r in M:
229
+ e = r["plan"]["exp"]
230
+ if e not in Z or not r["f"][0] or r["f"][0][1] <= 0:
231
+ continue
232
+ sx, sy = r["stamp_xy"]
233
+ w = 1 / r["f"][0][1] ** 2
234
+ acc += w * ndimage.shift(Z[e].astype(float), (c - sy, c - sx), order=1)
235
+ wt += w
236
+ sg.append((w, r["fwhm"] / 2.355 / r.get("pixscale", images.PIX)))
237
+ if not wt:
238
+ return None, None
239
+ return acc / wt, sum(a * b for a, b in sg) / sum(a for a, _ in sg)
240
+
241
+
242
+ def centroid(im, s, hw, ps):
243
+ """Gaussian (fixed sigma s px) + background fit in a (2 hw + 1)^2 box at the centre of the stack -> offset from the
244
+ centre ["] and amplitude S/N (noise from the outer ring)."""
245
+ c = im.shape[0] // 2
246
+ a, b = c - hw, c + 1 + hw
247
+ box = im[a:b, a:b]
248
+ yy, xx = np.mgrid[a:b, a:b]
249
+ ring = np.ones_like(im, bool)
250
+ ring[c - 15:c + 16, c - 15:c + 16] = False
251
+ noise = 1.4826 * np.median(np.abs(im[ring] - np.median(im[ring])))
252
+
253
+ def res(p):
254
+ return (p[0] * np.exp(-((xx - p[1]) ** 2 + (yy - p[2]) ** 2) / (2 * s * s)) + p[3] - box).ravel() / noise
255
+ try:
256
+ r = optimize.least_squares(res, [max(im[c - 2:c + 3, c - 2:c + 3].max(), 1e-3 * noise), float(c), float(c), float(np.median(box))],
257
+ bounds=([-np.inf, a, a, -np.inf], [np.inf, b - 1, b - 1, np.inf]))
258
+ J = r.jac
259
+ snr = r.x[0] / math.sqrt(np.linalg.inv(J.T @ J)[0, 0])
260
+ except (ValueError, np.linalg.LinAlgError):
261
+ return None, None
262
+ return float(math.hypot(r.x[1] - c, r.x[2] - c) * ps), float(snr)
263
+
264
+
265
+ def features(R, Z, rule=RULE):
266
+ """Features of one target (feat.feats): R {exposure: record}, Z {exposure: stamp}."""
267
+ M = [r for r in R.values() if r.get("status") == "measured" and r.get("f") and r["f"][0]]
268
+ nights = sorted({r["plan"]["night"] for r in M})
269
+ seas = []
270
+ for t in sorted(r["plan"]["mid"] for r in M):
271
+ if not seas or t - seas[-1] > rule["season_gap"]:
272
+ seas.append(t)
273
+ else:
274
+ seas[-1] = t
275
+ nt = 1 + len(rule["local_offsets"]) + rule["controls"]
276
+ tr = [flux_feats(M, j, rule) for j in range(nt)] if M else [(None, None, 0, {})] * nt
277
+ im, s = stack(keep(M, 0, rule), Z, rule["stamp"]) if M else (None, None)
278
+ ps = float(np.median([r.get("pixscale", images.PIX) for r in M])) if M else images.PIX
279
+ off, csnr = centroid(im, s, rule["centroid_box"], ps) if im is not None else (None, None)
280
+ return dict(n_meas=len(M), nights=len(nights), seasons=len(seas), snr_tot=tr[0][0], jk=tr[0][1], n3=tr[0][2], off=off,
281
+ csnr=csnr, night_snr={str(k): v for k, v in tr[0][3].items()}, null=[(t[0], t[1], t[2]) for t in tr[1:]])
282
+
283
+
284
+ def stack_rule(f, rule=RULE):
285
+ """The frozen stack rule (feat.rule): >= testable_nights nights, S/N_tot >= snr_tot, jackknife >= jk, stacked
286
+ centroid within ``centroid`` of the prediction, S/N_tot above every local track, at most null_max of the null
287
+ tracks meeting the flux part -> dict(passed, failed [names], null_pass)."""
288
+ T, J = rule["snr_tot"], rule["jk"]
289
+ fp = lambda tot, jk: tot is not None and jk is not None and tot >= T and jk >= J
290
+ nloc = len(rule["local_offsets"])
291
+ npass = sum(fp(t[0], t[1]) for t in f["null"])
292
+ failed = [k for k, bad in (
293
+ ("nights", f["nights"] < rule["testable_nights"]),
294
+ ("snr_tot", not (f["snr_tot"] is not None and f["snr_tot"] >= T)),
295
+ ("jk", not (f["jk"] is not None and f["jk"] >= J)),
296
+ ("centroid", f["off"] is None or f["off"] > rule["centroid"]),
297
+ ("local", f["snr_tot"] is None or any(t[0] is not None and t[0] >= f["snr_tot"] for t in f["null"][:nloc])),
298
+ ("nulls", npass > rule["null_max"])) if bad]
299
+ return dict(passed=not failed, failed=failed, null_pass=npass, null_tracks=sum(t[0] is not None for t in f["null"]))
300
+
301
+
302
+ def null_pass(f, rule=RULE):
303
+ """Null tracks meeting the flux part of the rule (no centroid test), and null tracks measured."""
304
+ T, J = rule["snr_tot"], rule["jk"]
305
+ return (sum(t[0] is not None and t[1] is not None and t[0] >= T and t[1] >= J for t in f["null"]),
306
+ sum(t[0] is not None for t in f["null"]))
307
+
308
+
309
+ def positions(R, rule=RULE):
310
+ """Per-exposure PSF rows of a passing stack (verdict2.positions): own exposure, fit S/N >= pos_snr, offset <=
311
+ pos_offset, shape in the window, kept by the clip."""
312
+ M = [r for r in R.values() if r.get("status") == "measured" and r.get("f") and r["f"][0]]
313
+ K = {id(r) for r in keep(M, 0, rule)}
314
+ lo, hi = rule["shape"]
315
+ out = []
316
+ for r in M:
317
+ m = r.get("fit")
318
+ if m and id(r) in K and m["snr"] >= rule["pos_snr"] and m["offset"] <= rule["pos_offset"] and lo <= m["shape"] <= hi \
319
+ and not m.get("masked"):
320
+ out.append(dict(exp=r["plan"]["exp"], ccd=r.get("ccd"), mjd_mid=r["frame_mid"], night=r["plan"]["night"],
321
+ band=r.get("filt"), ra=m["ra"], dec=m["dec"], snr=round(m["snr"], 2),
322
+ sig=round(max(m.get("sig", float("nan")), rule["sig_floor"]), 3), mag_G23=round(m["mag"], 2),
323
+ offset=round(m["offset"], 3), forced_snr=round(r["f"][0][0] / r["f"][0][1], 2),
324
+ time_src=r.get("time_src", ""), site=r.get("site", "W84")))
325
+ return sorted(out, key=lambda z: z["mjd_mid"])
326
+
327
+
328
+ def twin_offsets(n, rule=RULE, seed=None):
329
+ """n fixed sky offsets (east, north ["]) of 20-50" in random directions (sel2: random.Random(twin_seed))."""
330
+ rs = random.Random(rule["twin_seed"] if seed is None else seed)
331
+ out = []
332
+ for _ in range(n):
333
+ a, r = rs.uniform(0, 2 * math.pi), rs.uniform(*rule["twin_r"])
334
+ out.append((r * math.sin(a), r * math.cos(a)))
335
+ return out
336
+
337
+
338
+ def meas_key(x, st, rule, shifts):
339
+ """Measurement cache key: exposure, orbit state, shifts and the measurement keys of the rule."""
340
+ keys = {k: rule[k] for k in ("local_offsets", "controls", "fit_radius", "stamp")}
341
+ s = json.dumps([x["exposure"], [round(v, 9) for v in st["state"]], round(st["t0"], 9), shifts, keys], sort_keys=True)
342
+ return hashlib.sha1(s.encode()).hexdigest()[:20]
343
+
344
+
345
+ # ---------------------------------------------------------------- fetch by exposure id, the measurement cache
346
+ CONNECTOR = {"DECam": "noirlab", "MegaCam": "cadc"} # HSC: request files only (smoka.request); frames measured when local
347
+ TIME_SRC = {"DECam": "MJD-OBS+EXPTIME/2", "MegaCam": "SHUTOPEN/SHUTCLOS", "HSC": "MJD-STR/MJD-END"}
348
+
349
+
350
+ def _cache(*parts):
351
+ from .config import cache_dir
352
+ p = cache_dir().joinpath("confirm", *parts)
353
+ p.parent.mkdir(parents=True, exist_ok=True)
354
+ return p
355
+
356
+
357
+ def frames(x, ra, dec, tmp, log=print):
358
+ """Calibrated frames of exposure x (a plan entry) whose CCD holds one of the positions, fetched by exposure id only;
359
+ the cuts go to the folder tmp -> (frames, status). Status: ok | no_ccd | fetch_fail | frame_fail | not_fetched (HSC,
360
+ or not public)."""
361
+ from pathlib import Path
362
+ from . import archives
363
+ a = CONNECTOR.get(x["inst"])
364
+ if a is None or x.get("public", "1") not in ("1", "True", "true", ""):
365
+ return [], "not_fetched"
366
+ e = dict(archive=a, id=x["exposure"][:17] if x["inst"] == "DECam" else x["exposure"], mjd=x["mid"] - x["exptime"] / 172800,
367
+ exptime=x["exptime"], inst=x["inst"], site=x["site"], filt=x["band"], by_id=True, **({"pad": x["pad"]} if "pad" in x else {}))
368
+ ra, dec = np.atleast_1d(ra), np.atleast_1d(dec)
369
+ try:
370
+ paths = archives.connectors([a])[a].fetch(e, lambda m, s: (ra, dec), Path(tmp))
371
+ except extend.SKIP as ex:
372
+ log(f" {x['exposure']}: fetch failed ({type(ex).__name__}: {str(ex)[:120]})")
373
+ return [], "fetch_fail"
374
+ out, err = [], None
375
+ for p in paths:
376
+ try:
377
+ fr = extend.Frame(str(p), float(ra[0]), float(dec[0]))
378
+ except extend.SKIP as ex:
379
+ err = repr(ex)[:150]
380
+ continue
381
+ fr.time_src = TIME_SRC[x["inst"]]
382
+ out.append(fr)
383
+ return out, "ok" if out else "frame_fail" if err else "no_ccd"
384
+
385
+
386
+ def measure(x, st, rule=RULE, shifts=((0.0, 0.0),), log=print):
387
+ """Forced photometry on one planned exposure for the target and its twins, cached under <cache>/confirm/meas
388
+ (exposure, orbit state, shifts, the measurement keys of the rule) -> [(record, stamp or None)] per shift."""
389
+ import tempfile
390
+ shifts = [tuple(float(v) for v in s) for s in shifts]
391
+ k = meas_key(x, st, rule, shifts)
392
+ pj, pz = _cache("meas", k + ".json"), _cache("meas", k + ".npz")
393
+ if pj.exists():
394
+ R = json.loads(pj.read_text())
395
+ Z = dict(np.load(pz)) if pz.exists() else {}
396
+ return [(r, Z.get(str(i))) for i, r in enumerate(R)]
397
+ ra0, de0 = predict(st, x["mid"], x["site"])
398
+ pts = [p for sh in shifts for p in tracks(*shifted(ra0, de0, sh), x["pa"], rule)[:9]]
399
+ out = None
400
+ with tempfile.TemporaryDirectory(dir=_cache("cut", "x").parent) as tmp:
401
+ fs, status = frames(x, [p[0] for p in pts], [p[1] for p in pts], tmp, log)
402
+ for fr in fs:
403
+ got = measure_frame(fr, x, st, rule, shifts)
404
+ if got[0][0]["status"] == "measured":
405
+ out = got
406
+ break
407
+ out = out or [(dict(status=status if status != "ok" else "off_ccd"), None)] * len(shifts)
408
+ plan = dict(x, exp=x["exposure"])
409
+ out = [(dict(r, plan=plan, site=x["site"]), s) for r, s in out]
410
+ if status != "fetch_fail": # a failed fetch is retried on the next run
411
+ net.save(pj, json.dumps([r for r, _ in out], default=float))
412
+ Z = {str(i): s for i, (_, s) in enumerate(out) if s is not None}
413
+ if Z:
414
+ np.savez_compressed(pz, **Z)
415
+ return out
416
+
417
+
418
+ # ---------------------------------------------------------------- the row image check (vrow_a3, vg.meas_one, fitv)
419
+ def ok_point(m, R, rule=RULE):
420
+ """vg.ok_pt: a point source with S/N >= row_snr, shape in the window, within R ["] of the place."""
421
+ lo, hi = rule["shape"]
422
+ return m is not None and m["snr"] >= rule["row_snr"] and lo <= m["shape"] <= hi and not m.get("masked") and m["offset"] <= R
423
+
424
+
425
+ def _conc(r, x, y):
426
+ """Concentration of a source in a background-subtracted image: flux within 2.5 px / flux within 7 px."""
427
+ yi, xi = int(round(y)), int(round(x))
428
+ s = r[yi - 8:yi + 9, xi - 8:xi + 9]
429
+ if s.shape != (17, 17) or not np.isfinite(s).all():
430
+ return None
431
+ yy, xx = np.mgrid[yi - 8:yi + 9, xi - 8:xi + 9]
432
+ d = np.hypot(xx - x, yy - y)
433
+ tot = s[d < 7].sum()
434
+ return float(s[d < 2.5].sum() / tot) if tot > 0 else None
435
+
436
+
437
+ def profile(r, bad, xy, stars):
438
+ """The row's concentration against the CCD's calibration stars (c7opp2 prof.py): stars > 15 px from the row with
439
+ clean 17 px stamps -> dict(n_stars, conc, star_conc, conc_minus_star)."""
440
+ x, y = xy
441
+ C = [c for sx, sy in stars if np.hypot(sx - x, sy - y) > 15 and 8 <= sx < r.shape[1] - 9 and 8 <= sy < r.shape[0] - 9
442
+ and not bad[int(round(sy)) - 8:int(round(sy)) + 9, int(round(sx)) - 8:int(round(sx)) + 9].any()
443
+ and (c := _conc(r, sx, sy)) is not None]
444
+ c0 = _conc(r, x, y)
445
+ sc = float(np.median(C)) if C else None
446
+ return dict(n_stars=len(C), conc=c0, star_conc=sc, conc_minus_star=None if c0 is None or sc is None else round(c0 - sc, 3))
447
+
448
+
449
+ def sharp(m, prof, rule=RULE):
450
+ """Row test 1 (rule2_vet CRITERIA T1): a row sharper than the PSF of the stars on the same CCD is an artefact
451
+ (cosmic ray): free-width ratio < row_sharp_ratio and concentration above the stars' by > row_sharp_conc. Fewer
452
+ than row_sharp_stars stars or no profile -> None (untested, kept). -> True (artefact) | False | None."""
453
+ if not prof or prof.get("conc_minus_star") is None or prof["n_stars"] < rule["row_sharp_stars"]:
454
+ return None
455
+ return bool(m["shape"] < rule["row_sharp_ratio"] and prof["conc_minus_star"] > rule["row_sharp_conc"])
456
+
457
+
458
+ def night_motion(rows, rule=RULE):
459
+ """Row test 2 (c7opp2 motion.py): on every night with >= 2 passing rows, the displacement of each row from the
460
+ night's first one must be the one an orbit fitted to the OTHER nights' passing rows predicts (needs >= 2 other
461
+ nights): chi = |measured - predicted| / hypot(sigma pair, clone spread) <= row_motion_chi. A night whose predicted
462
+ displacement is below row_motion_min sigma is untestable. -> [dict(night, rows, chi, pred_sig, failed)]."""
463
+ ok = [r for r in rows if r.get("ok")]
464
+ nt = {id(r): expindex.night(r["mid"], r["site"]) for r in ok}
465
+ out = []
466
+ for n in sorted(set(nt.values())):
467
+ rr = sorted([r for r in ok if nt[id(r)] == n], key=lambda r: r["mid"])
468
+ oth = [r for r in ok if nt[id(r)] != n]
469
+ if len(rr) < 2 or len({nt[id(r)] for r in oth}) < 2:
470
+ continue
471
+ arc = orbit.Arc([r["mid"] for r in oth], [r["ra"] for r in oth], [r["dec"] for r in oth],
472
+ np.full(len(oth), rule["sigma"]), [r["site"] for r in oth])
473
+ if len(oth) < 3: # 2 rows: fewer residuals than the 6 orbit unknowns
474
+ continue
475
+ try:
476
+ o = orbit.fit(arc, rule["r_min"], rule["r_max"])
477
+ except (ValueError, np.linalg.LinAlgError):
478
+ o = None
479
+ if o is None:
480
+ continue
481
+ R, D = orbit.predict(orbit.sample(arc, o, 200), o.t0, np.array([r["mid"] for r in rr]), rr[0]["site"])
482
+ a, cd = rr[0], math.cos(math.radians(rr[0]["dec"]))
483
+ for k, b in enumerate(rr[1:], 1):
484
+ m = np.array([(b["ra"] - a["ra"]) * cd, b["dec"] - a["dec"]]) * 3600
485
+ p = np.array([(R[:, k] - R[:, 0]) * cd, D[:, k] - D[:, 0]]) * 3600
486
+ sg = math.hypot(max(a["sig"], 0.02), max(b["sig"], 0.02))
487
+ pm = np.median(p, axis=1)
488
+ chi = float(np.hypot(*(m - pm)) / math.hypot(sg, float(np.hypot(*p.std(axis=1)))))
489
+ ps = float(np.hypot(*pm) / sg)
490
+ out.append(dict(night=n, rows=[a["i"], b["i"]], chi=round(chi, 2), pred_sig=round(ps, 2),
491
+ testable=ps >= rule["row_motion_min"], failed=bool(ps >= rule["row_motion_min"] and chi > rule["row_motion_chi"])))
492
+ return out
493
+
494
+
495
+ def brightness(rows, rule=RULE):
496
+ """Row test 3 (rule2_vet bright.py): a passing row fails if its magnitude differs by more than row_mag_band from
497
+ the median of the other passing rows in its band (>= 2 of them), or by more than row_mag_all from the median of
498
+ all other passing rows after the colour terms row_mag_colour (band -> r). -> {row i: dict(d_band, d_all, failed)}."""
499
+ ok = [r for r in rows if r.get("ok") and r.get("mag") is not None]
500
+ col = rule["row_mag_colour"]
501
+ out = {}
502
+ for r in ok:
503
+ o = [q for q in ok if q is not r]
504
+ if not o:
505
+ continue
506
+ sb = [q["mag"] for q in o if q["band"] == r["band"]]
507
+ db = r["mag"] - float(np.median(sb)) if len(sb) >= 2 else None
508
+ da = r["mag"] - col.get(r["band"], 0.0) - float(np.median([q["mag"] - col.get(q["band"], 0.0) for q in o]))
509
+ out[r["i"]] = dict(d_band=None if db is None else round(db, 2), d_all=round(da, 2),
510
+ failed=bool((db is not None and abs(db) > rule["row_mag_band"]) or abs(da) > rule["row_mag_all"]))
511
+ return out
512
+
513
+
514
+ def row_tests(ci, cn, rule=RULE):
515
+ """The three per-row tests adopted on 21-22 Nov 2026 (rule2_vet CRITERIA.md), on all rows of a track at once
516
+ (input and new): a failing row (or night) gets ok False and the reason in 'row_test'; rows are changed in place.
517
+ No-op for a rule without the row_* test keys (confirm_v1). -> dict(motion, brightness) for the report."""
518
+ if "row_sharp_ratio" not in rule:
519
+ return {}
520
+ rows = ci + cn
521
+ idx = [dict(r, i=k) for k, r in enumerate(rows)] # all three on the same set: the rows that passed row_check
522
+ M, Bt = night_motion(idx, rule), brightness(idx, rule)
523
+ bad_n = {x["night"] for x in M if x["failed"]}
524
+ for k, r in enumerate(rows):
525
+ why = [w for w, f in (("sharper than the PSF", r.get("sharp")),
526
+ ("same-night motion", r.get("ok") and expindex.night(r["mid"], r["site"]) in bad_n),
527
+ ("brightness", Bt.get(k, {}).get("failed"))) if f]
528
+ if r.get("ok") and why:
529
+ r.update(ok=False, row_test=why)
530
+ return dict(motion=M, brightness={str(k): v for k, v in Bt.items()})
531
+
532
+
533
+ def point_check(x, ra, dec, R, rule=RULE, controls=True, log=print):
534
+ """PSF fit within R of (ra, dec) on exposure x, and the same fit at the control places of the CCD (cached) ->
535
+ dict(status, m, ctl_pass, ctl_n, mid, time_src, ccd)."""
536
+ import tempfile
537
+ key = [x["exposure"], round(ra, 8), round(dec, 8), R, controls, rule["controls"], rule["row_snr"], rule["shape"]]
538
+ k = hashlib.sha1(json.dumps(key + (["prof1"] if "row_sharp_ratio" in rule else [])).encode()).hexdigest()[:20]
539
+ pj = _cache("point", k + ".json")
540
+ if pj.exists():
541
+ return json.loads(pj.read_text())
542
+ out = dict(status="off_ccd")
543
+ with tempfile.TemporaryDirectory(dir=_cache("cut", "x").parent) as tmp:
544
+ fs, status = frames(x, [ra], [dec], tmp, log)
545
+ out["status"] = status if status != "ok" else "off_ccd"
546
+ for fr in fs:
547
+ px, py = fr.sky2pix(ra, dec)
548
+ if not (np.isfinite(px[0]) and 20 < px[0] < fr.r.shape[1] - 20 and 20 < py[0] < fr.r.shape[0] - 20):
549
+ continue
550
+ m = extend.point(fr, ra, dec, R)
551
+ C = []
552
+ if controls:
553
+ c = math.cos(math.radians(dec))
554
+ for dx, dy in extend.CONTROLS[:rule["controls"]]:
555
+ try:
556
+ C.append(ok_point(extend.point(fr, ra + dx / 3600 / c, dec + dy / 3600, R), R, rule))
557
+ except (ValueError, IndexError, np.linalg.LinAlgError):
558
+ pass
559
+ out = dict(status="measured", m=m, ctl_pass=int(sum(C)), ctl_n=len(C), mid=fr.mid, time_src=fr.time_src,
560
+ ccd=fr.origin, wcs_rms=fr.wcs_rms)
561
+ if m is not None and "row_sharp_ratio" in rule:
562
+ xy = fr.sky2pix(m["ra"], m["dec"])
563
+ out["prof"] = profile(fr.r, fr.bad, (float(xy[0][0]), float(xy[1][0])), getattr(fr, "star_xy", np.zeros((0, 2))))
564
+ break
565
+ if out["status"] != "fetch_fail":
566
+ net.save(pj, json.dumps(out, default=float))
567
+ return out
568
+
569
+
570
+ def own_exposure(T, mid, rule=RULE, ra=None, dec=None):
571
+ """Index of the table exposure whose mid time is within row_time_match of mid, or None. With the row's position, the
572
+ nearest in time among those whose chips hold it (programmes that take short exposures a minute apart on a grid put
573
+ the nearest one on a neighbouring pointing); none holds it -> the nearest in time, as without a position."""
574
+ d = np.abs(T["mjd_mid"] - mid) * 86400
575
+ k = np.nonzero(d <= rule["row_time_match"])[0]
576
+ if not len(k):
577
+ return None
578
+ if ra is not None and len(k) > 1:
579
+ on = expindex.on_chip(T["inst"][k], np.full(len(k), ra), np.full(len(k), dec), T["ra"][k], T["dec"][k], T["mjd_mid"][k], 0.0) >= 0
580
+ if on.any():
581
+ k = k[on]
582
+ return int(k[np.argmin(d[k])])
583
+
584
+
585
+ def _x(T, j):
586
+ return {c: (float(T[c][j]) if c in expindex.FLOATS else str(T[c][j])) for c in expindex.COLUMNS} | \
587
+ dict(mid=float(T["mjd_mid"][j]), night=expindex.night(float(T["mjd_mid"][j]), str(T["site"][j])))
588
+
589
+
590
+ def static_exposures(T, ra, dec, mid, band, rule=RULE):
591
+ """Other-epoch exposures holding a sky position (|dt| > static_dt, exptime >= static_min_exptime): same band first,
592
+ then longest, then nearest in time; at most static_n."""
593
+ m = (np.abs(T["mjd_mid"] - mid) > rule["static_dt"]) & (T["exptime"] >= rule["static_min_exptime"]) & np.isin(T["inst"], list(CONNECTOR))
594
+ ix = np.nonzero(m)[0]
595
+ if not len(ix):
596
+ return []
597
+ on = expindex.on_chip(T["inst"][ix], np.full(len(ix), ra), np.full(len(ix), dec), T["ra"][ix], T["dec"][ix],
598
+ T["mjd_mid"][ix], 0.0) >= 0
599
+ ix = ix[on]
600
+ ix = sorted(ix, key=lambda j: (T["band"][j] != band, -float(T["exptime"][j]), abs(float(T["mjd_mid"][j]) - mid)))
601
+ return [_x(T, j) for j in ix[:rule["static_n"]]]
602
+
603
+
604
+ def row_check(rows, T, rule=RULE, log=print):
605
+ """Every row on its own exposure (the table exposure within row_time_match of its time; none -> not_checkable,
606
+ kept as given): a point source within R = clip(3 s68, row_r) of the row and within row_cat_sep of it; for new
607
+ (unused) rows also at most ctl_max of the control places; and no point source at the same sky position on
608
+ static_n exposures of other epochs (a static positive fails the row). rows: dict(ra, dec, mid, kind 'input' |
609
+ 'new', s68, band). The final row is the PSF position at the frame's header mid time. -> list of dict."""
610
+ out = []
611
+ for i, q in enumerate(rows):
612
+ R = float(np.clip(3 * q.get("s68", rule["row_s68"]), *rule["row_r"]))
613
+ r = dict(i=i, kind=q.get("kind", "input"), R=R, ra_in=q["ra"], dec_in=q["dec"], mid_in=q["mid"])
614
+ j = own_exposure(T, q["mid"], rule, q["ra"], q["dec"])
615
+ if j is None:
616
+ out.append(dict(r, status="no_exposure", checkable=False, ok=None, ra=q["ra"], dec=q["dec"], mid=q["mid"],
617
+ sig=q.get("sig", rule["sigma"]), site=q.get("site", "W84"), time_src="as given"))
618
+ continue
619
+ x = _x(T, j)
620
+ c = point_check(x, q["ra"], q["dec"], R, rule, controls=True, log=log)
621
+ m = c.get("m")
622
+ sep = float(images._sep(m["ra"], m["dec"], q["ra"], q["dec"]) * 3600) if m else None
623
+ img_ok = c["status"] == "measured" and ok_point(m, R, rule) and sep <= rule["row_cat_sep"]
624
+ st = []
625
+ if img_ok:
626
+ for y in static_exposures(T, m["ra"], m["dec"], c["mid"], x["band"], rule):
627
+ s = point_check(y, m["ra"], m["dec"], R, rule, controls=False, log=log)
628
+ st.append(dict(exposure=y["exposure"], status=s["status"], positive=s["status"] == "measured" and ok_point(s.get("m"), R, rule)))
629
+ ctl_ok = r["kind"] != "new" or c.get("ctl_pass", 0) <= rule["ctl_max"]
630
+ ok = bool(img_ok and ctl_ok and not any(s["positive"] for s in st))
631
+ r.update(status=c["status"], checkable=True, own_frame=x["exposure"], snr=m and m["snr"], shape=m and m["shape"], cat_sep=sep,
632
+ ctl_pass=c.get("ctl_pass"), ctl_n=c.get("ctl_n"), static=st, static_measured=sum(s["status"] == "measured" for s in st),
633
+ static_positive=sum(s["positive"] for s in st), img_ok=bool(img_ok), ok=ok, band=x["band"], site=x["site"])
634
+ if img_ok and "row_sharp_ratio" in rule:
635
+ r.update(prof=c.get("prof"), sharp=sharp(m, c.get("prof"), rule))
636
+ if ok:
637
+ r.update(ra=m["ra"], dec=m["dec"], mid=c["mid"], time_src=c["time_src"], sig=max(m["sig"], rule["sig_floor"]),
638
+ mag=m.get("mag"), time_check_ms=0.0)
639
+ out.append(r)
640
+ return out
641
+
642
+
643
+ # ---------------------------------------------------------------- joint refit, leave-one-opposition-out (fitv, judge, loso)
644
+ def oppositions(mjd, gap):
645
+ """Opposition labels 0, 1, ... of UTC MJDs: a new one after a gap > gap days (not calendar years)."""
646
+ mjd = np.asarray(mjd, float)
647
+ o = np.argsort(mjd)
648
+ lab = np.empty(len(mjd), int)
649
+ lab[o] = np.cumsum(np.r_[True, np.diff(mjd[o]) > gap]) - 1
650
+ return lab
651
+
652
+
653
+ def _a_sig(o):
654
+ """Barycentric a and its 1-sigma from the fit covariance (numerical Jacobian)."""
655
+ f = lambda s: orbit.elements(s[:3], s[3:])["a"]
656
+ s0 = o.state
657
+ a = f(s0)
658
+ J = np.array([(f(s0 + h) - f(s0 - h)) / (2 * h[k]) for k, h in enumerate(np.diag(np.maximum(np.abs(s0) * 1e-7, 1e-12)))])
659
+ return float(a), float(np.sqrt(max(J @ o.cov @ J, 0.0)))
660
+
661
+
662
+ def _fit(rows, rule, backend, weights=None, start=None, seed=None):
663
+ """One fit of rows (dict ra, dec, mid, sig, site) -> (orbit, residual per row ["], used mask, info)."""
664
+ sig = np.array([max(r["sig"], rule["sig_floor"]) for r in rows]) if weights is None else np.asarray(weights, float)
665
+ if backend == "findorb":
666
+ from .external import findorb_fit
667
+ obs = [dict(mjd=r["mid"], ra=r["ra"], dec=r["dec"], rmsRA=s, rmsDec=s, stn=r["site"], astCat="Gaia3") for r, s in zip(rows, sig)]
668
+ res = findorb_fit(obs, rule["sigma"], seed=seed)
669
+ if res is None:
670
+ return None, None, None, {}
671
+ o, info = res
672
+ order = np.argsort([r["mid"] for r in rows], kind="stable")
673
+ rr = np.empty(len(rows))
674
+ rr[order] = np.hypot(*o.residuals.T)
675
+ used = np.ones(len(rows), bool)
676
+ used[order[info["findorb"]["rejected"]]] = False
677
+ f = info["findorb"]
678
+ a, asig = f["elements_helio"].get("a"), f["elements_helio"]["sigma"].get("a")
679
+ return o, rr, used, dict(rms=f.get("rms_used_arcsec"), a=a, a_sig=asig, backend="findorb", ephemeris=f.get("ephemeris"),
680
+ seed=f.get("seed"))
681
+ arc = orbit.Arc([r["mid"] for r in rows], [r["ra"] for r in rows], [r["dec"] for r in rows], sig, [r["site"] for r in rows])
682
+ o = None
683
+ if start is not None:
684
+ from .lov import _local
685
+ o = _local(arc, start.x0, start.v0)
686
+ o = o or orbit.fit(arc, rule["r_min"], rule["r_max"])
687
+ if o is None:
688
+ return None, None, None, {}
689
+ rr = np.hypot(*o.residuals.T)
690
+ used = rr <= np.maximum(4 * sig, rule["other_res_max"]) # the internal fitter's rejection: > max(4 sigma, 1")
691
+ a, asig = _a_sig(o)
692
+ rms = float(np.sqrt(np.mean(rr[used] ** 2) / 2)) if used.any() else None # per coordinate, as Find_Orb's rms
693
+ return o, rr, used, dict(rms=rms, a=a, a_sig=asig, backend="internal")
694
+
695
+
696
+ SEED_USED = 0.8 # a Find_Orb fit keeping fewer of the rows is redone seeded (audit 21 Nov, c6); fitting procedure, not a rule key
697
+
698
+
699
+ def joint(rows, rule=RULE, backend="internal"):
700
+ """Joint fit of the kept rows; rows the fitter rejects are removed once and the fit redone, never iterated
701
+ (judge.py). rms = sqrt(mean(dRA^2 + dDec^2) / 2) over the rows used, per coordinate as Find_Orb's (with Find_Orb:
702
+ its own). A fit with rms exactly 0 fails. -> dict(orbit, used, count, rms, max, dropped, a, a_sig, bound)."""
703
+ if len(rows) < 3:
704
+ return dict(ok=False, why="fewer than 3 rows", count=len(rows))
705
+ o, rr, used, info = _fit(rows, rule, backend)
706
+ if backend == "findorb" and o is not None and used.sum() < SEED_USED * len(rows):
707
+ # an unseeded Find_Orb fit that keeps < 80 % of the rows may sit in a false minimum (the survey's GCT0283/0285):
708
+ # redo it from the internal two-body orbit; still < 80 % -> no fit (never one removal on a bad orbit)
709
+ oi = _fit(rows, rule, "internal")[0]
710
+ seed = None if oi is None else [oi.t0] + list(orbit.convert(oi.state, oi.t0, orbit.ECLIPTIC, orbit.HELIOCENTRIC))
711
+ o, rr, used, info = _fit(rows, rule, backend, seed=seed) if seed else (None, None, None, {})
712
+ if o is None or used.sum() < SEED_USED * len(rows):
713
+ return dict(ok=False, why=f"Find_Orb keeps < {SEED_USED:.0%} of the rows, also seeded", count=len(rows))
714
+ dropped = []
715
+ if o is not None and not used.all():
716
+ dropped = [rows[k]["mid"] for k in np.flatnonzero(~used)]
717
+ rows = [r for r, u in zip(rows, used) if u]
718
+ o, rr, used, info = _fit(rows, rule, backend)
719
+ if o is None:
720
+ return dict(ok=False, why="no orbit", count=len(rows), dropped=dropped)
721
+ rms = info["rms"]
722
+ a, asig = info.get("a"), info.get("a_sig")
723
+ bound = bool(o.bound and a is not None and a > 0)
724
+ return dict(ok=True, orbit=o, rows=rows, used=int(used.sum()), count=len(rows), rms=rms, max=float(rr[used].max()), seed=info.get("seed"),
725
+ residuals=[round(float(v), 3) for v in rr], dropped=dropped, a=a, a_sig=asig, bound=bound,
726
+ backend=info["backend"], rms_zero=bool(rms is not None and (rms < 1e-3 or int(used.sum()) <= 3))) # 3 rows fit 6 unknowns exactly: no test
727
+
728
+
729
+ def loso(rows, rule=RULE, backend="internal", full=None, seed=None):
730
+ """Leave-one-opposition-out: each opposition (gap > season_gap) left out in turn, the others predict its rows
731
+ (internal: a local fit from the full orbit; findorb: its rows weighted 999", started from the full fit's ``seed``
732
+ as loso.py). -> [dict(opp, first, n, pred_max, rms_rest, passed)]."""
733
+ lab = oppositions([r["mid"] for r in rows], rule["season_gap"])
734
+ out = []
735
+ for y in sorted(set(lab.tolist())):
736
+ m = lab == y
737
+ if backend == "findorb":
738
+ w = [999.0 if k else max(r["sig"], rule["sig_floor"]) for r, k in zip(rows, m)]
739
+ o, rr, used, info = _fit(rows, rule, backend, weights=w, seed=seed)
740
+ p = rr[m] if o is not None else None
741
+ rest = info.get("rms")
742
+ else:
743
+ keep = [r for r, k in zip(rows, m) if not k]
744
+ o, rr, used, info = _fit(keep, rule, backend, start=full) if len(keep) >= 3 else (None, None, None, {})
745
+ p = None
746
+ if o is not None:
747
+ R, D = zip(*[predict(dict(state=o.state, t0=o.t0), r["mid"], r["site"]) for r, k in zip(rows, m) if k])
748
+ q = [r for r, k in zip(rows, m) if k]
749
+ p = images._sep(np.array(R), np.array(D), np.array([r["ra"] for r in q]), np.array([r["dec"] for r in q])) * 3600
750
+ rest = info.get("rms")
751
+ out.append(dict(opp=int(y), first=float(min(r["mid"] for r, k in zip(rows, m) if k)), n=int(m.sum()),
752
+ pred_max=None if p is None else round(float(np.max(p)), 3), rms_rest=rest,
753
+ passed=bool(p is not None and np.max(p) <= rule["loso_max"])))
754
+ return out
755
+
756
+
757
+ def foreign_rows(checked, o, rule=RULE):
758
+ """Failed input rows compared with the final orbit (resid.py): one farther than foreign_row ["] may not belong."""
759
+ out = []
760
+ for r in checked:
761
+ if r.get("ok") is False and r["kind"] == "input":
762
+ ra, de = predict(dict(state=o.state, t0=o.t0), r["mid_in"], r.get("site", "W84"))
763
+ d = float(images._sep(ra, de, r["ra_in"], r["dec_in"]) * 3600)
764
+ out.append(dict(i=r["i"], sep=round(d, 3), possible_foreign=d > rule["foreign_row"]))
765
+ return out
766
+
767
+
768
+ # ---------------------------------------------------------------- the tiers
769
+ def bar(inp, new, J, L, identity, registry, complete, rule=RULE):
770
+ """The registration bar (INDEP_REG), item by item -> dict(item: dict(ok, value, need)). inp / new: row_check
771
+ results of the input rows and of the new rows; J: joint; L: loso of the kept rows."""
772
+ g = rule["season_gap"]
773
+ ok_in = [r for r in inp if r.get("ok")]
774
+ ok_new = [r for r in new if r.get("ok")]
775
+ opp_in = len(set(oppositions([r["mid"] for r in ok_in], g).tolist())) if ok_in else 0
776
+ in_nights = {expindex.night(r["mid"], r["site"]) for r in ok_in}
777
+ un_nights = sorted({expindex.night(r["mid"], r["site"]) for r in ok_new} - in_nights)
778
+ kept = ok_in + ok_new
779
+ opp_all = len(set(oppositions([r["mid"] for r in kept], g).tolist())) if kept else 0
780
+ fit_ok = bool(J.get("ok") and J["rms"] is not None and not J["rms_zero"] and J["rms"] <= rule["rms_max"] and J["bound"]
781
+ and J["a_sig"] is not None and J["a_sig"] < rule["asig_frac"] * J["a"])
782
+ if opp_all >= rule["loso_from_opp"]:
783
+ worst = max([x["pred_max"] for x in L if x["pred_max"] is not None], default=None)
784
+ i4 = dict(ok=bool(L and all(x["passed"] for x in L)), value=worst, need=f"<= {rule['loso_max']}\" (leave-one-opposition-out)")
785
+ else:
786
+ i4 = dict(ok=len(un_nights) >= rule["unused_nights_2opp"], value=len(un_nights),
787
+ need=f">= {rule['unused_nights_2opp']} unused nights (2 oppositions)")
788
+ ident = identity.get("status") == "none_found" and registry.get("status") == "checked" and not registry.get("duplicates")
789
+ return {"1_images": dict(ok=opp_in >= rule["opp_min"], value=opp_in, need=f">= {rule['opp_min']} oppositions of input rows on their images"),
790
+ "2_unused": dict(ok=len(un_nights) >= rule["unused_nights_min"], value=len(un_nights), need=f">= {rule['unused_nights_min']} confirmed unused night"),
791
+ "3_fit": dict(ok=fit_ok, value=dict(rms=J.get("rms"), bound=J.get("bound"), a=J.get("a"), a_sig=J.get("a_sig")),
792
+ need=f"rms <= {rule['rms_max']}\", sigma_a < {rule['asig_frac']} a, rms > 0"),
793
+ "4_arc": i4,
794
+ "5_static": dict(ok=not any(r.get("static_positive") for r in kept), value=sum(bool(r.get("static_positive")) for r in kept), need="0"),
795
+ "6_identity": dict(ok=ident, value=dict(identity=identity.get("status"), registry=registry.get("status")), need="none_found, registry checked"),
796
+ "7_complete": dict(ok=bool(complete), value=bool(complete), need="no failed fetch")}
797
+
798
+
799
+ def tier(B, S, testable):
800
+ """The image tier: full_bar | stack_confirmed | probable | not_confirmed | not_testable. B: bar(); S: stack_rule()
801
+ or None. probable (narrow): items 1, 3 and 5 hold, the identity is not a match, only the unused-night items (2, 4
802
+ on two oppositions) fail; a failed leave-one-opposition-out is evidence against."""
803
+ fails = [k for k, v in B.items() if not v["ok"]]
804
+ if not fails:
805
+ return "full_bar", []
806
+ if S and S["passed"]:
807
+ return "stack_confirmed", fails
808
+ loso_failed = "4_arc" in fails and "leave-one" in B["4_arc"]["need"]
809
+ if set(fails) <= {"2_unused", "4_arc", "6_identity", "7_complete"} and not loso_failed and \
810
+ not str(B["6_identity"]["value"]["identity"]).startswith("known:") and {"2_unused", "4_arc"} & set(fails):
811
+ return "probable", fails
812
+ if not testable and not B["1_images"]["value"]:
813
+ return "not_testable", fails
814
+ return "not_confirmed", fails
815
+
816
+
817
+ def verdict(t, identity, registry, complete, J):
818
+ """Verdict string from the tier and the overrides (identity, duplicates, incomplete, no bound orbit)."""
819
+ s = identity.get("status", "")
820
+ if s.startswith(("known:", "possible:", "undecided:")):
821
+ return s
822
+ if registry.get("duplicates"):
823
+ return f"duplicate:{registry['duplicates'][0]}"
824
+ if J.get("ok") and not J.get("bound") and t in ("not_confirmed", "not_testable"):
825
+ return "no_bound_orbit"
826
+ if not complete and t in ("not_confirmed", "not_testable", "probable"):
827
+ return "incomplete"
828
+ return t
829
+
830
+
831
+ # ---------------------------------------------------------------- identity glue, rates, the whole run
832
+ def identify(rows, rule=RULE, backend="internal", mpc=None, log=print):
833
+ """Known-object check of the kept rows against the MPC orbits of the files ``mpc`` (paths; known.mpc_file) ->
834
+ dict(status none_found | known:<designation> | possible:<designation> | undecided:<designations> | not_run, rule, pairs)."""
835
+ if not mpc:
836
+ return dict(status="not_run")
837
+ from . import known
838
+ arc = orbit.Arc([r["mid"] for r in rows], [r["ra"] for r in rows], [r["dec"] for r in rows],
839
+ [max(r["sig"], rule["sig_floor"]) for r in rows], [r["site"] for r in rows])
840
+ our = [dict(mjd=r["mid"], ra=r["ra"], dec=r["dec"], rmsRA=r["sig"], rmsDec=r["sig"], stn=r["site"], astCat="Gaia3") for r in rows]
841
+ C = known.mpc_orbits([str(p) for p in mpc], Q_min=rule["Q_min"])
842
+ K = known.check(arc, C, backend=backend, our_obs=our, rules=dict(known.CHECK, **{k: rule[k] for k in rule if k in known.CHECK}),
843
+ r_min=rule["r_min"], r_max=rule["r_max"], log=log)
844
+ pairs = [dict(desig=p["desig"], match=p["match"], rule=p.get("joint", {}).get("rule", "strict" if p["match"] else None),
845
+ link_rms=p["link"]["rms"], joint_rms=p.get("joint", {}).get("rms")) for p in K.get("pairs", [])]
846
+ if K.get("matches"):
847
+ return dict(status=f"known:{K['matches'][0]}", pairs=pairs, backend=backend)
848
+ if K.get("status") == "undecided": # a failed joint fit, or none run: never none_found
849
+ return dict(status="undecided:" + (",".join(K["undecided"]) or "no_joint_fit"), pairs=pairs, backend=backend)
850
+ screened = [p for p in K.get("pairs", []) if "joint" in p]
851
+ if screened and backend != "findorb":
852
+ return dict(status=f"possible:{screened[0]['desig']}", pairs=pairs, backend=backend)
853
+ return dict(status="none_found", pairs=pairs, backend=backend)
854
+
855
+
856
+ def rates(p, modified, twins_run, nulls_run):
857
+ """The control and known-object rates printed beside every verdict: this run, and the preset's measured ones."""
858
+ if modified:
859
+ return dict(rule_sha256=None, modified=True, preset="not valid for a modified rule", twins=dict(this_run=twins_run),
860
+ nulls=dict(this_run=nulls_run))
861
+ r = p["rates"]
862
+ return dict(rule_sha256=p["rule_sha256"], modified=False, source=r["source"],
863
+ twins=dict(this_run=twins_run, preset=r["twins"]["preset"], upper95=round(1 - 0.05 ** (1 / r["twins"]["preset"][1]), 3)),
864
+ nulls=dict(this_run=nulls_run, preset_per_track=r["nulls"]["preset_per_track"]),
865
+ knowns=dict(preset=r["knowns"]["preset"], preset_all=r["knowns"]["preset_all"], bin=r["knowns"]["bin"]))
866
+
867
+
868
+ def run(det, T, name="trk", rule_over=None, twins=4, backend="internal", registry=None, mpc=None, dry_run=False,
869
+ bulk_ok=False, bulk_ccds=500, check_rows=True, search_mode=True, preset=PRESET, log=print):
870
+ """`orbitsift confirm` on one track: det = [[ra, dec, UTC mjd, V or None], ...], T = expindex table. Strict
871
+ outbound mode for the whole process; refuses without a contact (ValueError). check_rows=False stops after the stack
872
+ stage (no row checks, fit or identity: the stack-only validation arm). -> report dict."""
873
+ net.settings["strict"] = True
874
+ if not net.contact():
875
+ raise ValueError("no contact for the User-Agent: set [net] contact (or ORBITSIFT_CONTACT): archives ask who runs this")
876
+ rule, p, modified = load_rule(rule_over, preset)
877
+ st = start(det, rule, T=T)
878
+ rep = dict(name=name, rule_sha256=growth.rule_sha(rule), modified=modified, outbound="ids_only", time_check=st["time_check"])
879
+ if st["orbit"] is None:
880
+ return dict(rep, verdict="no_bound_orbit", tier="not_testable")
881
+ pl = plan(st, T, rule)
882
+ rep.update(H=round(st["H"], 2), H_flag=st["H_flag"], fit_rms=round(st["fit_rms"], 3),
883
+ plan=dict(exposures=pl["exposures"], search=len(pl["search"]), own=len(pl["own"]), listed=len(pl["listed"]),
884
+ n_eligible_exp=pl["n_eligible_exp"], n_eligible_nights=pl["n_eligible_nights"], testable=pl["testable"]),
885
+ hsc=[x["exposure"] for x in pl["exposures"] if x["inst"] == "HSC"])
886
+ n_ccd = sum(x["inst"] in CONNECTOR for x in pl["exposures"]) + len(st["used_mjd"]) * (1 + rule["static_n"]) + \
887
+ (sum(x["inst"] in CONNECTOR for x in pl["search"]) if search_mode else 0) # search mode fetches every exposure it lists
888
+ if n_ccd > bulk_ccds and not bulk_ok:
889
+ raise ValueError(f"{n_ccd} CCDs to download: write to the archive first, then pass --bulk-ok")
890
+ if dry_run:
891
+ return dict(rep, dry_run=True, ccds_at_most=n_ccd)
892
+ shifts = [(0.0, 0.0)] + twin_offsets(twins, rule)
893
+ Rs, Zs = [dict() for _ in shifts], [dict() for _ in shifts]
894
+ complete = True
895
+ for x in pl["exposures"]:
896
+ if x["inst"] not in CONNECTOR:
897
+ continue
898
+ for i, (r, z) in enumerate(measure(x, st, rule, shifts, log)):
899
+ Rs[i][x["exposure"]] = r
900
+ if z is not None:
901
+ Zs[i][x["exposure"]] = z
902
+ complete &= r["status"] != "fetch_fail"
903
+ F = [features(R, Z, rule) for R, Z in zip(Rs, Zs)]
904
+ S = [stack_rule(f, rule) for f in F]
905
+ log(f"{name}: stack S/N {F[0]['snr_tot']}, jk {F[0]['jk']}, centroid {F[0]['off']} on {F[0]['nights']} nights -> "
906
+ f"{'passes' if S[0]['passed'] else 'fails ' + ','.join(S[0]['failed'])}")
907
+ inp = [dict(ra=float(a), dec=float(d), mid=float(m), kind="input", s68=rule["row_s68"], sig=rule["sigma"], site="W84")
908
+ for a, d, m in zip(st["arc"].ra, st["arc"].dec, st["used_mjd"])]
909
+ new = [dict(ra=q["ra"], dec=q["dec"], mid=q["mjd_mid"], kind="new", s68=max(q["sig"], rule["sig_floor"]) / 2, sig=q["sig"],
910
+ site=q["site"]) for q in positions(Rs[0], rule)] if S[0]["passed"] else []
911
+ if not check_rows:
912
+ tw = [s["passed"] for f, s in zip(F[1:], S[1:]) if f["nights"] >= rule["testable_nights"]]
913
+ return dict(rep, verdict="stack_confirmed" if S[0]["passed"] else "not_confirmed" if pl["testable"] else "not_testable",
914
+ tier=None, complete=complete, stack=dict(features={k: v_ for k, v_ in F[0].items() if k != "null"}, rule=S[0]),
915
+ twins=[dict(offset=sh, passed=s["passed"], testable=f["nights"] >= rule["testable_nights"])
916
+ for sh, f, s in zip(shifts[1:], F[1:], S[1:])],
917
+ rates=rates(p, modified, [sum(tw), len(tw)], [S[0]["null_pass"], S[0]["null_tracks"]]),
918
+ requests=dict(net.COUNTS), halvings=list(net.EVENTS))
919
+ sx = [search(x, st, st["S"], rule, log) for x in pl["search"] if x["inst"] in CONNECTOR] if search_mode else []
920
+ complete &= not any(r["status"] == "fetch_fail" for r in sx)
921
+ acc, _ = accept_search([dict(q, sig=rule["sigma"]) for q in inp], search_rows(sx, st, rule), rule, backend)
922
+ new += [dict(r, kind="new", s68=max(r["sig"], rule["sig_floor"]) / 2) for r in acc]
923
+ ci, cn = row_check(inp, T, rule, log), row_check(new, T, rule, log)
924
+ complete &= not any(r.get("status") == "fetch_fail" for r in ci + cn)
925
+ rt = row_tests(ci, cn, rule)
926
+ kept =[dict(ra=r["ra"], dec=r["dec"], mid=r["mid"], sig=r["sig"], site=r["site"]) for r in ci + cn if r.get("ok")] + \
927
+ [dict(ra=r["ra"], dec=r["dec"], mid=r["mid"], sig=r["sig"], site=r["site"]) for r in ci if r["status"] == "no_exposure"]
928
+ J = joint(kept, rule, backend)
929
+ L = loso(J["rows"], rule, backend, J["orbit"], J.get("seed")) if J.get("ok") and len(set(oppositions([r["mid"] for r in J["rows"]], rule["season_gap"]).tolist())) >= rule["loso_from_opp"] else []
930
+ fin = J["rows"] if J.get("ok") else kept
931
+ few = len(fin) < 3 # no orbit from fewer than 3 rows: nothing to identify
932
+ ident = dict(status="not_run", why="fewer than 3 rows") if few else identify(fin, rule, backend, mpc, log)
933
+ reg = dict(status="not_run", why="fewer than 3 rows") if few else dict(status="not_run")
934
+ if registry and not few:
935
+ from . import known
936
+ reg = known.registry_check(fin, J.get("orbit"), registry,
937
+ {k: rule[k] for k in rule if k in known.CHECK}, log)
938
+ B = bar(ci, cn, J, L, ident, reg, complete, rule)
939
+ t, fails = tier(B, S[0], pl["testable"])
940
+ v = verdict(t, ident, reg, complete, J)
941
+ tw = [s["passed"] for f, s in zip(F[1:], S[1:]) if f["nights"] >= rule["testable_nights"]]
942
+ rep.update(verdict=v, tier=t, failed=fails, bar=B, complete=complete, stack=dict(features={k: v_ for k, v_ in F[0].items() if k != "null"},
943
+ rule=S[0]), twins=[dict(offset=sh, passed=s["passed"], testable=f["nights"] >= rule["testable_nights"]) for sh, f, s in zip(shifts[1:], F[1:], S[1:])],
944
+ measurements=Rs[0], search=[{k: v for k, v in r.items() if k != "hits"} | dict(n_hits=len(r.get("hits", []))) for r in sx],
945
+ rows_input=ci, rows_new=cn, row_tests=rt, identity=ident, registry=reg, catalogue_search="not_run",
946
+ joint={k: v_ for k, v_ in J.items() if k not in ("orbit", "rows")}, loso=L,
947
+ foreign_rows=foreign_rows(ci, J["orbit"], rule) if J.get("ok") else [],
948
+ rates=rates(p, modified, [sum(tw), len(tw)], [S[0]["null_pass"], S[0]["null_tracks"]]),
949
+ requests=dict(net.COUNTS), halvings=list(net.EVENTS), look="pending" if t == "stack_confirmed" else None)
950
+ return rep
951
+
952
+
953
+ # ---------------------------------------------------------------- search mode for clouds of 1-60" (PREREG_OTHERARCH)
954
+ def _merge(P, r):
955
+ """Points (n, 2) [deg] with duplicates within r ["] merged (cfm.pts)."""
956
+ keep = []
957
+ for a, d in P:
958
+ if all(3600 * math.hypot((a - k[0]) * math.cos(math.radians(d)), d - k[1]) > r for k in keep):
959
+ keep.append((a, d))
960
+ return np.array(keep).reshape(-1, 2)
961
+
962
+
963
+ def _hits(fr, P, rule, R=None):
964
+ """Distinct point sources (> s_merge apart) with S/N >= row_snr and shape in the window from PSF fits at P."""
965
+ found = []
966
+ for a, d in P:
967
+ try:
968
+ m = extend.point(fr, a, d, rule["fit_radius"])
969
+ except (ValueError, IndexError, np.linalg.LinAlgError):
970
+ m = None
971
+ if ok_point(m, rule["fit_radius"], rule) and all(
972
+ 3600 * math.hypot((m["ra"] - f["ra"]) * math.cos(math.radians(d)), m["dec"] - f["dec"]) > rule["s_merge"] for f in found):
973
+ found.append(m)
974
+ return found
975
+
976
+
977
+ def search(x, st, S, rule=RULE, log=print):
978
+ """One exposure in search mode: PSF fits at every clone position (merged within s_merge), hits = sources within
979
+ max(1", q99 + s_offset_pad) of the nominal place; the same cloud rotated by 180 deg about the nominal place and
980
+ shifted by (+-90", 0), (0, +-90") as control arms (clean = mean hits <= s_ctl_mean). -> dict."""
981
+ import tempfile
982
+ Rc, Dc = orbit.predict(S, st["t0"], np.array([x["mid"]]), x["site"])
983
+ Rc, Dc = Rc[:, 0], Dc[:, 0]
984
+ P = _merge(np.c_[Rc, Dc], rule["s_merge"])
985
+ c = math.cos(math.radians(Dc[0]))
986
+ lim = max(1.0, x["q99"] + rule["s_offset_pad"])
987
+ out = dict(exposure=x["exposure"], q99=x["q99"], n_points=len(P), status="off_ccd")
988
+ with tempfile.TemporaryDirectory(dir=_cache("cut", "x").parent) as tmp:
989
+ fs, status = frames(dict(x, pad=max(160.0, 3 * x["q99"] + 150.0)), Rc[:1], Dc[:1], tmp, log)
990
+ out["status"] = status if status != "ok" else "off_ccd"
991
+ for fr in fs:
992
+ H = [h for h in _hits(fr, P, rule) if images._sep(h["ra"], h["dec"], Rc[0], Dc[0]) * 3600 <= lim]
993
+ ctl = [len(_hits(fr, np.c_[2 * Rc[0] - P[:, 0] + ox / 3600 / c, 2 * Dc[0] - P[:, 1] + oy / 3600], rule))
994
+ for ox, oy in ((90, 0), (-90, 0), (0, 90), (0, -90))]
995
+ out.update(status="measured", hits=[dict(h, mid=fr.mid, site=fr.site, time_src=fr.time_src) for h in H], ctl_hits=ctl,
996
+ clean=bool(np.mean(ctl) <= rule["s_ctl_mean"]))
997
+ break
998
+ return out
999
+
1000
+
1001
+ def search_rows(results, st, rule=RULE):
1002
+ """Rows from search mode: a hit counts only on a clean exposure and with a hit on another exposure of the same night
1003
+ within s_same_night after the predicted motion is removed. -> list of rows (ra, dec, mid, sig, site)."""
1004
+ good = [(r, h) for r in results if r.get("clean") for h in r.get("hits", [])]
1005
+ out = []
1006
+ for r, h in good:
1007
+ n = expindex.night(h["mid"], h["site"])
1008
+ ra0, de0 = predict(st, h["mid"], h["site"])
1009
+ for r2, h2 in good:
1010
+ if r2 is r or expindex.night(h2["mid"], h2["site"]) != n:
1011
+ continue
1012
+ ra1, de1 = predict(st, h2["mid"], h2["site"])
1013
+ d = images._sep(h2["ra"] - (ra1 - ra0), h2["dec"] - (de1 - de0), h["ra"], h["dec"]) * 3600
1014
+ if d <= rule["s_same_night"]:
1015
+ out.append(dict(ra=h["ra"], dec=h["dec"], mid=h["mid"], sig=max(h["sig"], rule["sig_floor"]), site=h["site"], snr=h["snr"]))
1016
+ break
1017
+ return out
1018
+
1019
+
1020
+ def accept_search(base, new, rule=RULE, backend="internal"):
1021
+ """Search-mode rows accepted by a joint fit with the existing rows: every new row's residual <= other_res_max, rms
1022
+ <= other_rms_max, no existing row rejected (PREREG_OTHERARCH 6)."""
1023
+ if not new:
1024
+ return [], None
1025
+ J = joint(base + new, rule, backend)
1026
+ if not J.get("ok") or J["dropped"] or J["rms"] is None:
1027
+ return [], J
1028
+ res = J["residuals"][len(base):]
1029
+ ok = J["rms"] <= rule["other_rms_max"] and all(v <= rule["other_res_max"] for v in res)
1030
+ return (new if ok else []), J