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/tiles.py ADDED
@@ -0,0 +1,58 @@
1
+ """Sky tiles: 1 x 1 degree cells queried with a 0.15 degree margin (0.3 degree overlap between
2
+ neighbours). A link belongs to the tile whose core (the cell itself) holds its mean position, so
3
+ overlapping tiles never report the same object twice."""
4
+ import numpy as np
5
+ from scipy.spatial import cKDTree
6
+
7
+ from .catalog import night
8
+ from .orbit import unit
9
+
10
+ MARGIN = 0.15 # deg
11
+ DECAM_RADIUS = 0.95 # deg, field radius used for coverage (chip gaps ignored)
12
+
13
+
14
+ def tile(ra, dec, margin=MARGIN):
15
+ """The tile containing (ra, dec): dict(id, ra0, ra1, dec0, dec1, box) with box = queried area."""
16
+ ra0, dec0 = int(np.floor(ra % 360)), int(np.floor(dec))
17
+ dec0 = min(dec0, 89)
18
+ mr = margin / np.cos(np.radians(min(89.9, max(abs(dec0), abs(dec0 + 1)))))
19
+ box = [round(ra0 - mr, 3), round(ra0 + 1 + mr, 3), round(max(-90, dec0 - margin), 3), round(min(90, dec0 + 1 + margin), 3)]
20
+ return dict(id=f"{ra0:03d}{dec0:+03d}", ra0=ra0, ra1=ra0 + 1, dec0=dec0, dec1=dec0 + 1, box=box)
21
+
22
+
23
+ def block(t, n=3):
24
+ """The n x n tiles centred on tile t (RA wraps; rows beyond a pole are left out), RA-major order."""
25
+ h = n // 2
26
+ return [tile(t["ra0"] + 0.5 + i, t["dec0"] + 0.5 + j) for i in range(-h, h + 1) for j in range(-h, h + 1)
27
+ if -90 <= t["dec0"] + j <= 89]
28
+
29
+
30
+ def tiles_in(ra0, ra1, dec0, dec1):
31
+ """All tiles whose cell overlaps the box."""
32
+ return [tile(a + 0.5, d + 0.5) for d in range(int(np.floor(dec0)), int(np.ceil(dec1)))
33
+ for a in range(int(np.floor(ra0)), int(np.ceil(ra1)))]
34
+
35
+
36
+ def in_core(t, ra, dec):
37
+ """True where (ra, dec) falls inside the tile's own cell."""
38
+ ra = np.asarray(ra) % 360
39
+ return (ra >= t["ra0"]) & (ra < t["ra1"]) & (np.asarray(dec) >= t["dec0"]) & (np.asarray(dec) < t["dec1"])
40
+
41
+
42
+ def area(box):
43
+ """Area of an RA/Dec box [deg^2]."""
44
+ return (box[1] - box[0]) * (np.sin(np.radians(box[3])) - np.sin(np.radians(box[2]))) * 180 / np.pi
45
+
46
+
47
+ def nights_covering(ex, ra, dec, vlim=None, V=None, radius=DECAM_RADIUS):
48
+ """For each position, the array of distinct nights with an exposure covering it (and, if V and the
49
+ per-exposure V limit are given, deep enough to reach V)."""
50
+ tr = cKDTree(unit(ex["ra"], ex["dec"]))
51
+ lst = tr.query_ball_point(unit(np.atleast_1d(ra), np.atleast_1d(dec)), 2 * np.sin(np.radians(radius) / 2))
52
+ out = []
53
+ for n, ix in enumerate(lst):
54
+ ix = np.array(ix, int)
55
+ if V is not None:
56
+ ix = ix[vlim[ix] > np.atleast_1d(V)[n]]
57
+ out.append(np.unique(night(ex["mjd"][ix])))
58
+ return out
orbitsift/unused.py ADDED
@@ -0,0 +1,103 @@
1
+ """The unused-exposure test (``orbitsift unused``): is the object on archival exposures that no fit has used?
2
+
3
+ Positions enter a fit only while it stays consistent, so small residuals and blind predictions of left-out nights are
4
+ conditioned on that selection. This test measures where the orbit puts the object on every public DECam exposure of
5
+ the NSC DR2 era (2012-2019) that covers it and contributes no position: forced PSF S/N with the centroid FIXED at the
6
+ prediction (``extend.forced_snr``), and the same at 32 control positions shifted by 60-120" (``extend.CONTROLS``,
7
+ the same shift on every exposure). Rules (fixed on 30 designated TNOs and their controls before candidates were looked
8
+ at): an exposure is eligible if the prediction falls on it, its depth (depth95 + colour) is >= 0.3 mag fainter than the
9
+ expected magnitude, no input observation is within exptime/2 + 5 s of it, and the 95% extent of the orbit clones there is
10
+ <= 3"; then, per object, with N eligible exposures measured, f_det the fraction with S/N >= 3 and the depth-weighted
11
+ stack S/N = sum(w s) / sqrt(sum w^2), w = 10^(0.4 margin):
12
+ pass N >= 3, f_det >= 0.5 and stack >= 5
13
+ fail N >= 3, f_det <= 0.2 and stack < 3
14
+ inconclusive otherwise.
15
+ The same statistics on each control track give the false-pass rate. Measured on the survey: 30 of 30 truth objects and
16
+ 12 of 1663 control tracks (0.7%) pass. The test shows flux at the predicted places; it does not by itself prove that the
17
+ flux is one moving body.
18
+ """
19
+ import numpy as np
20
+
21
+ from . import catalog, extend, orbit, tiles
22
+
23
+ COLOUR = {"g": 0.45, "r": -0.30, "i": -0.60, "z": -0.75, "Y": -0.80, "VR": -0.15} # band - V of a typical TNO
24
+ MARGIN_MIN, EXT_MAX, FIELD = 0.3, 3.0, 0.95 # mag, arcsec, deg
25
+
26
+
27
+ def eligible(S, t0, V, used_mjd, start="2012-09-01", end="2019-12-31", site="W84", step_days=30.0):
28
+ """Exposures of the NSC DR2 table along the predicted track that pass the eligibility rules.
29
+ S: orbit samples (nominal first) at t0 JD TDB; V: expected V; used_mjd: UTC MJDs of every input observation.
30
+ -> list of dict(name, mid, exptime, filt, margin, ext95, ra, dec)."""
31
+ from astropy.time import Time
32
+ m0, m1 = Time(start).mjd, Time(end).mjd
33
+ days = np.arange(m0, m1 + step_days, step_days)
34
+ ra, dec = orbit.predict(S[:1], t0, days, site)
35
+ ts = {tiles.tile(a, d)["id"]: tiles.tile(a, d) for a, d in zip(ra[0], dec[0])}
36
+ ex = [catalog.exposures(t["box"]) for t in ts.values()]
37
+ keys = ("name", "mjd", "ra", "dec", "filt", "exptime", "depth")
38
+ E = {k: np.concatenate([e[k] for e in ex]) for k in keys} if ex else {k: np.zeros(0) for k in keys}
39
+ _, u = np.unique(E["name"], return_index=True)
40
+ E = {k: v[u] for k, v in E.items()}
41
+ mid = E["mjd"] + E["exptime"] / 2 / 86400
42
+ ok = (E["mjd"] >= m0) & (E["mjd"] <= m1) & np.array([str(n).startswith(("c4d", "tu")) for n in E["name"]], bool) # tu: 2013-14 CP names
43
+ used = np.asarray(used_mjd, float)
44
+ if len(used):
45
+ ok &= np.min(np.abs(mid[:, None] - used[None]), 1) * 86400 > E["exptime"] / 2 + 5
46
+ out = []
47
+ for j in np.flatnonzero(ok):
48
+ R, D = orbit.predict(S, t0, np.array([mid[j]]), site)
49
+ if np.degrees(np.arccos(np.clip(orbit.unit(R[0, 0], D[0, 0]) @ orbit.unit(E["ra"][j], E["dec"][j]), -1, 1))) > FIELD:
50
+ continue
51
+ ext95 = orbit.extent(R[:, 0], D[:, 0])[0] if len(R) > 2 else 0.0
52
+ f = str(E["filt"][j]).split()[0]
53
+ margin = float(E["depth"][j]) - (V + COLOUR.get(f, 0.0))
54
+ if ext95 <= EXT_MAX and margin >= MARGIN_MIN:
55
+ out.append(dict(name=str(E["name"][j]), mid=float(mid[j]), exptime=float(E["exptime"][j]), filt=f, margin=margin,
56
+ ext95=ext95, ra=float(R[0, 0]), dec=float(D[0, 0])))
57
+ return out
58
+
59
+
60
+ def measure(x, outdir):
61
+ """Fixed-centroid forced S/N at the prediction and at the 32 control offsets on the exposure ``x`` (from ``eligible``):
62
+ the CCD is cut from the NOIRLab archive -> dict(snr, ctl (32,), status: ok | masked | off)."""
63
+ from .archives import noirlab
64
+ c = np.cos(np.radians(x["dec"]))
65
+ P = np.r_[[(0.0, 0.0)], extend.CONTROLS[:32]]
66
+ A, D = x["ra"] + P[:, 0] / 3600 / c, x["dec"] + P[:, 1] / 3600
67
+ e = dict(archive="noirlab", inst="DECam", id=x["name"][:17], mjd=x["mid"] - x["exptime"] / 2 / 86400, exptime=x["exptime"], by_id=True)
68
+ s = [None] * len(P)
69
+ for p in noirlab.fetch(e, lambda m, site: (A, D), outdir):
70
+ fr = extend.Frame(str(p), x["ra"], x["dec"])
71
+ for j in range(len(P)):
72
+ if s[j] is None:
73
+ px, py = fr.sky2pix(np.array([A[j]]), np.array([D[j]]))
74
+ if 0 <= px[0] < fr.r.shape[1] and 0 <= py[0] < fr.r.shape[0]:
75
+ v = extend.forced_snr(fr, A[j], D[j])
76
+ s[j] = np.nan if v is None else float(v)
77
+ fr.drop_maps()
78
+ snr = s[0]
79
+ status = "off" if snr is None else ("masked" if not np.isfinite(snr) else "ok")
80
+ return dict(snr=None if status != "ok" else snr, ctl=np.array([np.nan if v is None else v for v in s[1:]], float), status=status)
81
+
82
+
83
+ def verdict(snr, margin):
84
+ """Per object (or control track): S/N on N exposures with their depth margins -> dict(n, f_det, stack, verdict)."""
85
+ s, m = np.asarray(snr, float), np.asarray(margin, float)
86
+ k = np.isfinite(s)
87
+ s, m = s[k], m[k]
88
+ n = len(s)
89
+ if not n:
90
+ return dict(n=0, f_det=None, stack=None, verdict="inconclusive")
91
+ w = 10 ** (0.4 * m)
92
+ f, st = float((s >= 3).mean()), float((w * s).sum() / np.sqrt((w ** 2).sum()))
93
+ v = "pass" if n >= 3 and f >= 0.5 and st >= 5 else "fail" if n >= 3 and f <= 0.2 and st < 3 else "inconclusive"
94
+ return dict(n=n, f_det=f, stack=st, verdict=v)
95
+
96
+
97
+ def summarize(rows):
98
+ """rows: [dict(eligible fields + measure fields)] -> dict(object verdict, controls: passes / tracks)."""
99
+ ok = [r for r in rows if r["status"] == "ok"]
100
+ obj = verdict([r["snr"] for r in ok], [r["margin"] for r in ok])
101
+ ctl = [verdict([r["ctl"][j] for r in ok], [r["margin"] for r in ok]) for j in range(32)] if ok else []
102
+ return dict(obj, controls_pass=sum(c["verdict"] == "pass" for c in ctl), controls=len(ctl),
103
+ exposures_measured=len(ok), masked=sum(r["status"] == "masked" for r in rows), off=sum(r["status"] == "off" for r in rows))
orbitsift/vet.py ADDED
@@ -0,0 +1,304 @@
1
+ """Vetoes that separate real movers from chance links of single-night catalogue objects.
2
+
3
+ Measured on NSC DR2 tiles: known TNOs pass, nearly all unmatched links fail. In order:
4
+
5
+ miss nights inside the link's span (+-5 d) whose exposures reach V + 0.3 and where the link's
6
+ orbit predicts the position to < 5" (1 sigma): a real mover must have a single-night object
7
+ within 3 sigma + 2" on >= min_found_frac of them (or on all but one).
8
+ cr detection FWHM < r x the exposure FWHM: cosmic ray or hot pixel. r depends on the depth
9
+ margin (exposure depth95 - detection magnitude in its band): the 1st percentile of the
10
+ FWHM ratio of known-TNO detections at that margin, capped at cr_fwhm_ratio (CR_MARGINS).
11
+ trail >= trail_min other single-night objects of the same exposure within 5' lie on one line
12
+ through the detection (perpendicular distance < 1.5"): satellite trail.
13
+ intra detections whose night has another deep exposure covering them must be confirmed there
14
+ (the NSC object has ndet >= 2, or another single-night object sits at the predicted
15
+ position). Veto if none is confirmed and (>= 2 such nights, or one and rms >= 0.15").
16
+ static another NSC object within static_radius arcsec, seen on another night (TAP query per
17
+ detection): a star or galaxy that the Gaia / Legacy Survey veto missed. Veto if >= 2.
18
+ kepler no bound barycentric two-body orbit fits the detections within kepler_rms_max arcsec rms.
19
+
20
+ A link is vetoed by miss, intra, static, kepler, or if fewer than 4 nights remain after dropping trail
21
+ detections and, when at least cr_min_flagged detections are cr (and not trail), the cr ones too.
22
+ """
23
+ import copy
24
+ from concurrent.futures import ThreadPoolExecutor
25
+
26
+ import numpy as np
27
+
28
+ from . import catalog, known, orbit, tiles
29
+ from .link import AS, fit, from_plane, jacobian, predict, to_plane
30
+ from .orbit import centre_ra, unit
31
+
32
+
33
+ def mid_times(det, ex):
34
+ """Mid-exposure UTC MJD and filter of each detection [[ra, dec, mjd, V], ...]: the NSC exposure
35
+ starting within 45 s of the object's mjd (else the object mjd, a mean of start times, plus half the nearest
36
+ exposure's time on that night, and '?')."""
37
+ o = np.argsort(ex["mjd"])
38
+ ms = ex["mjd"][o]
39
+ out = []
40
+ for _, _, mjd, _ in det:
41
+ i = int(np.clip(np.searchsorted(ms, mjd), 1, len(ms) - 1)) if len(ms) > 1 else 0
42
+ if len(ms) > 1 and abs(ms[i - 1] - mjd) < abs(ms[i] - mjd):
43
+ i -= 1
44
+ if len(ms) and abs(ms[i] - mjd) < 5e-4:
45
+ j = o[i]
46
+ out.append((mjd + ex["exptime"][j] / 2 / 86400, str(ex["filt"][j]), str(ex["name"][j])))
47
+ elif len(ms) and abs(ms[i] - mjd) < 0.5:
48
+ out.append((mjd + ex["exptime"][o[i]] / 2 / 86400, "?", None))
49
+ else:
50
+ out.append((mjd, "?", None))
51
+ return out
52
+
53
+
54
+ def miss_test(link, orph, ex, vlim, ndet, site="W84", dist_range=(30.0, 150.0)):
55
+ """Missing-night and intra-night confirmation counts for one link (see module docstring)."""
56
+ det = np.array(link["det"])
57
+ ra0, dec0, tm = centre_ra(det[:, 0]), det[:, 1].mean(), det[:, 2].mean()
58
+ th, E = to_plane(det[:, 0], det[:, 1], det[:, 2], ra0, dec0, site)
59
+ gsig = (1 / dist_range[0] - 1 / dist_range[1]) / 2
60
+ p, rms, H = fit(th, det[:, 2] - tm, E, 1 / link["dist_au"], gsig, 0.2)
61
+ H = H * (0.2 * AS) ** 2
62
+ t0, t1 = det[:, 2].min() - 5, det[:, 2].max() + 5
63
+ close = unit(ex["ra"], ex["dec"]) @ unit(ra0, dec0) > np.cos(np.radians(1.5))
64
+ deep = np.flatnonzero(close & (ex["mjd"] > t0) & (ex["mjd"] < t1) & (vlim > link["V"] + 0.3))
65
+ ora, odec, omjd = orph
66
+ ok_n = {}
67
+ for e in deep: # prediction on each deep exposure, if good to < 5"
68
+ m = ex["mjd"][e]
69
+ _, En = to_plane(np.array([ra0]), np.array([dec0]), np.array([m]), ra0, dec0, site)
70
+ J = jacobian(p, np.array([m - tm]), En)
71
+ s1 = np.sqrt(max(np.linalg.eigvalsh(J @ H @ J.T).max(), 0)) / AS
72
+ pra, pdec = from_plane(predict(p, np.array([m - tm]), En), ra0, dec0)
73
+ if s1 > 5 or unit(pra, pdec)[0] @ unit(ex["ra"][e], ex["dec"][e]) < np.cos(np.radians(0.95)):
74
+ continue
75
+ n = int(np.floor(m - 0.5))
76
+ k = np.flatnonzero((np.abs(omjd - m) < 0.4) & (np.abs((ora - pra[0] + 180) % 360 - 180) * np.cos(np.radians(pdec[0])) < 0.02)
77
+ & (np.abs(odec - pdec[0]) < 0.02))
78
+ hit = False
79
+ if len(k): # prediction at each candidate's own mjd
80
+ _, Ek = to_plane(ora[k], odec[k], omjd[k], ra0, dec0, site)
81
+ qa, qd = from_plane(predict(p, omjd[k] - tm, Ek), ra0, dec0)
82
+ hit = bool((np.hypot(((ora[k] - qa + 180) % 360 - 180) * np.cos(np.radians(qd)), odec[k] - qd) * 3600 < 3 * s1 + 2).any())
83
+ ok_n[n] = ok_n.get(n, False) or hit
84
+ intra_n = intra_c = 0
85
+ for (ra, dec, mjd, _), oid in zip(det, link["ids"]):
86
+ dm = np.abs(ex["mjd"][deep] - mjd)
87
+ oth = deep[(dm < 0.4) & (dm > 2e-4) & (unit(ex["ra"][deep], ex["dec"][deep]) @ unit(ra, dec) > np.cos(np.radians(0.95)))]
88
+ if ndet.get(oid, 1) >= 2:
89
+ intra_n += 1
90
+ intra_c += 1
91
+ continue
92
+ if not len(oth):
93
+ continue
94
+ intra_n += 1
95
+ k = np.flatnonzero((np.abs(omjd - mjd) < 0.4) & (np.abs(omjd - mjd) > 2e-4) & (np.abs(odec - dec) < 0.01)
96
+ & (np.abs((ora - ra + 180) % 360 - 180) * np.cos(np.radians(dec)) < 0.01))
97
+ if len(k):
98
+ _, Ek = to_plane(ora[k], odec[k], omjd[k], ra0, dec0, site)
99
+ qa, qd = from_plane(predict(p, omjd[k] - tm, Ek), ra0, dec0)
100
+ intra_c += bool((np.hypot(((ora[k] - qa + 180) % 360 - 180) * np.cos(np.radians(qd)), odec[k] - qd) * 3600 < 2.0).any())
101
+ found = sum(ok_n.values())
102
+ return dict(rms_refit=rms, exp_nights=len(ok_n), found_nights=found, frac=found / len(ok_n) if ok_n else None,
103
+ intra_nights=intra_n, intra_conf=intra_c)
104
+
105
+
106
+ def trail_test(d, orph, trail_min=5):
107
+ """True if >= trail_min single-night objects of the same exposure line up with the detection."""
108
+ ora, odec, omjd = orph
109
+ ra, dec, mjd = d[:3]
110
+ k = np.flatnonzero(np.abs(omjd - mjd) < 2e-4)
111
+ x = ((ora[k] - ra + 180) % 360 - 180) * np.cos(np.radians(dec)) * 3600
112
+ y = (odec[k] - dec) * 3600
113
+ r = np.hypot(x, y)
114
+ x, y = x[(r > 1) & (r < 300)], y[(r > 1) & (r < 300)]
115
+ for phi in np.radians(np.arange(0, 180, 1.0)):
116
+ if (np.abs(-np.sin(phi) * x + np.cos(phi) * y) < 1.5).sum() >= trail_min:
117
+ return True
118
+ return False
119
+
120
+
121
+ # (margin lo, margin hi, FWHM ratio): 1st percentile of the FWHM / exposure-FWHM ratio of 11,877 NSC DR2
122
+ # detections of known TNOs per depth-margin bin, capped at 0.8 (0.5 where a bin had < 50 detections; none had).
123
+ # With these and cr_min_flagged=2 the veto drops 32 of 1331 known-object links instead of 146 (flat 0.8, 1).
124
+ CR_MARGINS = ((-9.0, 0.0, 0.468), (0.0, 0.5, 0.651), (0.5, 9.0, 0.8))
125
+
126
+
127
+ def cr_test(d, fwhm_obj, ex, cr_fwhm_ratio=0.8, row=None, margins=CR_MARGINS):
128
+ """True if the detection is much sharper than the exposure's seeing. With ``margins`` the ratio
129
+ depends on the depth margin of the detection (``row``: its catalogue row, for the magnitude in the
130
+ exposure's band); an unknown margin takes the lowest ratio. ``margins=()``: flat cr_fwhm_ratio."""
131
+ ra, dec, mjd = d[:3]
132
+ j = np.flatnonzero(np.abs(ex["mjd"] - mjd) < 2e-5)
133
+ if not len(j):
134
+ j = np.flatnonzero((np.abs(ex["mjd"] - mjd) < 0.4) & (unit(ex["ra"], ex["dec"]) @ unit(ra, dec) > np.cos(np.radians(1.1))))
135
+ e = np.nanmedian(ex["fwhm"][j]) if len(j) else np.nan
136
+ r = cr_fwhm_ratio
137
+ if margins:
138
+ k = j[0] if len(j) else None
139
+ m = row.get(catalog.MAG_COLUMNS.get(str(ex["filt"][k]), ""), "") if row is not None and k is not None else ""
140
+ dm = float(ex["depth"][k]) - float(m) if m and float(m) < 50 else np.nan
141
+ r = min(cr_fwhm_ratio, next((t for lo, hi, t in margins if lo <= dm < hi), min(t for *_, t in margins)))
142
+ return bool(fwhm_obj < r * e)
143
+
144
+
145
+ def static_test(link, static_radius=1.0):
146
+ """Per detection: another NSC object within static_radius ", seen on another night? None if the
147
+ TAP service fails."""
148
+ out = []
149
+ try:
150
+ for (ra, dec, mjd, _), oid in zip(link["det"], link["ids"]):
151
+ c = np.cos(np.radians(dec))
152
+ objs = catalog.objects_near(ra, dec, static_radius)
153
+ out.append(any(o["id"] != oid and np.hypot((float(o["ra"]) - ra) * c, float(o["dec"]) - dec) * 3600 < static_radius
154
+ and (float(o["deltamjd"]) > 0.6 or abs(float(o["mjd"]) - mjd) > 0.6) for o in objs))
155
+ except Exception:
156
+ return None
157
+ return out
158
+
159
+
160
+ NEAR_KEP_RMS, NEAR_R_MIN = 0.3, 8.0 # near mode: exact two-body fit within 0.3" at >= 8 AU (main belt, Hildas out)
161
+
162
+
163
+ def near_rms_max(V):
164
+ """Two-body rms allowed for a near-mode survivor of median magnitude V: NSC single-epoch astrometry is
165
+ ~0.03-0.05" at V < 21 and ~0.1-0.15" at V 23."""
166
+ return 0.2 if V <= 22.5 else 0.25
167
+
168
+
169
+ def near_rules(links, site="W84"):
170
+ """Near-mode survivors among links that passed the local vetoes: >= 5 nights; two-body rms <= near_rms_max(V) or
171
+ heliocentric e > 1.1; a physical orbit (e <= 1.1, or a bound fit within near_rms_max(V): one-season arcs leave e
172
+ free and real TNOs drift hyperbolic); and not in a cluster: a link sharing >= 4 nights with >= 2 other such
173
+ links within 3 deg is dropped with them unless its orbit is TNO-like (chance links in dense fields come in
174
+ bunches on one set of nights). Sets l["vet"]["near"] = list of failed rules (empty: survives)."""
175
+ S = []
176
+ for l in links:
177
+ v, k = l["vet"], l["vet"].get("kep") or {}
178
+ why = [] if l["nights"] >= 5 else ["nights"]
179
+ if not k.get("rms", np.inf) <= near_rms_max(l["V"]) and not k.get("e", 9) > 1.1:
180
+ why.append("rms")
181
+ if k.get("e", 9) > 1.1:
182
+ t = v["times"]
183
+ arc = orbit.Arc([x[0] for x in t], [d[0] for d in l["det"]], [d[1] for d in l["det"]], 0.2, l.get("sites", site))
184
+ if not orbit.kepler_test(arc, near_rms_max(l["V"]), r_guess=l["dist_au"])["passed"]:
185
+ why.append("unbound")
186
+ v["near"] = why
187
+ if not why:
188
+ S.append(l)
189
+ U = np.array([unit(l["ra"], l["dec"]) for l in S]).reshape(-1, 3)
190
+ N = [{int(np.floor(d[2] - 0.5)) for d in l["det"]} for l in S]
191
+ for q, l in enumerate(S):
192
+ mates = sum(1 for j in np.flatnonzero(U @ U[q] > np.cos(np.radians(3))) if j != q and len(N[j] & N[q]) >= 4)
193
+ k = l["vet"]["kep"]
194
+ tno_like = k["rms"] <= 0.1 and k["e"] < 0.35 and k["i"] < 35 and 25 < k["a"] < 80
195
+ if mates >= 2 and not tno_like:
196
+ l["vet"]["near"] = ["cluster"]
197
+
198
+
199
+ def apply_vetters(doc, vetters):
200
+ """Run plugin vetters ({name: object with check(link, ctx)}, see ``plugins.Vetter``) on every link of a
201
+ vetted document. They can only add: each result goes to ``vet.plugins[name]``; a result with a true
202
+ ``veto`` lists the plugin in ``vet.veto_plugins`` and clears ``survives``. A vetter gets a copy of the
203
+ link, so it cannot change the core results; one that raises is recorded as ``{"error": ...}``."""
204
+ ctx = copy.deepcopy({k: v for k, v in doc.items() if k != "links"})
205
+ for l in doc["links"]:
206
+ res = {}
207
+ for name, p in vetters.items():
208
+ try:
209
+ r = p.check(copy.deepcopy(l), ctx)
210
+ res[name] = dict(r) if r else {}
211
+ except Exception as e:
212
+ res[name] = dict(error=f"{type(e).__name__}: {e}")
213
+ l["vet"]["plugins"] = res
214
+ bad = [n for n, r in res.items() if r.get("veto")]
215
+ if bad:
216
+ l["vet"]["veto_plugins"] = bad
217
+ l["vet"]["survives"] = False
218
+ return doc
219
+
220
+
221
+ def vet(doc, site="W84", static=True, kepler=True, ident=False, min_found_frac=0.7, cr_fwhm_ratio=0.8,
222
+ cr_margins=CR_MARGINS, cr_min_flagged=2, trail_min=5, static_radius=1.0, kepler_rms_max=0.2, workers=2, ident_backend="jpl", vetters=None, ident_two_pass=True):
223
+ """Apply all vetoes to the links of a ``link`` output document (in place) and return it.
224
+
225
+ Each link gets a ``vet`` dict with the test results, the veto flags and ``survives``; with
226
+ ident=True survivors are also matched against known objects (``known``: list of nearby objects; JPL
227
+ sb_ident, or SkyBoT with ident_backend='skybot'). ``vetters``: plugin checks run after the core
228
+ ones (``apply_vetters``)."""
229
+ box = doc["box"]
230
+ dr = (doc["params"]["dist_min"], doc["params"]["dist_max"])
231
+ nb, near = doc.get("blocks", 1), doc["params"].get("near")
232
+ if near: # near mode: the same rows as the linker (core + margin)
233
+ rows = catalog.block_orphans(tiles.tile((box[0] + box[1]) / 2, (box[2] + box[3]) / 2), tiles.tiles_in(*doc["data_box"]))
234
+ ex = catalog.exposures(box, margin=1.6 + doc["params"]["margin"])
235
+ kepler = False # near_rules replace the bound two-body test
236
+ elif nb > 1: # cross-tile link: the same merged rows, exposures around the whole block
237
+ rows = catalog.block_orphans(doc["tile"], tiles.block(doc["tile"], nb))
238
+ ex = catalog.exposures(box, margin=1.6 + nb // 2)
239
+ else:
240
+ rows = catalog.orphans(box)
241
+ ex = catalog.exposures(box)
242
+ vl = catalog.vlimit(ex)
243
+ orph = tuple(np.array([float(r[k]) for r in rows]) for k in ("ra", "dec", "mjd"))
244
+ fwo = {r["id"]: float(r["fwhm"]) for r in rows}
245
+ byid = {r["id"]: r for r in rows}
246
+ ndet = {r["id"]: int(float(r["ndet"])) for r in rows}
247
+ for l in doc["links"]:
248
+ v = l["vet"] = dict(miss=miss_test(l, orph, ex, vl, ndet, site, dr))
249
+ v["trail"] = [trail_test(d, orph, trail_min) for d in l["det"]]
250
+ v["cr"] = [cr_test(d, fwo.get(i, np.nan), ex, cr_fwhm_ratio, byid.get(i), cr_margins) for d, i in zip(l["det"], l["ids"])]
251
+ mi = v["miss"]
252
+ v["veto_miss"] = bool(mi["frac"] is not None and mi["frac"] < min_found_frac and mi["found_nights"] < mi["exp_nights"] - 1)
253
+ ncr = sum(c and not t for c, t in zip(v["cr"], v["trail"]))
254
+ bad = [c or t for c, t in zip(v["cr"], v["trail"])] if ncr >= cr_min_flagged else v["trail"]
255
+ v["veto_crtrail"] = len({int(np.floor(d[2] - 0.5)) for d, b in zip(l["det"], bad) if not b}) < 4
256
+ # one unconfirmed night is tolerated for a tight fit
257
+ v["veto_intra"] = bool(mi["intra_conf"] == 0 and (mi["intra_nights"] >= 2 or (mi["intra_nights"] == 1 and l["rms"] >= 0.15)))
258
+ v["times"] = mid_times(l["det"], ex)
259
+ if near:
260
+ arc = orbit.Arc([x[0] for x in v["times"]], [d[0] for d in l["det"]], [d[1] for d in l["det"]], 0.2, l.get("sites", site))
261
+ try:
262
+ o = orbit.free_fit(arc, l["dist_au"])
263
+ el = orbit.helio_elements(o.x0, o.v0, o.t0)
264
+ v["kep"] = dict(rms=o.rms, r=o.r, a=el["a"], e=el["e"], i=el["i"])
265
+ except Exception as e: # no fit: vetoed below
266
+ v["kep"] = dict(error=f"{type(e).__name__}: {e}")
267
+ v["veto_kep"] = not (v["kep"].get("rms", np.inf) <= NEAR_KEP_RMS and v["kep"].get("r", 0) >= NEAR_R_MIN)
268
+ v["pass_local"] = not (v["veto_miss"] or v["veto_crtrail"] or v["veto_intra"] or v.get("veto_kep"))
269
+ if near:
270
+ near_rules([l for l in doc["links"] if l["vet"]["pass_local"]], site)
271
+ for l in doc["links"]:
272
+ l["vet"]["veto_near"] = bool(l["vet"].get("near"))
273
+ l["vet"]["pass_local"] &= not l["vet"]["veto_near"]
274
+ todo = [l for l in doc["links"] if l["vet"]["pass_local"]]
275
+ if static:
276
+ with ThreadPoolExecutor(workers) as P:
277
+ for l, st in zip(todo, P.map(lambda l: static_test(l, static_radius), todo)):
278
+ l["vet"]["static"] = st
279
+ l["vet"]["veto_static"] = None if st is None else sum(st) >= 2
280
+ todo = [l for l in todo if l["vet"]["veto_static"] is False]
281
+ mode = doc["params"].get("mode")
282
+ far = mode in ("far", "multiyear") # far / multi-year: a bound fit within 0.3"; far also >= 5 nights
283
+ for l in todo:
284
+ if mode == "far" and l["nights"] < 5:
285
+ l["vet"]["veto_nights"] = True
286
+ l["vet"]["survives"] = False
287
+ continue
288
+ if kepler:
289
+ t = l["vet"]["times"]
290
+ arc = orbit.Arc([x[0] for x in t], [d[0] for d in l["det"]], [d[1] for d in l["det"]], 0.15, l.get("sites", site))
291
+ k = l["vet"]["kepler"] = orbit.kepler_test(arc, 0.3 if far else kepler_rms_max, r_guess=l["dist_au"])
292
+ l["vet"]["veto_kepler"] = not k["passed"]
293
+ l["vet"]["survives"] = not l["vet"].get("veto_kepler", False)
294
+ for l in doc["links"]:
295
+ l["vet"].setdefault("survives", False)
296
+ if vetters:
297
+ apply_vetters(doc, vetters)
298
+ for l in doc["links"]:
299
+ if ident and l["vet"]["survives"]:
300
+ k = len(l["det"]) // 2
301
+ l["vet"]["known"] = known.identify(l["det"][k][0], l["det"][k][1], l["det"][k][2], site, half_width=0.5, max_dist=1800,
302
+ backend=ident_backend, two_pass=ident_two_pass, allow=True)
303
+ doc["vetted"] = dict(static=static, kepler=kepler, ident=ident, survivors=sum(l["vet"]["survives"] for l in doc["links"]))
304
+ return doc
@@ -0,0 +1,5 @@
1
+ """Offline workflow primitives. No workers, network calls or scientific promotion."""
2
+ from .models import Artifact, CandidateRef, Job, Result
3
+ from .sqlite import Queue, Conflict, StaleLease
4
+
5
+ __all__ = ["Artifact", "CandidateRef", "Job", "Result", "Queue", "Conflict", "StaleLease"]
@@ -0,0 +1,103 @@
1
+ """Versioned JSON envelopes; large/private science data live in referenced artifacts."""
2
+ from dataclasses import asdict, dataclass, field
3
+ import hashlib
4
+ import json
5
+ import re
6
+
7
+ SCHEMA = "orbitsift.workflow/1"
8
+
9
+
10
+ def canonical(value):
11
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False)
12
+
13
+
14
+ def identifier(value):
15
+ if not isinstance(value, str) or not value.strip():
16
+ raise ValueError("identifiers must be nonempty strings")
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class CandidateRef:
21
+ namespace: str
22
+ key: str
23
+ revision: str # immutable input revision, preferably a manifest SHA256
24
+
25
+ def __post_init__(self):
26
+ for value in (self.namespace, self.key, self.revision):
27
+ identifier(value)
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Artifact:
32
+ uri: str # opaque private storage reference, never fetched automatically
33
+ sha256: str
34
+ size_bytes: int
35
+ media_type: str = "application/octet-stream"
36
+
37
+ def __post_init__(self):
38
+ identifier(self.uri)
39
+ identifier(self.media_type)
40
+ if not re.fullmatch(r"[0-9a-f]{64}", self.sha256):
41
+ raise ValueError("sha256 must be lowercase hex")
42
+ if type(self.size_bytes) is not int or self.size_bytes < 0:
43
+ raise ValueError("size_bytes must be a nonnegative integer")
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Job:
48
+ kind: str
49
+ candidate: CandidateRef
50
+ implementation: str # software/version/config identity; changes produce new jobs
51
+ parameters: dict = field(default_factory=dict)
52
+ inputs: tuple[Artifact, ...] = ()
53
+ requires: tuple[str, ...] = () # worker capabilities
54
+ dependencies: tuple[str, ...] = ()
55
+
56
+ def __post_init__(self):
57
+ identifier(self.kind)
58
+ identifier(self.implementation)
59
+ if not isinstance(self.candidate, CandidateRef) or not isinstance(self.parameters, dict):
60
+ raise ValueError("invalid candidate or parameters")
61
+ if not all(isinstance(a, Artifact) for a in self.inputs):
62
+ raise ValueError("inputs must be artifacts")
63
+ for value in (*self.requires, *self.dependencies):
64
+ identifier(value)
65
+ canonical(self.to_dict())
66
+
67
+ def to_dict(self):
68
+ return {"schema": SCHEMA, "type": "job", **asdict(self)}
69
+
70
+ @property
71
+ def id(self):
72
+ return hashlib.sha256(canonical(self.to_dict()).encode()).hexdigest()
73
+
74
+ @classmethod
75
+ def from_dict(cls, data):
76
+ data = dict(data)
77
+ if data.pop("schema", None) != SCHEMA or data.pop("type", None) != "job":
78
+ raise ValueError("unsupported workflow envelope")
79
+ data["candidate"] = CandidateRef(**data["candidate"])
80
+ data["inputs"] = tuple(Artifact(**a) for a in data.get("inputs", ()))
81
+ for name in ("requires", "dependencies"):
82
+ data[name] = tuple(data.get(name, ()))
83
+ return cls(**data)
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class Result:
88
+ """An evidence record, never an automatic discovery/novelty decision."""
89
+ summary: dict = field(default_factory=dict)
90
+ artifacts: tuple[Artifact, ...] = ()
91
+ provenance: dict = field(default_factory=dict)
92
+ review: str = "required"
93
+
94
+ def to_dict(self):
95
+ if self.review not in {"required", "not_requested"}:
96
+ raise ValueError("scientific promotion is outside the queue contract")
97
+ if not isinstance(self.summary, dict) or not isinstance(self.provenance, dict):
98
+ raise ValueError("summary and provenance must be objects")
99
+ if not all(isinstance(a, Artifact) for a in self.artifacts):
100
+ raise ValueError("artifacts must be Artifact records")
101
+ value = {"schema": SCHEMA, "type": "result", **asdict(self)}
102
+ canonical(value)
103
+ return value