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/known.py ADDED
@@ -0,0 +1,716 @@
1
+ """Known objects: small-body identification (JPL sb_ident, or IMCCE SkyBoT) and JPL Horizons ephemerides.
2
+
3
+ Always check survivors against known objects with a *wide* search: objects with poor orbits can be
4
+ degrees away from their nominal prediction after a decade.
5
+ """
6
+ import json
7
+ import re
8
+ import time
9
+ import urllib.parse
10
+
11
+ import numpy as np
12
+
13
+ from . import net
14
+
15
+ SB_IDENT = "https://ssd-api.jpl.nasa.gov/sb_ident.api"
16
+ SKYBOT = "https://ssp.imcce.fr/webservices/skybot/api/conesearch.php"
17
+ HORIZONS = "https://ssd.jpl.nasa.gov/api/horizons.api"
18
+
19
+
20
+ def _sexa(x):
21
+ sg = "-" if x < 0 else ""
22
+ t = round(abs(x) * 36000) # tenths of a second: never prints 60.0
23
+ return f"{sg}{t // 36000:02d}-{t // 600 % 60:02d}-{t % 600 / 10:04.1f}"
24
+
25
+
26
+ def _deg(s, hours=False):
27
+ """Sexagesimal 'hh mm ss.s' / '+dd:mm:ss' (any separators) -> degrees."""
28
+ v = [float(x) for x in re.findall(r"\d+(?:\.\d*)?", s)][:3]
29
+ x = v[0] + (v[1] if len(v) > 1 else 0) / 60 + (v[2] if len(v) > 2 else 0) / 3600
30
+ return (-x if s.strip().startswith("-") else x) * (15 if hours else 1)
31
+
32
+
33
+ def _sep(ra1, dec1, ra2, dec2):
34
+ """Angular distance [arcsec]."""
35
+ r = np.radians
36
+ c = np.sin(r(dec1)) * np.sin(r(dec2)) + np.cos(r(dec1)) * np.cos(r(dec2)) * np.cos(r(ra1 - ra2))
37
+ return float(np.degrees(np.arccos(np.clip(c, -1, 1))) * 3600)
38
+
39
+
40
+ def identify(ra, dec, mjd_utc, site="W84", half_width=0.05, max_dist=300.0, backend="jpl", two_pass=False, allow=False):
41
+ """Known small bodies near (ra, dec) [deg] at a UTC MJD seen from an MPC site.
42
+
43
+ half_width: half size of the search box [deg]; max_dist: keep objects within this many arcsec.
44
+ Returns [(name, distance from centre ["], V)], nearest first. backend 'jpl': the two-body first pass
45
+ of sb_ident (~1' accuracy for a TNO a decade from its orbit epoch; can take minutes per field);
46
+ 'skybot': IMCCE SkyBoT cone search of radius half_width x sqrt(2) (seconds; same kind of answer).
47
+ two_pass (jpl): sb_ident's second pass, a numerical integration of every object beyond 5.5 AU to the epoch (exact to
48
+ ~0.1" where the first pass can be off by arcminutes; slower).
49
+
50
+ Unless net.OUTBOUND is "exact", the service is asked about the whole 1 deg tile holding (ra, dec) (``net.snap``,
51
+ box/cone grown to cover the caller's), and objects are kept here by their distance from (ra, dec). The service
52
+ still learns the tile and the epoch: only with ``allow`` (the caller's per-run flag; ``net.require``)."""
53
+ if backend not in ("jpl", "skybot"):
54
+ raise ValueError(f"unknown identify backend {backend!r}")
55
+ net.require("ident", allow)
56
+ qra, qdec, grow = (ra, dec, 0.0) if net.exact() else net.snap(ra, dec)
57
+ if backend == "skybot":
58
+ return _skybot(ra, dec, qra, qdec, mjd_utc, site, half_width * 2 ** 0.5, grow, max_dist)
59
+ hw = round(half_width + grow, 3) if grow else half_width # RA half width grown by 1/cos(Dec): covers the cell in either convention
60
+ rhw = round(hw / np.cos(np.radians(min(89.0, abs(qdec) + grow))), 3) if grow else hw
61
+ q = urllib.parse.urlencode({"mpc-code": site, "obs-time": f"{mjd_utc + 2400000.5:.5f}",
62
+ "fov-ra-center": _sexa(qra / 15), "fov-dec-center": _sexa(qdec),
63
+ "fov-ra-hwidth": rhw, "fov-dec-hwidth": hw,
64
+ **({"two-pass": "true", "suppress-first-pass": "true", "mag-required": "false",
65
+ "sb-cdata": json.dumps({"AND": ["a|GT|5.5"]})} if two_pass else {})})
66
+ r = json.loads(net.fetch(f"{SB_IDENT}?{q}", timeout=600))
67
+ k = "second" if two_pass else "first"
68
+ f = r.get(f"fields_{k}", [])
69
+ rows = [dict(zip(f, x)) for x in r.get(f"data_{k}_pass", [])]
70
+ ka, kd = (next(c for c in f if c.startswith(p)) for p in ("Astrometric RA", "Astrometric Dec")) if rows else (None, None)
71
+ out = []
72
+ for x in rows:
73
+ a, d = _deg(x[ka], hours=True), _deg(x[kd])
74
+ dra = ((a - ra + 180) % 360 - 180) * np.cos(np.radians(dec))
75
+ if abs(dra) <= half_width and abs(d - dec) <= half_width and _sep(a, d, ra, dec) < max_dist: # the caller's box
76
+ out.append((x["Object name"].strip(), round(_sep(a, d, ra, dec), 2), x.get("Visual magnitude (V)")))
77
+ return sorted(out, key=lambda x: x[1])
78
+
79
+
80
+ def _skybot(ra, dec, qra, qdec, mjd_utc, site, radius, grow, max_dist):
81
+ q = urllib.parse.urlencode({"-ep": f"{mjd_utc + 2400000.5:.6f}", "-ra": f"{qra:.7f}", "-dec": f"{qdec:.7f}",
82
+ "-rd": f"{radius + grow:.5f}", "-mime": "text", "-output": "basic", "-loc": site, "-filter": "0",
83
+ "-objFilter": "111", "-refsys": "EQJ2000", "-from": "orbitsift"})
84
+ out = []
85
+ for line in net.fetch(f"{SKYBOT}?{q}", timeout=300).decode(errors="replace").splitlines():
86
+ c = [x.strip() for x in line.split("|")]
87
+ if line.startswith("#") or len(c) < 8:
88
+ continue # Num | Name | RA | DE | Class | Mv | Err | d(arcsec) | ...
89
+ name = c[1] if c[0] in ("-", "") else f"{c[0]} ({c[1]})"
90
+ d = _sep(_deg(c[2], hours=True), _deg(c[3]), ra, dec)
91
+ if d < max_dist and d <= radius * 3600:
92
+ out.append((name, round(d, 3), c[5]))
93
+ return sorted(out, key=lambda x: x[1])
94
+
95
+
96
+ def horizons(target, mjd_utc, site="W84"):
97
+ """Astrometric RA, Dec [deg], distance [AU] and V of ``target`` (Horizons COMMAND syntax, e.g.
98
+ '2011 MV11;' or 'DES=2014 UZ224;') at UTC MJDs -> array (n, 4)."""
99
+ mjd_utc = np.atleast_1d(np.asarray(mjd_utc, float))
100
+ order = np.argsort(mjd_utc)
101
+ out = []
102
+ for k in range(0, len(mjd_utc), 40): # Horizons TLIST: keep URLs short
103
+ m = mjd_utc[order][k:k + 40]
104
+ p = {"format": "json", "COMMAND": f"'{target}'", "CENTER": f"'{site}'", "EPHEM_TYPE": "OBSERVER",
105
+ "TLIST": " ".join(f"{x + 2400000.5:.6f}" for x in m), "TIME_TYPE": "UT", "QUANTITIES": "'1,9,20'",
106
+ "CSV_FORMAT": "YES", "ANG_FORMAT": "DEG", "OBJ_DATA": "NO", "EXTRA_PREC": "YES"}
107
+ res = json.loads(net.fetch(f"{HORIZONS}?{urllib.parse.urlencode(p)}", timeout=120))["result"]
108
+ if "$$SOE" not in res:
109
+ raise net.ServiceError("Horizons: " + res[:500])
110
+ for line in res.split("$$SOE")[1].split("$$EOE")[0].strip().splitlines():
111
+ c = [x.strip() for x in line.split(",")]
112
+ out.append([float(c[3]), float(c[4]), float(c[7]), float(c[5]) if c[5] not in ("", "n.a.") else np.nan])
113
+ out = np.array(out)
114
+ return out[np.argsort(order)]
115
+
116
+
117
+ SBDB_QUERY = "https://ssd-api.jpl.nasa.gov/sbdb_query.api"
118
+ SBDB_FIELDS = ("full_name", "e", "q", "i", "om", "w", "ma", "epoch", "data_arc", "condition_code")
119
+
120
+
121
+ def sbdb_outer(refresh=False):
122
+ """Every TNO and Centaur in JPL's SBDB, one-opposition orbits included: rows of SBDB_FIELDS (heliocentric ecliptic
123
+ elements at each object's own epoch, JD TDB). Cached in <cache>/known/sbdb_outer.json; refresh=True downloads again
124
+ (recent discoveries appear every week)."""
125
+ from . import config
126
+ path = config.cache_dir() / "known" / "sbdb_outer.json"
127
+ if refresh or not path.exists():
128
+ q = urllib.parse.urlencode({"fields": ",".join(SBDB_FIELDS), "sb-class": "TNO,CEN"})
129
+ r = json.loads(net.fetch(f"{SBDB_QUERY}?{q}", timeout=600))
130
+ path.parent.mkdir(parents=True, exist_ok=True)
131
+ net.save(path, json.dumps(dict(fields=r["fields"], data=r["data"])))
132
+ d = json.loads(path.read_text())
133
+ return [dict(zip(d["fields"], row)) for row in d["data"]]
134
+
135
+
136
+ def _sun_many(jd):
137
+ from astropy.coordinates import get_body_barycentric
138
+ from astropy.time import Time
139
+ return get_body_barycentric("sun", Time(np.asarray(jd, float), format="jd", scale="tdb")).xyz.to("au").value.T
140
+
141
+
142
+ def screen(states, t0, rows=None, margin_deg=0.05, max_dr=2.0):
143
+ """Inverse identity screen: every catalogue orbit (``rows``, default ``sbdb_outer()``) is placed where its own elements
144
+ put it at its own epoch, and compared with ``states`` (nominal first, then clones; barycentric equatorial at t0 JD
145
+ TDB, e.g. ``orbit.sample``) propagated (two-body) to that epoch, seen from the Sun. A hit is within the clones' 99%
146
+ angle + ``margin_deg`` of the nominal direction and within ``max_dr`` AU in distance: no ephemeris error enters, so
147
+ it catches objects whose short-arc orbits put them far from a backward check (recent discoveries).
148
+ -> hits [dict(name, ang_deg, cloud99_deg, dr_au, epoch, arc_days, U)], nearest first."""
149
+ from . import orbit
150
+ rows = sbdb_outer() if rows is None else rows
151
+ num = lambda r, k: float(r[k]) if r.get(k) not in (None, "") else np.nan
152
+ ok = [r for r in rows if num(r, "e") < 0.995 and np.isfinite(num(r, "ma")) and np.isfinite(num(r, "epoch"))]
153
+ if not ok:
154
+ return []
155
+ ep = np.array([num(r, "epoch") for r in ok])
156
+ P = np.array([orbit.state_from_elements(num(r, "q") / (1 - num(r, "e")), num(r, "e"), num(r, "i"), num(r, "om"), num(r, "w"),
157
+ num(r, "ma"), num(r, "epoch"))[:3] for r in ok])
158
+ ue, inv = np.unique(ep, return_inverse=True)
159
+ S = np.atleast_2d(states)
160
+ sun = _sun_many(ue)
161
+ Q = orbit.kepler(S[:, :3], S[:, 3:], ue - t0) - sun[None] # (k, n_epochs, 3) heliocentric
162
+ Q = Q[:, inv]
163
+ P = P - sun[inv]
164
+ nq, nr = np.linalg.norm(Q, axis=2), np.linalg.norm(P, axis=1)
165
+ ang = np.degrees(np.arccos(np.clip((Q[0] * P).sum(1) / (nq[0] * nr), -1, 1)))
166
+ cl = np.degrees(np.arccos(np.clip((Q * Q[:1]).sum(2) / (nq * nq[:1]), -1, 1)))
167
+ spread = np.percentile(cl, 99, axis=0) if len(S) > 1 else np.zeros(len(ok))
168
+ dr = np.abs(nq - nr[None]).min(0)
169
+ hit = np.flatnonzero((ang < spread + margin_deg) & (dr < max_dr))
170
+ out = [dict(name=ok[j]["full_name"].strip(), ang_deg=float(ang[j]), cloud99_deg=float(spread[j]), dr_au=float(dr[j]),
171
+ epoch=float(ep[j]), arc_days=num(ok[j], "data_arc"), U=ok[j].get("condition_code")) for j in hit]
172
+ return sorted(out, key=lambda x: x["ang_deg"])
173
+
174
+
175
+ def forward(states, t0, mjd_utc, site="500", backend="jpl", allow=False):
176
+ """Forward check: predict the nominal orbit and clones (``states`` at t0, as in ``screen``) to a recent date
177
+ ``mjd_utc`` and list the known objects inside the clones' 99% extent + 70" (sb_ident second pass, or SkyBoT).
178
+ -> dict(ra, dec, ext99_arcsec, half_width_deg, known=[(name, distance ["], V)])."""
179
+ from . import orbit
180
+ ra, dec = orbit.predict(np.atleast_2d(states), t0, np.array([mjd_utc]), site)
181
+ ra, dec = ra[:, 0], dec[:, 0]
182
+ sep = np.hypot(((ra - ra[0] + 180) % 360 - 180) * np.cos(np.radians(dec[0])), dec - dec[0]) * 3600
183
+ ext = float(np.percentile(sep, 99)) if len(sep) > 1 else 0.0
184
+ hw = min(1.5, max(0.05, (ext + 70) / 3600))
185
+ k = identify(float(ra[0]), float(dec[0]), mjd_utc, site, half_width=hw, max_dist=ext + 70, backend=backend, two_pass=True,
186
+ allow=allow)
187
+ return dict(ra=float(ra[0]), dec=float(dec[0]), ext99_arcsec=ext, half_width_deg=hw, known=k)
188
+
189
+
190
+ # ---------------------------------------------------------------- the check at the designated objects' own epochs
191
+ # A cone at OUR epochs misses designated objects with arcs of days to weeks: their ephemeris years away is off by far
192
+ # more than any cone. ``check`` goes the other way round: OUR orbit is propagated to THEIR observed interval and
193
+ # compared there with their MPC orbit (bulk files, local), then linked locally, then decided with their published
194
+ # astrometry (MPC get-obs by designation) in a joint fit. Nothing about the user's objects is sent anywhere: the only
195
+ # requests are the bulk catalogue downloads and get-obs queries by the designation of already-designated objects.
196
+ MPC_URLS = {"Distant.txt": "https://minorplanetcenter.net/iau/MPCORB/Distant.txt",
197
+ "MPCORB.DAT.gz": "https://minorplanetcenter.net/iau/MPCORB/MPCORB.DAT.gz"}
198
+ GET_OBS = "https://data.minorplanetcenter.net/api/get-obs"
199
+ CHECK = dict(clones=40, chi=5.0, sig_floor_deg=0.01, near_deg=5.0, b_deg=0.3, pole_deg=1.0, link_starts=20, link_rms=2.0,
200
+ link_max=5.0, match_used=0.9, match_rms=0.4, match_max=1.5, loose_their_frac=0.8, their_sigma=0.3, Q_min=5.0,
201
+ gate_q=2.0, gate_Q=0.5, dup_dt=120.0, dup_sep=2.0, orbit_gate=600.0, same_dt_s=5.0, same_sep=1.0,
202
+ robust_their_frac=0.95, robust_used=0.8, rows_multi_deg=0.5, rows_single_deg=15.0, rows_n=15)
203
+ _UNP = {c: k for k, c in enumerate("0123456789ABCDEFGHIJKLMNOPQRSTUV")}
204
+
205
+
206
+ def mpc_file(name="Distant.txt", refresh=False, max_age_days=1.0):
207
+ """Path of an MPC bulk orbit file (``MPC_URLS``) in <cache>/known, downloaded again when older than ``max_age_days``
208
+ (new designations and orbits appear with every Daily Orbit Update) or with refresh=True."""
209
+ from . import config
210
+ path = config.cache_dir() / "known" / name
211
+ if refresh or not path.exists() or time.time() - path.stat().st_mtime > max_age_days * 86400:
212
+ b = net.fetch(MPC_URLS[name], timeout=1800)
213
+ if (name.endswith(".gz") and b[:2] != b"\x1f\x8b") or (not name.endswith(".gz") and len(b.split(b"\n", 1)[0]) < 200):
214
+ raise net.ServiceError(f"MPC {name}: unexpected answer " + repr(b[:200]))
215
+ path.parent.mkdir(parents=True, exist_ok=True)
216
+ net.save(path, b)
217
+ return path
218
+
219
+
220
+ def _jd_ymd(y, m, d):
221
+ """Calendar dates (integer arrays) -> JD at 12h."""
222
+ y, m, d = (np.asarray(x, int) for x in (y, m, d))
223
+ t = (np.asarray(y - 1970, "datetime64[Y]").astype("datetime64[M]") + (m - 1)).astype("datetime64[D]") + (d - 1)
224
+ return (t - np.datetime64("1858-11-17")).astype(float) + 2400001.0
225
+
226
+
227
+ def mpc_orbits(paths, Q_min=CHECK["Q_min"]):
228
+ """MPC orbits of MPCORB-format files (Distant.txt, MPCORB.DAT[.gz]) as arrays: name, desig (what get-obs takes),
229
+ packed, src, epoch (JD TT), a e i node peri M (heliocentric ecliptic J2000), U, ref, nobs, nopp, arc, ts (n, 3)
230
+ = first, middle and last date of the observed arc (JD), X = barycentric equatorial states at epoch. Every orbit with
231
+ aphelion Q = a (1 + e) >= ``Q_min`` AU is kept, from every file (no cut by rate of motion: a slow mover's orbit can
232
+ sit in MPCORB); an object in several files is kept once."""
233
+ import gzip
234
+ lines, src, seen = [], [], set()
235
+ for p in paths:
236
+ op = gzip.open if str(p).endswith(".gz") else open
237
+ with op(p, "rb") as f:
238
+ for ln in f:
239
+ if len(ln) < 202 or ln[:1] == b"-" or ln[25:26] != b" " or not ln[20:25].strip() or ln[:7] in seen:
240
+ continue
241
+ if not (_num(ln[92:103]) * (1 + _num(ln[70:79])) >= Q_min):
242
+ continue
243
+ seen.add(ln[:7])
244
+ lines.append(ln[:202])
245
+ src.append(str(p).replace("\\", "/").rsplit("/", 1)[-1])
246
+ B = np.array(lines, "S202").view("S1").reshape(-1, 202)
247
+ col = lambda a, b: B[:, a:b].copy().view(f"S{b - a}").ravel()
248
+ num = lambda a, b: np.where(np.char.strip(col(a, b)) == b"", b"nan", col(a, b)).astype(float)
249
+ a, e = num(92, 103), num(70, 79)
250
+ ok = (a > 0) & (e >= 0) & (e < 0.995)
251
+ pe, inv = np.unique(col(20, 25).astype(str), return_inverse=True) # packed epochs, at 0h TT
252
+ ep = _jd_ymd(*np.array([[100 * _UNP[x[0]] + int(x[1:3]), _UNP[x[3]], _UNP[x[4]]] for x in pe]).T)[inv] - 0.5
253
+ last = _jd_ymd(num(194, 198), num(198, 200), num(200, 202))
254
+ arc = np.char.strip(col(127, 136)).astype(str)
255
+ days = np.char.endswith(arc, "days") # 'nnnn days', else 'yyyy-yyyy'
256
+ n_days = np.where(days, np.char.partition(arc, " ")[:, 0], "nan").astype(float)
257
+ y1 = np.where(days, "nan", np.char.partition(arc, "-")[:, 0]).astype(float)
258
+ first = np.where(days, last - n_days, np.minimum(last, _jd_ymd(np.nan_to_num(y1, nan=2000), 7, 1)))
259
+ name = np.char.strip(col(166, 194)).astype(str)
260
+ out = dict(name=name, desig=np.array([n[1:n.index(")")] if n.startswith("(") else n for n in name]),
261
+ packed=np.char.strip(col(0, 7)).astype(str), src=np.array(src), epoch=ep, a=a, e=e, i=num(59, 68),
262
+ node=num(48, 57), peri=num(37, 46), M=num(26, 35), U=np.char.strip(col(105, 106)).astype(str),
263
+ ref=np.char.strip(col(107, 116)).astype(str), nobs=num(117, 122), nopp=num(123, 126), arc=arc,
264
+ ts=np.c_[first, (first + last) / 2, last])
265
+ out = {k: v[ok] for k, v in out.items()}
266
+ out["X"] = _states(out)
267
+ return out
268
+
269
+
270
+ def _num(b):
271
+ try:
272
+ return float(b)
273
+ except ValueError:
274
+ return np.nan
275
+
276
+
277
+ def _states(m):
278
+ """Barycentric equatorial states (n, 6) at each epoch of heliocentric ecliptic elements (vectorised; the Sun's
279
+ barycentric state from astropy at the distinct epochs)."""
280
+ from astropy.coordinates import get_body_barycentric_posvel
281
+ from astropy.time import Time
282
+
283
+ from . import orbit
284
+ i, node, peri, M, a, e = np.radians(m["i"]), np.radians(m["node"]), np.radians(m["peri"]), np.radians(m["M"]), m["a"], m["e"]
285
+ E = M.copy()
286
+ for _ in range(50):
287
+ E = E - (E - e * np.sin(E) - M) / (1 - e * np.cos(E))
288
+ cO, sO, cw, sw, ci, si = np.cos(node), np.sin(node), np.cos(peri), np.sin(peri), np.cos(i), np.sin(i)
289
+ P = np.stack([cO * cw - sO * sw * ci, sO * cw + cO * sw * ci, sw * si], -1)
290
+ Q = np.stack([-cO * sw - sO * cw * ci, -sO * sw + cO * cw * ci, cw * si], -1)
291
+ n, den = np.sqrt(orbit.GM_SUN / a ** 3), 1 - e * np.cos(E)
292
+ x = (a * (np.cos(E) - e))[:, None] * P + (a * np.sqrt(1 - e * e) * np.sin(E))[:, None] * Q
293
+ v = (-a * n * np.sin(E) / den)[:, None] * P + (a * n * np.sqrt(1 - e * e) * np.cos(E) / den)[:, None] * Q
294
+ ue, inv = np.unique(m["epoch"], return_inverse=True)
295
+ p, w = get_body_barycentric_posvel("sun", Time(ue, format="jd", scale="tt"))
296
+ return np.c_[x @ orbit.ECL + p.xyz.to("au").value.T[inv], v @ orbit.ECL + w.xyz.to("au/d").value.T[inv]]
297
+
298
+
299
+ def _earth(jd):
300
+ """Barycentric position of the geocentre (..., 3) at JD (TDB) values (any shape)."""
301
+ import warnings
302
+
303
+ from astropy.coordinates import get_body_barycentric
304
+ from astropy.time import Time
305
+ from erfa import ErfaWarning
306
+ jd = np.asarray(jd, float)
307
+ u, inv = np.unique(np.round(jd.ravel(), 6), return_inverse=True)
308
+ with warnings.catch_warnings(): # first dates of old objects lie before 1900 ("dubious year")
309
+ warnings.simplefilter("ignore", ErfaWarning)
310
+ p = get_body_barycentric("earth", Time(u, format="jd", scale="tdb")).xyz.to("au").value.T
311
+ return p[inv].reshape(jd.shape + (3,))
312
+
313
+
314
+ def _radec_own(X, t0, jd, obs):
315
+ """Geocentric astrometric RA, Dec [deg] (k, m) of k states X, each at its own epoch t0 (k,), at times jd (k, m)."""
316
+ from . import orbit
317
+ lt = 0.0
318
+ for _ in range(3):
319
+ p = orbit.kepler(X[:, :3], X[:, 3:], jd - t0[:, None] - lt) - obs
320
+ d = np.linalg.norm(p, axis=-1)
321
+ lt = d / orbit.C_AU_D
322
+ return np.degrees(np.arctan2(p[..., 1], p[..., 0])) % 360, np.degrees(np.arcsin(p[..., 2] / d))
323
+
324
+
325
+ def _sep_deg(a1, d1, a2, d2):
326
+ a1, d1, a2, d2 = map(np.radians, (a1, d1, a2, d2))
327
+ return np.degrees(np.arccos(np.clip(np.sin(d1) * np.sin(d2) + np.cos(d1) * np.cos(d2) * np.cos(a1 - a2), -1, 1)))
328
+
329
+
330
+ def _pole(x, v):
331
+ h = np.cross(x, v)
332
+ return h / np.linalg.norm(h, axis=-1, keepdims=True)
333
+
334
+
335
+ def screen_epochs(o, S, arc, C, rules=CHECK):
336
+ """The screen. A (the decisive direction): our orbit ``o`` at each catalogue object's first, middle and last arc
337
+ date against its MPC orbit there, chi = separation / (rms of our clones ``S`` + 0.01 deg) < 5 at all three.
338
+ B: its MPC orbit within 0.3 deg of our first, middle and last row. C: orbit poles within 1 deg and A separation
339
+ < 5 deg (coplanar). -> [pair dicts] for A, B or C."""
340
+ from . import orbit
341
+ k = len(C["epoch"])
342
+ if not k:
343
+ return []
344
+ jd = C["ts"] + 69.184 / 86400 # UTC-ish dates -> TDB (screening accuracy)
345
+ E = _earth(jd)
346
+ ra0, de0 = orbit.radec(o.x0, o.v0, o.t0, jd.ravel(), E.reshape(-1, 3))
347
+ ra0, de0 = ra0[0].reshape(k, 3), de0[0].reshape(k, 3)
348
+ rt, dt = _radec_own(C["X"], C["epoch"], jd, E) # their orbit at their own dates
349
+ sA = _sep_deg(ra0, de0, rt, dt)
350
+ pole = np.degrees(np.arccos(np.clip(_pole(C["X"][:, :3], C["X"][:, 3:]) @ _pole(o.x0, o.v0), -1, 1)))
351
+ near = np.flatnonzero((sA.min(1) < rules["near_deg"]) | (pole < rules["pole_deg"]))
352
+ if not len(near):
353
+ return []
354
+ Sc = S[1:]
355
+ rc, dc = orbit.radec(Sc[:, :3], Sc[:, 3:], o.t0, jd[near].ravel(), E[near].reshape(-1, 3))
356
+ sig = np.sqrt(np.mean(_sep_deg(rc, dc, ra0[near].ravel(), de0[near].ravel()) ** 2, 0)).reshape(-1, 3)
357
+ chi = sA[near] / (sig + rules["sig_floor_deg"])
358
+ o3 = np.argsort(arc.mjd)[[0, len(arc.mjd) // 2, -1]]
359
+ jo = np.broadcast_to(arc.jd[o3], (len(near), 3))
360
+ rb, db = _radec_own(C["X"][near], C["epoch"][near], jo, np.broadcast_to(arc.obs[o3], (len(near), 3, 3)))
361
+ sB = _sep_deg(rb, db, arc.ra[o3], arc.dec[o3])
362
+ out = []
363
+ for j, n in enumerate(near):
364
+ A, B, Cp = chi[j].max() < rules["chi"], sB[j].max() < rules["b_deg"], pole[n] < rules["pole_deg"] and sA[n].min() < rules["near_deg"]
365
+ if A or B or Cp:
366
+ out.append(dict(k=int(n), name=str(C["name"][n]), desig=str(C["desig"][n]), src=str(C["src"][n]), A=bool(A), B=bool(B),
367
+ C=bool(Cp), chiA=round(float(chi[j].max()), 2), sepA_deg=sA[n].round(4).tolist(),
368
+ sigA_deg=sig[j].round(4).tolist(), sepB_deg=sB[j].round(4).tolist(), pole_deg=round(float(pole[n]), 3),
369
+ their=dict(a=float(C["a"][n]), e=float(C["e"][n]), i=float(C["i"][n]), arc=str(C["arc"][n]),
370
+ nopp=float(C["nopp"][n]), nobs=float(C["nobs"][n]), U=str(C["U"][n]), ref=str(C["ref"][n]))))
371
+ return out
372
+
373
+
374
+ def screen_rows(o, arc, C, rules=CHECK):
375
+ """Screen B2: EVERY catalogue orbit propagated (two-body) from its own epoch to OUR row epochs, its largest separation
376
+ from our measured positions. screen_epochs tests B only for orbits already near by A (5 deg at their dates) or by
377
+ the pole (1 deg), so a short arc of ours, whose extrapolation to their dates is degrees off, never reaches B (the
378
+ survey's check missed 2015 KJ176, (523643) 2010 TY53, 2014 WB626 and others that way, 23 Nov 2026). Kept: the
379
+ ``rows_n`` nearest multi-opposition orbits within ``rows_multi_deg``, the ``rows_n`` nearest one-opposition orbits
380
+ within ``rows_single_deg`` (a 29-day orbit sits degrees off in two-body years later) and the ``rows_n`` one-opposition
381
+ orbits of that radius closest to our orbit pole (a lost orbit 4.7 deg off, 17th by distance, was 2nd by pole).
382
+ -> [dict(k, name, desig, src, sepB2_deg, pick "multi" | "single" | "pole")]."""
383
+ k = len(C["epoch"])
384
+ if not k:
385
+ return []
386
+ sb = _sep_deg(*_radec_own(C["X"], C["epoch"], np.broadcast_to(arc.jd, (k, len(arc))),
387
+ np.broadcast_to(arc.obs, (k,) + arc.obs.shape)), arc.ra, arc.dec).max(1)
388
+ single, order = C["nopp"] <= 1, np.argsort(sb)
389
+ pick = {int(j): "multi" for j in order[~single[order] & (sb[order] < rules["rows_multi_deg"])][:rules["rows_n"]]}
390
+ near1 = single & (sb < rules["rows_single_deg"])
391
+ pick |= {int(j): "single" for j in order[near1[order]][:rules["rows_n"]]}
392
+ pole = np.degrees(np.arccos(np.clip(_pole(C["X"][:, :3], C["X"][:, 3:]) @ _pole(o.x0, o.v0), -1, 1)))
393
+ by_pole = np.argsort(pole)
394
+ for j in [int(j) for j in by_pole[near1[by_pole]] if int(j) not in pick][:rules["rows_n"]]:
395
+ pick[j] = "pole"
396
+ return [dict(k=j, name=str(C["name"][j]), desig=str(C["desig"][j]), src=str(C["src"][j]), sepB2_deg=round(float(sb[j]), 4), pick=w)
397
+ for j, w in sorted(pick.items(), key=lambda x: sb[x[0]])]
398
+
399
+
400
+ def _at(X, t0, t):
401
+ """States X (k, 6) at epochs t0 (k,) propagated (two-body) to one time t -> (k, 6)."""
402
+ from . import orbit
403
+ h = 1e-3
404
+ P = orbit.kepler(X[:, :3], X[:, 3:], (t - np.asarray(t0, float))[:, None] + np.array([-h, 0.0, h]))
405
+ return np.c_[P[:, 1], (P[:, 2] - P[:, 0]) / (2 * h)]
406
+
407
+
408
+ def _fit_from(a, starts):
409
+ """Best (by rms) free 6-parameter fit of arc a from several (x0, v0) starts -> (rms ["], per-row residuals ["], x, v)."""
410
+ best = None
411
+ for x0, v0 in starts:
412
+ try:
413
+ p, _ = a.fit6(a.to_p6(np.asarray(x0), np.asarray(v0)))
414
+ except (ValueError, FloatingPointError):
415
+ continue
416
+ x, v = a.from_p6(p)
417
+ r = a.residuals(x, v) * np.r_[a.sigma, a.sigma]
418
+ rr = np.hypot(r[:len(a)], r[len(a):])
419
+ rms = float(np.sqrt(np.mean(rr ** 2)))
420
+ if np.isfinite(rms) and (best is None or rms < best[0]):
421
+ best = (rms, rr, x, v)
422
+ return best
423
+
424
+
425
+ def link(arc, o, S, C, k, rules=CHECK):
426
+ """Local linkage pre-test (no download): our rows plus 5 positions of the MPC orbit inside its own arc, one free
427
+ two-body fit from our orbit, ``link_starts`` clones and their orbit moved to our epoch. Linkable: rms < 2" and every
428
+ row < 5". -> dict(rms, max, ours_max, theirs_max, linkable, x, v)."""
429
+ ts = np.linspace(C["ts"][k, 0], C["ts"][k, 2], 5)
430
+ jd = ts + 69.184 / 86400
431
+ r, d = _radec_own(C["X"][k:k + 1], C["epoch"][k:k + 1], jd[None], _earth(jd)[None])
432
+ a = arc.extend(ts - 2400000.5, r[0], d[0], sigma=float(np.median(arc.sigma)), site="500")
433
+ th = _at(C["X"][k:k + 1], C["epoch"][k:k + 1], arc.t0)[0]
434
+ best = _fit_from(a, [(o.x0, o.v0)] + [(s[:3], s[3:]) for s in S[1:1 + rules["link_starts"]]] + [(th[:3], th[3:])])
435
+ if best is None:
436
+ return dict(rms=None, linkable=False)
437
+ rms, rr, x, v = best
438
+ n = len(arc)
439
+ return dict(rms=round(rms, 3), max=round(float(rr.max()), 2), ours_max=round(float(rr[:n].max()), 2),
440
+ theirs_max=round(float(rr[n:].max()), 2), linkable=bool(rms < rules["link_rms"] and rr.max() < rules["link_max"]), x=x, v=v)
441
+
442
+
443
+ def get_obs(desig, refresh=False):
444
+ """Published astrometry of a designated object (MPC get-obs, ADES_DF rows), cached in <cache>/known/getobs. Only the
445
+ designation is sent."""
446
+ from . import config
447
+ path = config.cache_dir() / "known" / "getobs" / (desig.replace(" ", "_").replace("/", "_") + ".json")
448
+ if refresh or not path.exists():
449
+ b = net.fetch(GET_OBS, json.dumps({"desigs": [desig], "output_format": ["ADES_DF"]}).encode(),
450
+ {"Content-Type": "application/json"}, timeout=300, method="GET")
451
+ try:
452
+ rows = json.loads(b)[0]["ADES_DF"]
453
+ except (ValueError, LookupError, TypeError):
454
+ raise net.ServiceError(f"MPC get-obs {desig}: unexpected answer " + repr(b[:200])) from None
455
+ path.parent.mkdir(parents=True, exist_ok=True)
456
+ net.save(path, json.dumps(rows))
457
+ return json.loads(path.read_text())
458
+
459
+
460
+ def their_rows(rows, sigma=CHECK["their_sigma"]):
461
+ """Optical positions of ADES_DF rows from fixed ground stations -> dicts mjd, ra, dec, sig, stn (rmsRA/rmsDec as
462
+ in ades.read). Roving and space-based stations (no fixed position in the MPC list) are left out."""
463
+ from astropy.time import Time
464
+
465
+ from . import orbit
466
+ out = []
467
+ for r in rows:
468
+ if r.get("Obstype", "optical") != "optical" or r.get("mode") in ("RAD", "OCC") or not r.get("ra") or not r.get("dec"):
469
+ continue
470
+ try:
471
+ lon, rc, rs = orbit.site_constants(r["stn"])
472
+ except ValueError:
473
+ continue
474
+ if rc == rs == 0 and r["stn"] != "500":
475
+ continue
476
+ s = max(float(r.get("rmsra") or sigma), float(r.get("rmsdec") or sigma))
477
+ out.append(dict(mjd=float(Time(r["obstime"].rstrip("Z").replace(" ", "T"), scale="utc").mjd), ra=float(r["ra"]), dec=float(r["dec"]),
478
+ sig=s, rmsRA=s, rmsDec=s, stn=r["stn"], astCat=r.get("astcat") or "UNK"))
479
+ return sorted(out, key=lambda x: x["mjd"])
480
+
481
+
482
+ def same_exposure(arc, T, rules=CHECK):
483
+ """Published rows ``T`` (``their_rows``) that are OUR detections of the same exposure: same station, mid-times within
484
+ ``same_dt_s`` and positions within ``same_sep`` arcsec of one of our rows. -> (the other published rows, [(k, our index,
485
+ sep)] of the dropped ones). Such a pair is ONE observation: our row is kept (it is the row under test, measured on the
486
+ image), the published one is dropped, and every "rows used" rule of ``joint`` (>= 90 % match, < 80 % seeding) is
487
+ applied to the merged set. Given both, Find_Orb sets the two observations at the same second aside and a true identity
488
+ fails the 90 % rule (2016 GR397, 22 Nov 2026: 28/46 used)."""
489
+ keep, shared = [], []
490
+ for k, t in enumerate(T):
491
+ m = np.flatnonzero((arc.site == t["stn"]) & (np.abs(arc.mjd - t["mjd"]) * 86400 <= rules["same_dt_s"]))
492
+ sp = [_sep(arc.ra[j], arc.dec[j], t["ra"], t["dec"]) for j in m]
493
+ j = int(np.argmin(sp)) if sp else None
494
+ if j is not None and sp[j] <= rules["same_sep"]:
495
+ shared.append((k, int(m[j]), round(float(sp[j]), 3)))
496
+ else:
497
+ keep.append(t)
498
+ return keep, shared
499
+
500
+
501
+ def joint(arc, o, rows, start=None, backend="internal", our_obs=None, rules=CHECK):
502
+ """The decisive test with their published rows: residuals of THEIR rows from OUR orbit alone (``theirs_from_ours``),
503
+ then one joint fit of both sets (internal two-body from our orbit and ``start``; or Find_Orb with ``our_obs``, the
504
+ ades.read rows of our arc). The fit must use >= 90% of the rows, with 0 < rms < 0.4" (a zero rms is a degenerate fit)
505
+ and every one of OUR rows < 1.5"; then 'strict': every one of THEIR rows < 1.5" too, or 'loose': >= 80% of theirs
506
+ < 1.5" (old discordant published rows). Either is a match. -> dict(match, rule "strict" | "loose" | None, ...)."""
507
+ from . import orbit
508
+ T = their_rows(rows, rules["their_sigma"])
509
+ if not T:
510
+ return dict(match=False, why="no optical rows from fixed stations")
511
+ T, shared = same_exposure(arc, T, rules)
512
+ if not T: # every published row is one of our own detections (same exposure, <= same_sep): the same object
513
+ return dict(match=True, rule="same_exposure", n_shared=len(shared), shared_sep_max=max(x[2] for x in shared), used=0, count=0)
514
+ mj, ra, de, sg, st = (np.array([t[k] for t in T]) for k in ("mjd", "ra", "dec", "sig", "stn"))
515
+ at = orbit.Arc(mj, ra, de, sg, st.astype(object), ref=arc.ref)
516
+ r = at.residuals(o.x0, o.v0) * np.r_[at.sigma, at.sigma]
517
+ fo = np.hypot(r[:len(at)], r[len(at):])
518
+ out = dict(n_theirs=len(T), n_shared=len(shared), shared_sep_max=max((x[2] for x in shared), default=None),
519
+ stations=sorted(set(st.tolist())), their_arc_mjd=[float(mj.min()), float(mj.max())],
520
+ theirs_from_ours=dict(median=round(float(np.median(fo)), 3), max=round(float(fo.max()), 3)))
521
+ n = len(arc)
522
+ if backend == "findorb":
523
+ from .external import findorb_fit
524
+ obs = [dict(q, mine=True) for q in our_obs] + [dict(t, mine=False) for t in T]
525
+ obs.sort(key=lambda q: q["mjd"])
526
+ res = findorb_fit(obs, float(np.median(arc.sigma)), "W84", o.t0)
527
+ if res is None or res[1]["findorb"]["n_used"] < 0.8 * len(obs):
528
+ # no fit, or one keeping < 80 % of the rows (a possible false minimum, audit 21 Nov c6): again from our orbit
529
+ seed = [o.t0] + list(orbit.convert(o.state, o.t0, orbit.ECLIPTIC, orbit.HELIOCENTRIC))
530
+ res2 = findorb_fit(obs, float(np.median(arc.sigma)), "W84", o.t0, seed=seed)
531
+ if res2 is not None and (res is None or res2[1]["findorb"]["n_used"] > res[1]["findorb"]["n_used"]):
532
+ res = res2
533
+ out["seeded"] = True
534
+ if res is None:
535
+ return dict(out, match=False, why="Find_Orb found no orbit")
536
+ fit, info = res
537
+ rr, mine = np.hypot(*fit.residuals.T), np.array([q["mine"] for q in obs])
538
+ used, count = info["findorb"]["n_used"], len(obs)
539
+ use = np.ones(count, bool)
540
+ use[info["findorb"]["rejected"]] = False
541
+ rms = float(np.sqrt(np.mean(rr[use] ** 2)))
542
+ ours, theirs = rr[mine], rr[~mine]
543
+ out["findorb"] = info["findorb"]
544
+ out["backend"] = backend
545
+ return _decide(out, used, count, rms, ours, theirs, rules, use[mine], use[~mine])
546
+ else:
547
+ a = arc.extend(mj, ra, de, sigma=sg, site=st.astype(object))
548
+ best = _fit_from(a, [(o.x0, o.v0)] + ([start] if start is not None else []))
549
+ if best is None:
550
+ return dict(out, match=False, why="no joint fit")
551
+ rms, rr = best[0], best[1]
552
+ used = count = len(a)
553
+ ours, theirs = rr[:n], rr[n:]
554
+ out["elements"] = orbit.elements(best[2], best[3])
555
+ out["backend"] = backend
556
+ return _decide(out, used, count, rms, ours, theirs, rules)
557
+
558
+
559
+ def _decide(out, used, count, rms, ours, theirs, rules=CHECK, ours_used=None, theirs_used=None):
560
+ """The match rule of ``joint`` on one fit (residuals ["] of our rows and of theirs; which rows the fit kept, None: all)
561
+ -> ``out`` updated. Besides 'strict' and 'loose' (>= 90 % of the rows used), 'robust': rms < 0.4", every one of OUR rows
562
+ used and < 1.5", >= 95 % of THEIR rows < 1.5", >= 80 % of all rows and >= 80 % of theirs used (Find_Orb sets old
563
+ photographic rows aside: 1993 FW 147/183; one of the 565 rows of (523643) 2010 TY53 at 2.6"; survey, 23 Nov 2026)."""
564
+ out.update(used=int(used), count=int(count), rms=round(rms, 3), ours_max=round(float(ours.max()), 3),
565
+ theirs_max=round(float(theirs.max()), 3), theirs_frac=round(float(np.mean(theirs < rules["match_max"])), 3))
566
+ fit_ok = used >= rules["match_used"] * count and round(rms, 3) > 0 and rms < rules["match_rms"] and ours.max() < rules["match_max"]
567
+ strict = fit_ok and theirs.max() < rules["match_max"]
568
+ loose = fit_ok and np.mean(theirs < rules["match_max"]) >= rules["loose_their_frac"]
569
+ ou = np.ones(len(ours), bool) if ours_used is None else np.asarray(ours_used, bool)
570
+ tu = np.ones(len(theirs), bool) if theirs_used is None else np.asarray(theirs_used, bool)
571
+ robust = bool(ou.all() and round(rms, 3) > 0 and rms < rules["match_rms"] and ours.max() < rules["match_max"]
572
+ and np.mean(theirs < rules["match_max"]) >= rules["robust_their_frac"] and used >= rules["robust_used"] * count
573
+ and tu.mean() >= rules["robust_used"])
574
+ out.update(match=bool(strict or loose or robust), rule="strict" if strict else "loose" if loose else "robust" if robust else None)
575
+ if round(rms, 3) == 0:
576
+ out["why"] = "zero rms: a degenerate fit, not a pass"
577
+ return out
578
+
579
+
580
+ def check(arc, C, o=None, obs_of=get_obs, backend="internal", our_obs=None, rules=CHECK, r_min=15.0, r_max=200.0, log=print):
581
+ """The known-object check of one object (orbit.Arc ``arc``, best its whole arc) against the MPC orbits ``C``
582
+ (``mpc_orbits``), first cut to the orbits with q <= 2 r and Q >= r / 2 at our distance r: ``screen_epochs`` and
583
+ ``screen_rows`` (their union) -> ``link`` (local, a reported number) -> ``joint`` with ``obs_of(desig)`` (MPC get-obs)
584
+ for every pair with screen A or B whatever ``link`` says (a two-body link fails on long arcs that a perturbed fit
585
+ joins), for screen-B2 pairs with Find_Orb (with the internal two-body fit only if they link), and for C-only pairs that
586
+ link. A joint fit that gives no orbit is undecided, never 'no match'; so is a check that ran no joint fit at all.
587
+ -> dict(status "checked" | "undecided", n_orbits, gated, screened, fits_run, fits_converged, matches, undecided, pairs)
588
+ with the pairs sorted matches first, then by link rms."""
589
+ from . import orbit
590
+ o = o or orbit.fit(arc, r_min, r_max)
591
+ if o is None:
592
+ return dict(status="no_orbit", matches=[], pairs=[])
593
+ S = orbit.sample(arc, o, rules["clones"] + 1)
594
+ r = float(np.linalg.norm(o.x0))
595
+ g = np.flatnonzero((C["a"] * (1 - C["e"]) <= rules["gate_q"] * r) & (C["a"] * (1 + C["e"]) >= rules["gate_Q"] * r))
596
+ Cg = {key: v[g] for key, v in C.items()}
597
+ P = screen_epochs(o, S, arc, Cg, rules)
598
+ B2 = {p["k"]: p for p in screen_rows(o, arc, Cg, rules)}
599
+ for p in P:
600
+ q = B2.pop(p["k"], None)
601
+ p["B2"], p["sepB2_deg"] = q is not None, q and q["sepB2_deg"]
602
+ P += [dict(q, A=False, B=False, C=False, B2=True) for q in B2.values()]
603
+ for p in P:
604
+ p["k"] = int(g[p["k"]])
605
+ log(f" {len(C['epoch'])} MPC orbits; screen at their own dates: {len(P) - len(B2)} pairs (A {sum(p['A'] for p in P)}, "
606
+ f"B {sum(p['B'] for p in P)}, C {sum(p['C'] for p in P)}); at our rows (B2): {sum(p['B2'] for p in P)}, {len(B2)} more")
607
+ for p in P:
608
+ L = link(arc, o, S, C, p["k"], rules)
609
+ x, v = L.pop("x", None), L.pop("v", None)
610
+ p["link"] = L
611
+ if p["A"] or p["B"] or L["linkable"] or (p["B2"] and backend == "findorb"):
612
+ p["joint"] = joint(arc, o, obs_of(p["desig"]), None if x is None else (x, v), backend, our_obs, rules)
613
+ p["undecided"] = "used" not in p["joint"] and "rule" not in p["joint"] # no fit: not a 'no match'
614
+ p["match"] = bool(p.get("joint", {}).get("match"))
615
+ log(f" {p['name']}: link rms {L['rms']}\"" + (f", joint {p['joint'].get('used')}/{p['joint'].get('count')} rms "
616
+ f"{p['joint'].get('rms')}\" -> {'MATCH' if p['match'] else 'UNDECIDED' if p['undecided'] else 'no match'}" if "joint" in p else ""))
617
+ P.sort(key=lambda p: (not p["match"], p["link"]["rms"] if p["link"]["rms"] is not None else 1e9))
618
+ run = sum("joint" in p for p in P)
619
+ und = [p["desig"] for p in P if p.get("undecided")]
620
+ matches = [p["desig"] for p in P if p["match"]]
621
+ return dict(status="checked" if matches or (run and not und) else "undecided", n_orbits=int(len(C["epoch"])), gated=int(len(g)),
622
+ screened=len(P), fits_run=run, fits_converged=run - len(und), matches=matches, undecided=und, pairs=P)
623
+
624
+
625
+ # ---------------------------------------------------------------- registry / duplicate check (local only)
626
+ def registry_tracks(paths):
627
+ """ADES PSV files or folders (every *.psv below) -> {track: rows} (``ades.read``: trkSub, else provID, else permID;
628
+ a track in several files is merged)."""
629
+ from pathlib import Path
630
+
631
+ from . import ades
632
+ out = {}
633
+ for p in map(Path, paths):
634
+ for f in sorted(p.rglob("*.psv")) if p.is_dir() else [p]:
635
+ for t, rows in ades.read(f).items():
636
+ out.setdefault(t, []).extend(rows)
637
+ return {t: sorted(v, key=lambda r: r["mjd"]) for t, v in out.items()}
638
+
639
+
640
+ def _rarc(rows, rules):
641
+ """orbit.Arc of rows as confirm keeps them (mid, sig, site) or as ades.read gives them (mjd, rmsRA/rmsDec, stn)."""
642
+ from . import orbit
643
+ rows = sorted(rows, key=lambda r: r.get("mid", r.get("mjd")))
644
+ sig = [r.get("sig") or max(r.get("rmsRA") or 0, r.get("rmsDec") or 0) or rules["their_sigma"] for r in rows]
645
+ return orbit.Arc([r.get("mid", r.get("mjd")) for r in rows], [r["ra"] for r in rows], [r["dec"] for r in rows], sig,
646
+ [r.get("site") or r.get("stn") or "W84" for r in rows])
647
+
648
+
649
+ def _offsets(o, a, idx=None):
650
+ """Offsets ["] of orbit o (two-body) from the rows ``idx`` of arc a (all rows if None)."""
651
+ from . import orbit
652
+ if idx is not None:
653
+ a = orbit.Arc(a.mjd[idx], a.ra[idx], a.dec[idx], a.sigma[idx], a.site[idx])
654
+ s = _at(np.r_[o.x0, o.v0][None], [o.t0], a.t0)[0]
655
+ r = a.residuals(s[:3], s[3:]) * np.r_[a.sigma, a.sigma]
656
+ return np.hypot(r[:len(a)], r[len(a):])
657
+
658
+
659
+ _TRACK_ORBITS = {}
660
+
661
+
662
+ def _track_orbit(t, b, r_min, r_max):
663
+ """A registry track's own orbit, fitted once per process (the same rows give the same fit; 384 fits took ~600 s of
664
+ every confirm run)."""
665
+ from . import orbit
666
+ k = (t, r_min, r_max, b.mjd.tobytes(), b.ra.tobytes(), b.dec.tobytes(), np.asarray(b.sigma).tobytes(), tuple(np.atleast_1d(b.site).tolist()))
667
+ if k not in _TRACK_ORBITS:
668
+ _TRACK_ORBITS[k] = orbit.fit(b, r_min, r_max)
669
+ return _TRACK_ORBITS[k]
670
+
671
+
672
+ def registry_check(rows, orbit_, registry, rule=None, log=print):
673
+ """Is this object already in the registry (the user's registered objects and other candidates)? All local.
674
+ rows: our rows (dicts mid|mjd, ra, dec, sig|rmsRA, site|stn); orbit_: our orbit.Orbit (None: fitted here);
675
+ registry: {track: rows} or ADES PSV paths (``registry_tracks``). (a) row duplicates: a registry row within ``dup_dt``
676
+ s and ``dup_sep``"; (b) each track's own orbit (fitted from its rows) at our first, middle and last row; (c) our orbit
677
+ at the first, middle and last row of each track (covers tracks with no or a bad fit). A track closer than
678
+ ``orbit_gate``" at all three rows in (b) or (c) gets a two-body joint fit of both row sets with the match rule of
679
+ ``joint`` (strict or loose). -> dict(status "checked", duplicates [track], row_duplicates, pairs)."""
680
+ from . import orbit
681
+ R = dict(CHECK, **(rule or {}))
682
+ if not isinstance(registry, dict):
683
+ registry = registry_tracks(registry)
684
+ a = _rarc(rows, R)
685
+ o = orbit_ or orbit.fit(a, R.get("r_min", 15.0), R.get("r_max", 200.0))
686
+ three = lambda n: [0, n // 2, n - 1]
687
+ dups, pairs = [], []
688
+ for t, rr in registry.items():
689
+ b = _rarc(rr, R)
690
+ dt = np.abs(a.mjd[:, None] - b.mjd[None]) * 86400 < R["dup_dt"]
691
+ i, j = np.nonzero(dt)
692
+ same = [(int(x), int(y)) for x, y in zip(i, j) if _sep(a.ra[x], a.dec[x], b.ra[y], b.dec[y]) < R["dup_sep"]]
693
+ if same:
694
+ dups.append(dict(track=t, rows=[(float(a.mjd[x]), float(b.mjd[y])) for x, y in same]))
695
+ ob = _track_orbit(t, b, R.get("r_min", 15.0), R.get("r_max", 200.0)) if len(b) >= 3 else None
696
+ fwd = float(_offsets(ob, a, three(len(a))).max()) if ob is not None else None
697
+ rev = float(_offsets(o, b, three(len(b))).max()) if o is not None else None
698
+ if not (min(x for x in (fwd, rev, np.inf) if x is not None) < R["orbit_gate"]):
699
+ continue
700
+ ab = a.extend(b.mjd, b.ra, b.dec, sigma=b.sigma, site=b.site)
701
+ starts = [(lambda s: (s[:3], s[3:]))(_at(np.r_[q.x0, q.v0][None], [q.t0], ab.t0)[0]) for q in (o, ob) if q is not None]
702
+ best = _fit_from(ab, starts)
703
+ p = dict(track=t, fwd_max=None if fwd is None else round(fwd, 1), rev_max=None if rev is None else round(rev, 1))
704
+ if best is None:
705
+ p.update(match=False, why="no joint fit")
706
+ else:
707
+ _decide(p, len(ab), len(ab), best[0], best[1][:len(a)], best[1][len(a):], R)
708
+ pairs.append(p)
709
+ log(f" registry {t}: (b) {p['fwd_max']}\" (c) {p['rev_max']}\" -> joint {p.get('rms')}\" {'DUPLICATE' if p['match'] else 'no match'}")
710
+ names = [d["track"] for d in dups] + [p["track"] for p in pairs if p["match"]]
711
+ return dict(status="checked", n_tracks=len(registry), duplicates=list(dict.fromkeys(names)), row_duplicates=dups, pairs=pairs)
712
+
713
+
714
+ def batch_check(tracks, rule=None, log=print):
715
+ """(d) inside a batch: every track against every other one, both ways ({track: rows} -> {track: registry_check})."""
716
+ return {t: registry_check(rr, None, {u: v for u, v in tracks.items() if u != t}, rule, log) for t, rr in tracks.items()}