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/orbit.py ADDED
@@ -0,0 +1,614 @@
1
+ """Barycentric two-body orbits: observer positions, propagation, astrometry, least-squares fitting,
2
+ uncertainty sampling and osculating elements.
3
+
4
+ A distant object orbits the barycentre of the Sun and planets, so a two-body orbit about the barycentre
5
+ with GM = GM_sun x (1 + planet masses) is good to ~0.1" over a few years for a TNO (a heliocentric
6
+ two-body orbit is off by tens of arcsec because of the Sun's reflex motion). Frames: ICRS equatorial,
7
+ positions in AU, velocities in AU/day, times in JD (TDB) inside, MJD (UTC) at the interface.
8
+ """
9
+ import inspect
10
+ from dataclasses import dataclass
11
+ from typing import ClassVar
12
+
13
+ import numpy as np
14
+ from scipy.optimize import least_squares
15
+
16
+ from . import _native
17
+
18
+ _WORKERS = "workers" in inspect.signature(least_squares).parameters # scipy >= 1.16
19
+
20
+ GM_SUN = 2.9591220828559115e-4 # AU^3 / day^2
21
+ GM_BARY = GM_SUN * (1 + 1 / 6023600 + 1 / 408523.71 + 1 / 328900.56 + 1 / 3098708 + 1 / 1047.3486
22
+ + 1 / 3497.898 + 1 / 22902.98 + 1 / 19412.24)
23
+ C_AU_D = 173.1446326742403 # speed of light, AU/day
24
+ AU_KM = 149597870.7
25
+ R_EARTH_AU = 6378.137 / AU_KM
26
+ EPS = np.radians(23.4392911) # J2000 obliquity
27
+ ECL = np.array([[1, 0, 0], [0, np.cos(EPS), np.sin(EPS)], [0, -np.sin(EPS), np.cos(EPS)]]) # ICRS -> ecliptic
28
+ POLE = ECL[2] # ecliptic pole in ICRS
29
+ # Frame labels. States here are barycentric equatorial (ICRS axes) unless stated; elements are always
30
+ # referred to the ecliptic J2000 (obliquity EPS). ``convert`` moves states between frames and centres.
31
+ EQUATORIAL, ECLIPTIC = "equatorial", "ecliptic"
32
+ BARYCENTRIC, HELIOCENTRIC = "barycentric", "heliocentric"
33
+ OBSCODES_URL = "https://minorplanetcenter.net/iau/lists/ObsCodes.html"
34
+
35
+ # MPC parallax constants: east longitude [deg], rho cos(phi'), rho sin(phi') [Earth radii]
36
+ SITES = {"W84": (289.19358, 0.865572, -0.499793), # Cerro Tololo, DECam
37
+ "807": (289.1941, 0.86560, -0.49980), # Cerro Tololo
38
+ "695": (248.40533, 0.849504, 0.526425), # Kitt Peak (Mayall, Mosaic3)
39
+ "V00": (248.39981, 0.849456, 0.526492), # Kitt Peak-Bok (90Prime)
40
+ "568": (204.5278, 0.94171, 0.33725), # Maunakea (CFHT MegaCam)
41
+ "T09": (204.52396, 0.941711, 0.337239), # Subaru Telescope, Maunakea (HSC)
42
+ "309": (289.59569, 0.909943, -0.414336), # Cerro Paranal (VST OmegaCAM)
43
+ "F51": (203.74409, 0.936241, 0.351543), # Pan-STARRS 1, Haleakala
44
+ "I41": (243.14022, 0.836322, 0.546875), # Palomar (ZTF)
45
+ "X05": (289.25058, 0.864981, -0.500958), # Cerro Pachon (Rubin Observatory, Simonyi Survey Telescope)
46
+ "500": (0.0, 0.0, 0.0)} # geocentre
47
+ _obs_cache = {}
48
+
49
+
50
+ def site_constants(code):
51
+ """(longitude, rho cos phi', rho sin phi') of an MPC observatory code; the MPC list is downloaded
52
+ once into the cache for codes not built in."""
53
+ code = str(code).strip().upper()
54
+ if code not in SITES:
55
+ from . import config, net
56
+ path = config.cache_dir() / "ObsCodes.html"
57
+ if not path.exists():
58
+ b = net.fetch(OBSCODES_URL)
59
+ if b"Geocentric" not in b: # an error page, not the list: never cache it
60
+ raise net.ServiceError("MPC ObsCodes: unexpected answer " + repr(b[:200]))
61
+ net.save(path, b)
62
+ for line in path.read_text(errors="replace").splitlines():
63
+ if line[:4].rstrip() == code:
64
+ try:
65
+ SITES[code] = (float(line[4:13]), float(line[13:21]), float(line[21:30]))
66
+ except ValueError:
67
+ raise ValueError(f"MPC site {code} has no fixed ground position") from None
68
+ break
69
+ else:
70
+ raise ValueError(f"unknown MPC site code {code}")
71
+ return SITES[code]
72
+
73
+
74
+ def observer(mjd_utc, site="W84"):
75
+ """Observer at UTC MJDs -> (JD TDB (n,), barycentric ICRS position (n, 3) [AU]).
76
+
77
+ Geocentre from astropy's built-in ephemeris (~km); site offset from the MPC parallax constants rotated
78
+ by GMST (precession, nutation, UT1-UTC and polar motion ignored: < 2 mas at 30 AU)."""
79
+ mjd = np.atleast_1d(np.asarray(mjd_utc, float))
80
+ key = np.round(mjd, 8)
81
+ new = [k for k in np.unique(key).tolist() if (site, k) not in _obs_cache]
82
+ if new:
83
+ from astropy.coordinates import get_body_barycentric
84
+ from astropy.time import Time
85
+ t = Time(new, format="mjd", scale="utc")
86
+ geo = get_body_barycentric("earth", t).xyz.to("au").value.T
87
+ lon, rc, rs = site_constants(site)
88
+ lst = np.radians(280.46061837 + 360.98564736629 * (np.array(new) - 51544.5) + lon)
89
+ off = R_EARTH_AU * np.c_[rc * np.cos(lst), rc * np.sin(lst), np.full(len(new), rs)]
90
+ for k, jd, x in zip(new, t.tdb.jd, geo + off):
91
+ _obs_cache[(site, k)] = (jd, x)
92
+ v = [_obs_cache[(site, k)] for k in key.tolist()]
93
+ return np.array([a for a, _ in v]), np.array([b for _, b in v]).reshape(-1, 3)
94
+
95
+
96
+ def unit(ra, dec):
97
+ """Unit vectors (..., 3) for RA/Dec in degrees."""
98
+ ra, dec = np.radians(ra), np.radians(dec)
99
+ return np.stack([np.cos(dec) * np.cos(ra), np.cos(dec) * np.sin(ra), np.sin(dec)], -1)
100
+
101
+
102
+ def centre_ra(ra, f=np.mean):
103
+ """f (np.mean or np.median) of RA values [deg] spanning less than 180 deg, across RA 0/360 too."""
104
+ ra = np.asarray(ra) % 360
105
+ if np.ptp(ra) > 180:
106
+ ra = np.where(ra >= 180, ra - 360, ra)
107
+ return float(f(ra)) % 360
108
+
109
+
110
+ def _stumpff(z, zs):
111
+ """Stumpff C(z), S(z); all-elliptic arrays (the usual case) skip the other branches (same values)."""
112
+ if (z > 1e-8).all():
113
+ return (1 - np.cos(zs)) / zs ** 2, (zs - np.sin(zs)) / zs ** 3
114
+ return (np.where(z > 1e-8, (1 - np.cos(zs)) / zs ** 2, np.where(z < -1e-8, (np.cosh(zs) - 1) / zs ** 2, 0.5)),
115
+ np.where(z > 1e-8, (zs - np.sin(zs)) / zs ** 3, np.where(z < -1e-8, (np.sinh(zs) - zs) / zs ** 3, 1 / 6)))
116
+
117
+
118
+ def kepler(x0, v0, dt, gm=GM_BARY, rows=False):
119
+ """Two-body propagation (universal variables, any eccentricity). x0, v0: (k, 3) states; dt: (m,) or
120
+ (k, m) days -> positions (k, m, 3). Newton stops when every step is < 1e-11; rows=True: each state
121
+ stops on its own, exactly as if propagated in a call of its own."""
122
+ x0, v0 = np.atleast_2d(x0), np.atleast_2d(v0)
123
+ dt = np.asarray(dt, float)
124
+ if _native.lib is not None:
125
+ d = np.atleast_1d(dt)
126
+ d = np.ascontiguousarray(np.broadcast_to(d, (len(x0), d.shape[-1])))
127
+ return _native.lib.kepler(np.ascontiguousarray(x0, float), np.ascontiguousarray(v0, float), d, float(gm), rows)
128
+ r0 = np.linalg.norm(x0, axis=1)[:, None]
129
+ vr0 = (x0 * v0).sum(1)[:, None] / r0
130
+ al = 2 / r0 - (v0 * v0).sum(1)[:, None] / gm
131
+ sq = np.sqrt(gm)
132
+ chi = np.where(al > 0, sq * np.abs(al) * dt, sq * dt / r0) * np.ones_like(r0)
133
+ a1, a2, a3 = r0 * vr0 / sq, 1 - al * r0, sq * dt * np.ones_like(r0) # loop invariants
134
+ C, S = np.empty_like(chi), np.empty_like(chi)
135
+ act = slice(None) # rows still iterating
136
+ with np.errstate(over="ignore", invalid="ignore"):
137
+ for _ in range(50):
138
+ c, al_, b1, b2, b3, r = chi[act], al[act], a1[act], a2[act], a3[act], r0[act]
139
+ z = al_ * c ** 2
140
+ zs = np.sqrt(np.abs(z)) + 1e-30
141
+ Cz, Sz = _stumpff(z, zs)
142
+ F = b1 * c ** 2 * Cz + b2 * c ** 3 * Sz + r * c - b3
143
+ dF = b1 * c * (1 - z * Sz) + b2 * c ** 2 * Cz + r
144
+ step = F / dF
145
+ chi[act], C[act], S[act] = c - step, Cz, Sz
146
+ if not rows:
147
+ if np.nanmax(np.abs(step)) < 1e-11:
148
+ break
149
+ continue
150
+ ix = np.arange(len(chi))[act]
151
+ act = ix[~(np.fmax.reduce(np.abs(step), axis=1) < 1e-11)]
152
+ if not len(act):
153
+ break
154
+ f = 1 - chi ** 2 / r0 * C
155
+ g = dt - chi ** 3 / sq * S
156
+ return f[..., None] * x0[:, None, :] + g[..., None] * v0[:, None, :]
157
+
158
+
159
+ def radec(x0, v0, t0, jd, obs, gm=GM_BARY, rows=False):
160
+ """Astrometric RA/Dec [deg], arrays (k, m), of k states at epoch t0 (JD TDB) seen at m times jd
161
+ (JD TDB) from observer positions obs (m, 3); light time included. rows=True: every state exactly as
162
+ in a call of its own."""
163
+ if _native.lib is not None:
164
+ return _native.lib.radec(np.ascontiguousarray(np.atleast_2d(x0), float), np.ascontiguousarray(np.atleast_2d(v0), float),
165
+ float(t0), np.ascontiguousarray(jd, float).ravel(), np.ascontiguousarray(obs, float).reshape(-1, 3),
166
+ float(gm), rows)
167
+ lt = 0.0
168
+ for _ in range(3):
169
+ p = kepler(x0, v0, jd - t0 - lt, gm, rows) - obs
170
+ d = np.linalg.norm(p, axis=-1)
171
+ lt = d / C_AU_D
172
+ return np.degrees(np.arctan2(p[..., 1], p[..., 0])) % 360, np.degrees(np.arcsin(p[..., 2] / d))
173
+
174
+
175
+ def predict(states, t0, mjd_utc, site="W84"):
176
+ """RA, Dec [deg] arrays (k, m) of k states (k, 6) at epoch t0 (JD TDB) at UTC MJDs from ``site``."""
177
+ states = np.atleast_2d(states)
178
+ jd, obs = observer(mjd_utc, site)
179
+ return radec(states[:, :3], states[:, 3:], t0, jd, obs)
180
+
181
+
182
+ def extent(ra, dec):
183
+ """Central 95% extent (major, minor) [arcsec] of a cloud of predicted positions."""
184
+ a0, d0 = centre_ra(ra, np.median), np.median(dec)
185
+ x = ((ra - a0 + 180) % 360 - 180) * np.cos(np.radians(d0)) * 3600
186
+ y = (dec - d0) * 3600
187
+ _, vec = np.linalg.eigh(np.cov(x, y))
188
+ p = np.c_[x, y] @ vec
189
+ return [float(np.ptp(np.percentile(p[:, k], [2.5, 97.5]))) for k in (1, 0)]
190
+
191
+
192
+ def is_bound(x, v):
193
+ return float(v @ v) < 2 * GM_BARY / float(np.linalg.norm(x))
194
+
195
+
196
+ @dataclass
197
+ class Node:
198
+ chi2: float
199
+ r: float
200
+ vr: float
201
+ q: np.ndarray
202
+ jac: np.ndarray
203
+ bound: bool
204
+
205
+
206
+ class Arc:
207
+ """Astrometric observations to fit: UTC MJDs, RA/Dec [deg], per-point sigma [arcsec] and MPC site(s).
208
+
209
+ States are parameterised relative to a reference observation (``ref``): offsets on the sky [arcsec]
210
+ from its position, barycentric distance r [AU] and velocity [1e-3 AU/day], at its time t0 (JD TDB).
211
+ ``extend`` keeps the reference, so states and samples of the shorter arc stay valid."""
212
+
213
+ def __init__(self, mjd, ra, dec, sigma=0.15, site="W84", ref=None):
214
+ self.mjd, self.ra, self.dec = (np.atleast_1d(np.asarray(x, float)) for x in (mjd, ra, dec))
215
+ self.sigma = np.broadcast_to(np.asarray(sigma, float), self.mjd.shape).copy()
216
+ self.site = np.broadcast_to(np.asarray(site, dtype=object), self.mjd.shape).copy()
217
+ self.jd, self.obs = np.empty(len(self.mjd)), np.empty((len(self.mjd), 3))
218
+ for s in set(self.site.tolist()):
219
+ m = self.site == s
220
+ self.jd[m], self.obs[m] = observer(self.mjd[m], s)
221
+ if ref is None:
222
+ k = int(np.argmin(np.abs(self.jd - self.jd.mean())))
223
+ ref = (self.jd[k], self.obs[k], self.ra[k], self.dec[k])
224
+ self.ref = ref
225
+ self.t0, self.o0, self.ra0, self.dec0 = ref
226
+
227
+ def __len__(self):
228
+ return len(self.mjd)
229
+
230
+ @property
231
+ def days(self):
232
+ return float(np.ptp(self.mjd))
233
+
234
+ def extend(self, mjd, ra, dec, sigma=None, site="W84"):
235
+ """This arc plus extra points (same reference)."""
236
+ mjd = np.atleast_1d(mjd)
237
+ s = np.broadcast_to(np.median(self.sigma) if sigma is None else sigma, mjd.shape)
238
+ return Arc(np.r_[self.mjd, mjd], np.r_[self.ra, ra], np.r_[self.dec, dec], np.r_[self.sigma, s],
239
+ np.r_[self.site, np.broadcast_to(np.asarray(site, dtype=object), mjd.shape)], ref=self.ref)
240
+
241
+ def residuals(self, x0, v0):
242
+ """(2n,) residuals (dRA cos Dec, then dDec) in units of sigma."""
243
+ ra, dec = radec(x0, v0, self.t0, self.jd, self.obs)
244
+ dra = ((ra[0] - self.ra + 180) % 360 - 180) * np.cos(np.radians(self.dec)) * 3600
245
+ return np.r_[dra, (dec[0] - self.dec) * 3600] / np.r_[self.sigma, self.sigma]
246
+
247
+ def residuals_many(self, states):
248
+ """``residuals`` of many (x0, v0) at once -> (k, 2n), each row as computed alone."""
249
+ ra, dec = radec(np.array([x for x, _ in states]), np.array([v for _, v in states]), self.t0, self.jd, self.obs,
250
+ rows=True)
251
+ dra = ((ra - self.ra + 180) % 360 - 180) * np.cos(np.radians(self.dec)) * 3600
252
+ return np.concatenate([dra, (dec - self.dec) * 3600], 1) / np.r_[self.sigma, self.sigma]
253
+
254
+ def _lsq(self, to_state, x0, max_nfev):
255
+ """Levenberg-Marquardt (MINPACK) on residuals(*to_state(q)); with scipy >= 1.16 the finite-difference
256
+ columns of each Jacobian are evaluated together (same values, fewer calls)."""
257
+ kw = {}
258
+ if _WORKERS:
259
+ kw["workers"] = lambda _, qs: list(self.residuals_many([to_state(q) for q in qs]))
260
+ return least_squares(lambda q: self.residuals(*to_state(q)), x0, method="lm", max_nfev=max_nfev, **kw)
261
+
262
+ def state(self, q, r, vr):
263
+ """q = (dRA cos Dec ", dDec ", two tangential velocity components) at distance r [AU] and radial
264
+ velocity vr [1e-3 AU/d] -> (x0, v0) at t0."""
265
+ if _native.lib is not None:
266
+ return _native.lib.arc_state(float(self.ra0), float(self.dec0), self.o0, POLE, q, float(r), float(vr))
267
+ l = unit(self.ra0 + q[0] / 3600 / np.cos(np.radians(self.dec0)), self.dec0 + q[1] / 3600)
268
+ b = self.o0 @ l
269
+ x0 = self.o0 + (-b + np.sqrt(b * b - self.o0 @ self.o0 + r * r)) * l
270
+ xh = x0 / r
271
+ e1 = np.cross(POLE, xh)
272
+ e1 /= np.linalg.norm(e1)
273
+ e2 = np.cross(xh, e1)
274
+ return x0, (vr * xh + q[2] * e1 + q[3] * e2) / 1e3
275
+
276
+ def from_p6(self, p):
277
+ """p6 = (dRA cos Dec ", dDec ", r, vx, vy, vz [1e-3 AU/d]) -> (x0, v0)."""
278
+ x0, _ = self.state([p[0], p[1], 0, 0], p[2], 0)
279
+ return x0, np.asarray(p[3:], float) / 1e3
280
+
281
+ def to_p6(self, x0, v0):
282
+ l = (x0 - self.o0) / np.linalg.norm(x0 - self.o0)
283
+ ra, dec = np.degrees(np.arctan2(l[1], l[0])) % 360, np.degrees(np.arcsin(l[2]))
284
+ return np.r_[((ra - self.ra0 + 180) % 360 - 180) * np.cos(np.radians(self.dec0)) * 3600,
285
+ (dec - self.dec0) * 3600, np.linalg.norm(x0), np.asarray(v0) * 1e3]
286
+
287
+ def fit_node(self, r, vr, q0=None):
288
+ """Best q at fixed (r, vr)."""
289
+ if q0 is None:
290
+ q0 = self._guess(r)
291
+ k = self._lsq(lambda q: self.state(q, r, vr), q0, 200)
292
+ x0, v0 = self.state(k.x, r, vr)
293
+ return Node(2 * k.cost, r, vr, k.x, k.jac, is_bound(x0, v0))
294
+
295
+ def _guess(self, r):
296
+ """Tangential velocity from the earliest and latest positions put at distance r (any point order)."""
297
+ first, last = int(np.argmin(self.jd)), len(self.jd) - 1 - int(np.argmax(self.jd[::-1]))
298
+ P = []
299
+ for k in (first, last):
300
+ l = unit(self.ra[k], self.dec[k])
301
+ o = self.obs[k]
302
+ b = o @ l
303
+ P.append(o + (-b + np.sqrt(b * b - o @ o + r * r)) * l)
304
+ v = (P[1] - P[0]) / max(self.jd[last] - self.jd[first], 1e-3)
305
+ x0, _ = self.state([0, 0, 0, 0], r, 0)
306
+ xh = x0 / r
307
+ e1 = np.cross(POLE, xh)
308
+ e1 /= np.linalg.norm(e1)
309
+ return np.array([0, 0, v @ e1 * 1e3, v @ np.cross(xh, e1) * 1e3])
310
+
311
+ def scan(self, rs, nv=7, vrs=None, bound=True):
312
+ """Nodes on a grid of distance x radial velocity (by default nv - 2 values inside the bound range; bound=False:
313
+ nv values in |vr| <= 2 sqrt(GM / r), the speed of a hyperbolic orbit with v_inf = escape speed at r)."""
314
+ out = []
315
+ for r in rs:
316
+ try:
317
+ n0 = self.fit_node(r, 0.0 if vrs is None else vrs[0])
318
+ except ValueError: # propagation overflow (unbound grids at small r): no node
319
+ continue
320
+ q = n0.q
321
+ if vrs is not None:
322
+ grid = vrs
323
+ elif bound:
324
+ vmax = np.sqrt(max(0.0, 2 * GM_BARY / r - (n0.q[2] ** 2 + n0.q[3] ** 2) / 1e6)) * 1e3
325
+ grid = np.linspace(-vmax, vmax, nv)[1:-1] if vmax > 0 else []
326
+ else:
327
+ grid = np.linspace(-1, 1, nv) * 2 * np.sqrt(GM_BARY / r) * 1e3
328
+ for vr in grid:
329
+ try:
330
+ n = self.fit_node(r, vr, q)
331
+ except ValueError:
332
+ continue
333
+ q = n.q
334
+ out.append(n)
335
+ return out
336
+
337
+ def fit6(self, p0):
338
+ """Free 6-parameter least squares from p0 -> (p, chi2)."""
339
+ k = self._lsq(self.from_p6, p0, 400)
340
+ return k.x, 2 * k.cost
341
+
342
+ def jac6(self, p):
343
+ """Numerical Jacobian of the residuals with respect to p6."""
344
+ H = np.array([1e-3, 1e-3, 1e-5, 1e-5, 1e-5, 1e-5])
345
+ R = self.residuals_many([self.from_p6(p + dp) for dp in np.diag(H)] + [self.from_p6(p - dp) for dp in np.diag(H)])
346
+ return np.array([(R[k] - R[6 + k]) / (2 * H[k]) for k in range(6)]).T
347
+
348
+
349
+ @dataclass
350
+ class Orbit:
351
+ """Best-fit state at epoch t0 (JD TDB), Cartesian covariance (6, 6) and fit statistics. The state and
352
+ covariance are barycentric equatorial (ICRS axes): see ``frame``, ``center`` and ``convert``."""
353
+ frame: ClassVar[str] = EQUATORIAL
354
+ center: ClassVar[str] = BARYCENTRIC
355
+ x0: np.ndarray
356
+ v0: np.ndarray
357
+ t0: float
358
+ cov: np.ndarray
359
+ chi2: float
360
+ n: int
361
+ rms: float # arcsec, per coordinate
362
+ days: float
363
+ residuals: np.ndarray # (n, 2) arcsec
364
+
365
+ @property
366
+ def state(self):
367
+ return np.r_[self.x0, self.v0]
368
+
369
+ @property
370
+ def bound(self):
371
+ return is_bound(self.x0, self.v0)
372
+
373
+ @property
374
+ def r(self):
375
+ return float(np.linalg.norm(self.x0))
376
+
377
+ def elements(self):
378
+ return elements(self.x0, self.v0)
379
+
380
+ def state_in(self, frame=ECLIPTIC, center=BARYCENTRIC):
381
+ """The state (6,) in another frame / centre."""
382
+ return convert(self.state, self.t0, frame, center)
383
+
384
+ def to_dict(self):
385
+ return dict(frame=self.frame, center=self.center, t0_jd_tdb=self.t0, x0=self.x0.tolist(), v0=self.v0.tolist(), cov=self.cov.tolist(),
386
+ chi2=self.chi2, n=self.n, rms_arcsec=self.rms, arc_days=self.days, r_au=self.r,
387
+ bound=self.bound, elements_bary=self.elements(), elements_helio=helio_elements(self.x0, self.v0, self.t0),
388
+ residuals_arcsec=np.round(self.residuals, 3).tolist())
389
+
390
+
391
+ def _orbit(arc, p):
392
+ x0, v0 = arc.from_p6(p)
393
+ res = arc.residuals(x0, v0)
394
+ J = arc.jac6(p)
395
+ n = len(arc)
396
+ chi2 = float(res @ res)
397
+ cov_p = np.linalg.pinv(J.T @ J) * max(1.0, chi2 / max(1, 2 * n - 6))
398
+ Js = np.empty((6, 6)) # d(state)/d(p6)
399
+ H = np.array([1e-3, 1e-3, 1e-5, 1e-5, 1e-5, 1e-5])
400
+ for k in range(6):
401
+ dp = np.zeros(6)
402
+ dp[k] = H[k]
403
+ Js[:, k] = (np.r_[arc.from_p6(p + dp)] - np.r_[arc.from_p6(p - dp)]).ravel() / (2 * H[k])
404
+ rr = res * np.r_[arc.sigma, arc.sigma]
405
+ return Orbit(x0, v0, float(arc.t0), Js @ cov_p @ Js.T, chi2, n, float(np.sqrt(np.mean(rr ** 2))), arc.days,
406
+ np.c_[rr[:n], rr[n:]])
407
+
408
+
409
+ def fit(arc, r_min=15.0, r_max=200.0, nv=7, r_guess=None, bound=True):
410
+ """Best bound barycentric orbit, or None if no bound orbit exists.
411
+
412
+ A grid of distances (2% steps from r_min to r_max, or +-30% around r_guess) x radial velocities
413
+ gives the best bound starting point; a free 6-parameter least-squares fit then polishes it (kept
414
+ only if it stays bound and improves chi2). Fewer than 3 rows: None (fewer residuals than unknowns).
415
+ bound=False: parabolic and hyperbolic orbits too (wider radial-velocity grid, no bound filter); r_min can go down
416
+ to ~1 AU (distances the reference line of sight cannot reach from the observer are skipped). Inside ~10 AU the
417
+ barycentric two-body model ignores the planets and the Sun's reflex: fine for arcs of weeks, use Find_Orb beyond."""
418
+ if len(arc) < 3:
419
+ return None
420
+ if r_guess:
421
+ r_min, r_max = max(r_min, 0.7 * r_guess), 1.3 * r_guess
422
+ rs = r_min * 1.02 ** np.arange(int(np.log(r_max / r_min) / np.log(1.02)) + 1)
423
+ b = arc.o0 @ unit(arc.ra0, arc.dec0)
424
+ rs = rs[rs * rs > arc.o0 @ arc.o0 - b * b] # the line of sight reaches distance r (always true beyond ~1.02 AU)
425
+ nodes = [n for n in arc.scan(rs, nv, bound=bound) if n.bound or not bound]
426
+ if not nodes:
427
+ return None
428
+ best = min(nodes, key=lambda n: n.chi2)
429
+ p0 = arc.to_p6(*arc.state(best.q, best.r, best.vr))
430
+ p, chi2 = arc.fit6(p0)
431
+ if (bound and not is_bound(*arc.from_p6(p))) or chi2 > best.chi2:
432
+ p = p0
433
+ return _orbit(arc, p)
434
+
435
+
436
+ def sample(arc, orb, n=1000, method="auto", seed=1, grid=21, bound=True):
437
+ """Orbit uncertainty samples (m, 6) at orb.t0 (barycentric equatorial, like orb), bound orbits only
438
+ (bound=False: unbound ones too, as from ``fit(..., bound=False)``); row 0 = best fit.
439
+
440
+ 'linear': Gaussian draws from the fit covariance (good for arcs over about a year).
441
+ 'ranging': nodes on a distance x radial-velocity grid around the best fit, weighted by
442
+ exp(-dchi2 / 2 / s) (s = max(1, chi2_min/dof)), each with a Gaussian draw of the other 4
443
+ parameters. The grid follows the axes of the linear (r, vr) error ellipse (+-8 sigma, the long axis
444
+ kept within 20% in r and the bound vr range), so it resolves the narrow diagonal valley of
445
+ arcs of weeks; its box shrinks to the best fit and the dchi2 < 16 s nodes 3 times. Needed for
446
+ short arcs, where distance and radial velocity are poorly constrained and the linear covariance is wrong.
447
+ 'auto': ranging if the arc is shorter than 300 days.
448
+ 'both': the union of n - n//2 ranging and n//2 linear samples (row 0 = best fit): either cloud alone can
449
+ miss the object when an arc of a few nights is extrapolated by years."""
450
+ if method == "both":
451
+ return np.r_[sample(arc, orb, n - n // 2, "ranging", seed, grid, bound), sample(arc, orb, n // 2 + 1, "linear", seed, bound=bound)[1:]]
452
+ rng = np.random.default_rng(seed)
453
+ if method == "auto":
454
+ method = "ranging" if arc.days < 300 else "linear"
455
+ if method == "linear":
456
+ S = rng.multivariate_normal(orb.state, orb.cov, n)
457
+ S = S[[is_bound(s[:3], s[3:]) or not bound for s in S]]
458
+ return np.r_[[orb.state], S[1:]]
459
+ dof = max(1, 2 * len(arc) - 6)
460
+ x, v, r0 = orb.x0, orb.v0, orb.r
461
+ vr0 = x @ v / r0
462
+ vmax = np.sqrt(max(2 * GM_BARY / r0 - (v @ v - vr0 ** 2), 1e-12) if bound else 4 * GM_BARY / r0) * 1e3
463
+ J = np.zeros((2, 6)) # d(r, vr [1e-3 AU/d]) / d(state)
464
+ J[0, :3], J[1, :3], J[1, 3:] = x / r0, (v - vr0 * x / r0) / r0 * 1e3, x / r0 * 1e3
465
+ lam, E = np.linalg.eigh(J @ orb.cov @ J.T)
466
+ E = E * np.sqrt(np.maximum(lam, 1e-12)) # columns: 1-sigma axes of the linear (r, vr) ellipse
467
+ h = np.minimum(8.0, np.min(np.array([[0.2 * r0], [vmax]]) / (np.abs(E) + 1e-300), 0)) # long axis kept in the box
468
+ lo, hi = -h, h
469
+ cmin = orb.chi2
470
+ for _ in range(3):
471
+ B, P = [], []
472
+ for a in np.linspace(lo[0], hi[0], grid):
473
+ q = None
474
+ for b in np.linspace(lo[1], hi[1], grid):
475
+ r, vr = np.array([r0, vr0 * 1e3]) + E @ [a, b]
476
+ if r > 1.5:
477
+ nd = arc.fit_node(r, vr, q)
478
+ q = nd.q
479
+ if nd.bound or not bound:
480
+ B.append(nd)
481
+ P.append((a, b))
482
+ c, P = np.array([b.chi2 for b in B]), np.array(P)
483
+ cmin = min(cmin, c.min())
484
+ scale = max(1.0, cmin / dof)
485
+ W = np.r_[P[c - cmin < 16 * scale], [[0, 0]]] # box of the dchi2 < 16 s nodes and the best fit
486
+ d = np.ptp(W, 0) / 10 + 0.1
487
+ lo, hi = W.min(0) - d, W.max(0) + d
488
+ w = np.exp(-(c - c.min()) / 2 / scale)
489
+ out = [orb.state]
490
+ for k in rng.choice(len(B), n - 1, p=w / w.sum()):
491
+ b = B[k]
492
+ q = rng.multivariate_normal(b.q, np.linalg.pinv(b.jac.T @ b.jac) * scale)
493
+ x0, v0 = arc.state(q, b.r, b.vr)
494
+ if is_bound(x0, v0) or not bound:
495
+ out.append(np.r_[x0, v0])
496
+ return np.array(out)
497
+
498
+
499
+ def elements(x, v, gm=GM_BARY, frame=EQUATORIAL, center=BARYCENTRIC):
500
+ """Osculating ecliptic J2000 elements of a state (AU, AU/d) given in ``frame`` (equatorial = ICRS axes,
501
+ or ecliptic): dict a [AU], e, i, node, peri, M [deg], frame='ecliptic' and ``center`` (a label: pass
502
+ the GM that goes with it, GM_SUN for heliocentric)."""
503
+ _check(frame, center)
504
+ if frame == EQUATORIAL:
505
+ x, v = ECL @ np.asarray(x, float), ECL @ np.asarray(v, float)
506
+ else:
507
+ x, v = np.asarray(x, float), np.asarray(v, float)
508
+ r = np.linalg.norm(x)
509
+ h = np.cross(x, v)
510
+ hn = h / np.linalg.norm(h)
511
+ ev = np.cross(v, h) / gm - x / r
512
+ e = float(np.linalg.norm(ev))
513
+ a = float(1 / (2 / r - v @ v / gm))
514
+ n = np.cross([0, 0, 1.0], hn)
515
+ nu = np.arctan2(np.cross(ev, x) @ hn, ev @ x)
516
+ if e < 1:
517
+ E = 2 * np.arctan(np.sqrt((1 - e) / (1 + e)) * np.tan(nu / 2))
518
+ M = float(np.degrees(E - e * np.sin(E)) % 360)
519
+ else:
520
+ M = float("nan")
521
+ return dict(a=a, e=e, i=float(np.degrees(np.arccos(hn[2]))), node=float(np.degrees(np.arctan2(n[1], n[0])) % 360),
522
+ peri=float(np.degrees(np.arctan2(np.cross(n, ev) @ hn, n @ ev)) % 360), M=M, frame=ECLIPTIC, center=center)
523
+
524
+
525
+ def helio_elements(x, v, t0):
526
+ """Heliocentric osculating ecliptic elements (comparable with JPL/MPC) of a barycentric state at t0 (JD TDB)."""
527
+ from astropy.coordinates import get_body_barycentric_posvel
528
+ from astropy.time import Time
529
+ p, w = get_body_barycentric_posvel("sun", Time(t0, format="jd", scale="tdb"))
530
+ return elements(np.asarray(x) - p.xyz.to("au").value, np.asarray(v) - w.xyz.to("au/d").value, GM_SUN,
531
+ center=HELIOCENTRIC)
532
+
533
+
534
+ def _check(frame, center):
535
+ if frame not in (EQUATORIAL, ECLIPTIC) or center not in (BARYCENTRIC, HELIOCENTRIC):
536
+ raise ValueError(f"frame must be '{EQUATORIAL}' or '{ECLIPTIC}', center '{BARYCENTRIC}' or '{HELIOCENTRIC}'")
537
+
538
+
539
+ def _sun(t0):
540
+ """Barycentric ICRS state (6,) of the Sun at t0 (JD TDB)."""
541
+ from astropy.coordinates import get_body_barycentric_posvel
542
+ from astropy.time import Time
543
+ p, w = get_body_barycentric_posvel("sun", Time(t0, format="jd", scale="tdb"))
544
+ return np.r_[p.xyz.to("au").value, w.xyz.to("au/d").value]
545
+
546
+
547
+ def convert(states, t0, frame=ECLIPTIC, center=BARYCENTRIC, from_frame=EQUATORIAL, from_center=BARYCENTRIC):
548
+ """Cartesian states (6,) or (n, 6) [AU, AU/d] at t0 (JD TDB) from (from_frame, from_center) to (frame,
549
+ center). Frames: 'equatorial' (ICRS axes) or 'ecliptic' (J2000, obliquity EPS); centres: 'barycentric'
550
+ or 'heliocentric'. OrbitSift's own states are equatorial barycentric (the defaults of from_*)."""
551
+ _check(frame, center)
552
+ _check(from_frame, from_center)
553
+ s = np.array(states, float)
554
+ if from_frame == ECLIPTIC:
555
+ s[..., :3], s[..., 3:] = s[..., :3] @ ECL, s[..., 3:] @ ECL
556
+ if from_center != center:
557
+ s += _sun(t0) if from_center == HELIOCENTRIC else -_sun(t0)
558
+ if frame == ECLIPTIC:
559
+ s[..., :3], s[..., 3:] = s[..., :3] @ ECL.T, s[..., 3:] @ ECL.T
560
+ return s
561
+
562
+
563
+ def state_from_elements(a, e, i, node, peri, M, t0, helio=True, frame=EQUATORIAL, center=BARYCENTRIC):
564
+ """State (6,) from ecliptic J2000 elements [AU, deg] at t0 (JD TDB); heliocentric elements (JPL/MPC
565
+ style) by default. The state is barycentric equatorial (ICRS axes) unless frame / center say otherwise."""
566
+ i, node, peri, M = np.radians([i, node, peri, M])
567
+ gm = GM_SUN if helio else GM_BARY
568
+ E = M
569
+ for _ in range(50):
570
+ E = E - (E - e * np.sin(E) - M) / (1 - e * np.cos(E))
571
+ P = np.array([np.cos(node) * np.cos(peri) - np.sin(node) * np.sin(peri) * np.cos(i),
572
+ np.sin(node) * np.cos(peri) + np.cos(node) * np.sin(peri) * np.cos(i), np.sin(peri) * np.sin(i)])
573
+ Q = np.array([-np.cos(node) * np.sin(peri) - np.sin(node) * np.cos(peri) * np.cos(i),
574
+ -np.sin(node) * np.sin(peri) + np.cos(node) * np.cos(peri) * np.cos(i), np.cos(peri) * np.sin(i)])
575
+ nmo = np.sqrt(gm / a ** 3)
576
+ den = 1 - e * np.cos(E)
577
+ x = a * (np.cos(E) - e) * P + a * np.sqrt(1 - e * e) * np.sin(E) * Q
578
+ v = -a * nmo * np.sin(E) / den * P + a * nmo * np.sqrt(1 - e * e) * np.cos(E) / den * Q
579
+ x, v = ECL.T @ x, ECL.T @ v
580
+ if helio:
581
+ from astropy.coordinates import get_body_barycentric_posvel
582
+ from astropy.time import Time
583
+ p, w = get_body_barycentric_posvel("sun", Time(t0, format="jd", scale="tdb"))
584
+ x, v = x + p.xyz.to("au").value, v + w.xyz.to("au/d").value
585
+ s = np.r_[x, v]
586
+ return s if (frame, center) == (EQUATORIAL, BARYCENTRIC) else convert(s, t0, frame, center)
587
+
588
+
589
+ def free_fit(arc, r_guess, vr_guess=0.0):
590
+ """Exact barycentric two-body fit, bound or not, started near a known distance: the best of the (r, vr) nodes at
591
+ r_guess x (0.94 ... 1.06) and vr in {0, vr_guess}, then a free 6-parameter fit. Two least-squares problems instead of
592
+ ``fit``'s grid: for links whose distance the linker already knows (near mode). -> Orbit or None."""
593
+ nodes, q = [], None
594
+ for r in r_guess * np.array([0.94, 0.97, 1.0, 1.03, 1.06]):
595
+ for vr in sorted({0.0, float(vr_guess)}):
596
+ n = arc.fit_node(r, vr, q)
597
+ q = n.q
598
+ nodes.append(n)
599
+ best = min(nodes, key=lambda n: n.chi2)
600
+ p0 = arc.to_p6(*arc.state(best.q, best.r, best.vr))
601
+ p, chi2 = arc.fit6(p0)
602
+ return _orbit(arc, p if chi2 <= best.chi2 else p0)
603
+
604
+
605
+ def kepler_test(arc, kepler_rms_max=0.2, r_guess=None, **fit_kw):
606
+ """Does a bound barycentric orbit (``bound=False`` in fit_kw: any orbit) fit these detections to within
607
+ ``kepler_rms_max`` arcsec rms?
608
+ Linking assumes a simplified motion model; this rejects chance alignments that it lets through.
609
+ -> dict(passed, rms, r, a, e, i) (rms = inf when no bound orbit exists)."""
610
+ orb = fit(arc, r_guess=r_guess, **fit_kw)
611
+ if orb is None:
612
+ return dict(passed=False, rms=float("inf"), r=None, a=None, e=None, i=None)
613
+ el = orb.elements()
614
+ return dict(passed=bool(orb.rms <= kepler_rms_max), rms=orb.rms, r=orb.r, a=el["a"], e=el["e"], i=el["i"])