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/link.py ADDED
@@ -0,0 +1,509 @@
1
+ """Link single-night detections of a slow distant mover across nights, with exact parallax.
2
+
3
+ Model (Bernstein & Khushalani 2000, AJ 120, 3323): tangent-plane frame (e1 east, e2 north, e3 = line of
4
+ sight to the field centre); the object is at barycentric X = (alpha + adot t, beta + bdot t, 1) / gamma,
5
+ gamma = 1 / distance, plus a small radial velocity gdot and the Sun's pull as a uniform shrink of the
6
+ position (c = GM gamma^3 t^2 / 2):
7
+
8
+ theta_x = (alpha (1 - c) + adot t - gamma x_E) / (1 + gdot t - c - gamma z_E) (same for y)
9
+
10
+ with (x_E, y_E, z_E) the observer in that frame. For fixed gamma, u = theta + gamma (E_xy - theta E_z)
11
+ moves on a straight line, so linking is a search for straight lines in u across >= 3 nights. A
12
+ triple's gamma is solved in closed form (u is linear in gamma), so the gamma grid only sets the seed
13
+ tolerance, not the precision.
14
+ """
15
+ import numpy as np
16
+ from scipy.spatial import cKDTree
17
+
18
+ from . import _native
19
+ from .orbit import GM_SUN, centre_ra, observer, unit
20
+
21
+ AS = np.pi / 180 / 3600 # one arcsec in radians
22
+
23
+
24
+ def frame(ra0, dec0):
25
+ """Rows e1 (east), e2 (north), e3 (line of sight) of the tangent frame at (ra0, dec0), in ICRS."""
26
+ a, d = np.radians(ra0), np.radians(dec0)
27
+ return np.array([[-np.sin(a), np.cos(a), 0],
28
+ [-np.sin(d) * np.cos(a), -np.sin(d) * np.sin(a), np.cos(d)],
29
+ [np.cos(d) * np.cos(a), np.cos(d) * np.sin(a), np.sin(d)]])
30
+
31
+
32
+ def to_plane(ra, dec, mjd, ra0, dec0, site="W84"):
33
+ """Gnomonic coordinates theta (n, 2) [rad] and observer position in the frame (n, 3) [AU]. site: an MPC code, or a
34
+ function mjd (UTC) -> barycentric ICRS observer positions (n, 3) [AU], or one MPC code per row."""
35
+ R = frame(ra0, dec0)
36
+ v = unit(ra, dec) @ R.T
37
+ if callable(site):
38
+ E = site(mjd)
39
+ elif np.ndim(site): # one MPC code per row (NSC: W84, 695, V00)
40
+ site, mjd = np.asarray(site), np.atleast_1d(np.asarray(mjd, float))
41
+ E = np.empty((len(mjd), 3))
42
+ for s in np.unique(site):
43
+ m = site == s
44
+ E[m] = observer(mjd[m], str(s))[1]
45
+ else:
46
+ E = observer(mjd, site)[1]
47
+ return v[:, :2] / v[:, 2:], E @ R.T
48
+
49
+
50
+ def from_plane(theta, ra0, dec0):
51
+ """Inverse of the gnomonic projection -> RA, Dec [deg]."""
52
+ v = np.c_[theta, np.ones(len(theta))] @ frame(ra0, dec0)
53
+ v /= np.linalg.norm(v, axis=1)[:, None]
54
+ return np.degrees(np.arctan2(v[:, 1], v[:, 0])) % 360, np.degrees(np.arcsin(v[:, 2]))
55
+
56
+
57
+ def predict(p, t, E):
58
+ """theta (n, 2) for p = (alpha, beta, adot, bdot, gamma[, gdot]) [rad, rad/day, 1/AU, 1/day] at
59
+ times t [days from the frame epoch] seen from E (n, 3)."""
60
+ a, b, ad, bd, g = p[:5]
61
+ gd = p[5] if len(p) > 5 else 0.0
62
+ c = 0.5 * GM_SUN * g ** 3 * t ** 2
63
+ den = 1 + gd * t - c - g * E[:, 2]
64
+ out = np.empty((len(den), 2)) # (np.c_ costs more than the arithmetic)
65
+ out[:, 0] = (a * (1 - c) + ad * t - g * E[:, 0]) / den
66
+ out[:, 1] = (b * (1 - c) + bd * t - g * E[:, 1]) / den
67
+ return out
68
+
69
+
70
+ def jacobian(p, t, E):
71
+ J = np.empty((2 * len(t), len(p)))
72
+ for k in range(len(p)):
73
+ dp = np.zeros(len(p))
74
+ dp[k] = (1e-9, 1e-9, 1e-12, 1e-12, 1e-8, 1e-12)[k]
75
+ J[:, k] = ((predict(p + dp, t, E) - predict(p - dp, t, E)) / (2 * dp[k])).ravel()
76
+ return J
77
+
78
+
79
+ def fit(theta, t, E, g0, sig_g=None, sig=0.2, iters=8):
80
+ """Gauss-Newton on (alpha, beta, adot, bdot, gamma, gdot) with priors gamma ~ N(g0, sig_g) (none if
81
+ sig_g is None) and gdot ~ N(0, gamma x escape speed / 2). sig: astrometric sigma [arcsec].
82
+ Returns p, rms [arcsec], H^-1 (multiply by (sig AS)^2 for the covariance)."""
83
+ u = theta * (1 - g0 * E[:, 2:]) + g0 * E[:, :2]
84
+ A = np.c_[np.ones_like(t), t]
85
+ ca, cb = np.linalg.lstsq(A, u, rcond=None)[0].T
86
+ p = np.array([ca[0], cb[0], ca[1], cb[1], g0, 0.0])
87
+ s = sig * AS
88
+ pg = 0.0 if sig_g is None else s / sig_g
89
+ pd = s / (g0 * np.sqrt(2 * GM_SUN * g0) / 2)
90
+ P = np.zeros((2, 6))
91
+ P[0, 4], P[1, 5] = pg, pd
92
+ for _ in range(iters):
93
+ r = np.r_[(theta - predict(p, t, E)).ravel(), pg * (g0 - p[4]), -pd * p[5]]
94
+ J = np.r_[jacobian(p, t, E), P]
95
+ p = p + np.linalg.lstsq(J, r, rcond=None)[0]
96
+ res = theta - predict(p, t, E)
97
+ J = np.r_[jacobian(p, t, E), P]
98
+ return p, float(np.sqrt((res ** 2).sum(1).mean()) / AS), np.linalg.pinv(J.T @ J)
99
+
100
+
101
+ # Stacked fits: ``fit`` for many detection sets at once, bit for bit the same p and rms (same element-wise
102
+ # operations in the same order, one LAPACK dgelsd per set through the gufunc behind np.linalg.lstsq).
103
+ _DP = np.array([1e-9, 1e-9, 1e-12, 1e-12, 1e-8, 1e-12])
104
+ _DPM = np.diag(_DP)
105
+ _G3I, _G3M = [0, 5, 11], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0] # rows (of 13) with gamma, gamma + dg, gamma - dg
106
+ try:
107
+ _LSQ = np.linalg._umath_linalg.lstsq
108
+ except AttributeError: # pragma: no cover (private numpy API)
109
+ _LSQ = None
110
+
111
+
112
+ _PAIRCHUNK = 1e7 # link(): expected night-pair matches per block (one 82 MB catalogue tile asked for > 30 GB in one)
113
+
114
+
115
+ def _lstsq(A, b):
116
+ """np.linalg.lstsq(A[i], b[i], rcond=None)[0] for every i of a stack."""
117
+ if _LSQ is None: # pragma: no cover
118
+ return np.array([np.linalg.lstsq(a, y, rcond=None)[0] for a, y in zip(A, b)])
119
+ with np.errstate(over="ignore", divide="ignore", under="ignore", invalid="ignore"):
120
+ return _LSQ(A, b, np.finfo(float).eps * max(A.shape[-2:]), signature="ddd->ddid")[0]
121
+
122
+
123
+ def _cube(g):
124
+ """g ** 3 element by element as numpy scalars (as ``predict`` computes it for one p)."""
125
+ return np.array([x ** 3 for x in g.ravel()]).reshape(g.shape)
126
+
127
+
128
+ def _predict13(p, t, E):
129
+ """``predict`` at p (k, 6) and at the 12 central-difference points of ``jacobian`` -> (k, 13, n, 2)."""
130
+ P = np.concatenate([p[:, None], p[:, None] + _DPM, p[:, None] - _DPM], 1) # (k, 13, 6)
131
+ G3 = _cube(P[:, _G3I, 4])[:, _G3M]
132
+ P = P[..., None]
133
+ t, E = t[:, None], E[:, None]
134
+ c = (0.5 * GM_SUN * G3)[..., None] * t ** 2
135
+ g, omc = P[:, :, 4], 1 - c
136
+ den = 1 + P[:, :, 5] * t - c - g * E[..., 2]
137
+ out = np.empty(den.shape + (2,))
138
+ out[..., 0] = (P[:, :, 0] * omc + P[:, :, 2] * t - g * E[..., 0]) / den
139
+ out[..., 1] = (P[:, :, 1] * omc + P[:, :, 3] * t - g * E[..., 1]) / den
140
+ return out
141
+
142
+
143
+ def _predict1(p, t, E):
144
+ """``predict`` for k parameter sets at once -> (k, n, 2)."""
145
+ a, b, ad, bd, g, gd = (p[:, k:k + 1] for k in range(6))
146
+ c = (0.5 * GM_SUN * _cube(p[:, 4]))[:, None] * t ** 2
147
+ den = 1 + gd * t - c - g * E[..., 2]
148
+ return np.stack([(a * (1 - c) + ad * t - g * E[..., 0]) / den, (b * (1 - c) + bd * t - g * E[..., 1]) / den], -1)
149
+
150
+
151
+ def fit_many(theta, t, E, g0, sig_g=None, sig=0.2, iters=8):
152
+ """``fit`` for k sets of n detections at once: theta (k, n, 2), t (k, n), E (k, n, 3) -> p (k, 6),
153
+ rms (k,) ["], identical to fitting each set alone (H^-1 is not computed)."""
154
+ k, n = t.shape
155
+ u = theta * (1 - g0 * E[..., 2:]) + g0 * E[..., :2]
156
+ x = _lstsq(np.stack([np.ones_like(t), t], -1), u)
157
+ p = np.stack([x[:, 0, 0], x[:, 0, 1], x[:, 1, 0], x[:, 1, 1], np.full(k, g0), np.zeros(k)], 1)
158
+ s = sig * AS
159
+ pg = 0.0 if sig_g is None else s / sig_g
160
+ pd = s / (g0 * np.sqrt(2 * GM_SUN * g0) / 2)
161
+ J = np.zeros((k, 2 * n + 2, 6))
162
+ J[:, 2 * n, 4], J[:, 2 * n + 1, 5] = pg, pd
163
+ r = np.empty((k, 2 * n + 2, 1))
164
+ for _ in range(iters):
165
+ pr = _predict13(p, t, E)
166
+ r[:, :2 * n, 0] = (theta - pr[:, 0]).reshape(k, 2 * n)
167
+ r[:, 2 * n, 0], r[:, 2 * n + 1, 0] = pg * (g0 - p[:, 4]), -pd * p[:, 5]
168
+ J[:, :2 * n] = ((pr[:, 1:7] - pr[:, 7:13]) / (2 * _DP)[None, :, None, None]).reshape(k, 6, 2 * n).transpose(0, 2, 1)
169
+ p = p + _lstsq(J, r)[..., 0]
170
+ res = theta - _predict1(p, t, E)
171
+ return p, np.sqrt((res ** 2).sum(2).mean(1)) / AS
172
+
173
+
174
+ def _occupancy(pts, cell):
175
+ """Grid of ``cell``-sized squares (origin = min of pts) marking every square next to (3 x 3) one holding a
176
+ point: anything within ``cell`` of a point lies in a marked square."""
177
+ if not len(pts):
178
+ return None
179
+ o = pts.min(0)
180
+ ij = ((pts - o) / cell).astype(int) + 1
181
+ G = np.zeros(tuple(ij.max(0) + 2), bool)
182
+ for a in (-1, 0, 1):
183
+ for b in (-1, 0, 1):
184
+ G[ij[:, 0] + a, ij[:, 1] + b] = True
185
+ return o, G
186
+
187
+
188
+ def _maybe_near(grid, Q, cell):
189
+ """False where no point of ``_occupancy`` can lie within ``cell`` of Q (a cheap exact pre-filter)."""
190
+ if grid is None:
191
+ return np.zeros(len(Q), bool)
192
+ o, G = grid
193
+ ij = np.floor((Q - o) / cell) + 1
194
+ ok = (ij >= 0).all(1) & (ij[:, 0] < G.shape[0]) & (ij[:, 1] < G.shape[1])
195
+ out = np.zeros(len(Q), bool)
196
+ out[ok] = G[ij[ok, 0].astype(int), ij[ok, 1].astype(int)]
197
+ return out
198
+
199
+
200
+ def link(theta, t, night, E, gmin=1 / 150, gmax=1 / 30, sig=0.2, dgam=2e-4, nmin=4, rms_max=None, mag=None,
201
+ dmag=1.0, dtmax=40.0, rcap=600.0, gate=None, vfac=1.0, curvature=False, amask=None, ext_days=None):
202
+ """All sets of detections on >= nmin distinct nights that fit one bound orbit at 1/gamma in [1/gmax, 1/gmin].
203
+
204
+ theta, t (days from the frame epoch), night (int), E: from to_plane. sig: astrometric sigma [arcsec].
205
+ Seeds are night pairs (A, B), B - A <= dtmax days (None: no limit), with >= 1 night between them;
206
+ in-between detections near the interpolated u-line are checked exactly (closed-form gamma).
207
+ Seed sets of >= 3 nights (>= nmin without dtmax) get a 6-parameter fit and are then extended night
208
+ by night along the fitted orbit: the 10 detections nearest to the prediction (within rcap ") are
209
+ tried in order and the first that keeps rms <= rms_max is added.
210
+ mag (optional): magnitudes; detections in a set must agree within dmag.
211
+ gate (optional, e.g. 4): extension candidates farther from the prediction at their own epoch than
212
+ gate * sqrt((rms_max / sig)^2 (n + 1) + 12) * sig * sqrt(1 + lambda_max(J H J^T)) (H: the set's fit covariance
213
+ / sig^2 with the priors, n: set size) are not fitted. The linearised refit could not bring them under
214
+ rms_max, so the links are the same (gate 3 and 4: identical on the dense test tiles; 2 was not).
215
+ Near mode (8-35 AU, any direction of motion; defaults keep the TNO behaviour):
216
+ vfac: speed bound in units of the escape speed (1.1 admits near-parabolic comets).
217
+ curvature: seed tolerance from the Earth's real deviation from a straight line over dtmax (GM dtmax^2 / 8, x1.5,
218
+ + 0.002 AU) instead of a fixed 2 AU, and the pair radius grows by the u-plane offset a gamma mismatch adds between
219
+ the two nights; this allows dgam ~ 2e-3 at 8-35 AU with a tolerance of ~8" instead of 42".
220
+ amask (bool per detection): only these start a seed pair (the core of a region; the margin supplies later nights).
221
+ ext_days: extend only to nights within this many days of the seed's mean epoch (the motion model is not meant
222
+ for multi-season arcs at 8-14 AU).
223
+ Returns [(sorted detection indices, p, rms ["])], longest first, no two sharing >= 2 detections."""
224
+ rms_max = rms_max or 2.5 * sig
225
+ nseed = 3 if dtmax else nmin
226
+ nights = np.unique(night)
227
+ by = {n: np.flatnonzero(night == n) for n in nights}
228
+ byA = by if amask is None else {n: v[np.asarray(amask)[v]] for n, v in by.items()}
229
+ tn = {n: t[by[n]].mean() for n in nights}
230
+ En = {n: E[by[n]].mean(0) for n in nights}
231
+ ttree = {n: cKDTree(theta[by[n]]) for n in nights}
232
+ w = E[:, :2] - theta * E[:, 2:] # u = theta + gamma * w (exact)
233
+ dev = 1.5 * GM_SUN * dtmax ** 2 / 8 + 0.002 if curvature else 2.0 # AU: the observer's deviation from a line
234
+ tol = 4 * sig * AS + dgam / 2 * dev # seed tolerance: astrometry + gamma grid mismatch
235
+ cell = tol * 1.001
236
+ gsig = (gmax - gmin) / 2
237
+
238
+ def ok_g(g):
239
+ return gmin * 0.9 <= g <= gmax * 1.1
240
+
241
+ def fitsets(sets, g):
242
+ """``fit`` of many index lists (any sizes) -> [(p, rms)] in input order, stacked by size."""
243
+ out = [None] * len(sets)
244
+ bylen = {}
245
+ for q, ss in enumerate(sets):
246
+ bylen.setdefault(len(ss), []).append(q)
247
+ for qs in bylen.values():
248
+ ix = np.array([sets[q] for q in qs])
249
+ p, rms = fit_many(theta[ix], t[ix], E[ix], g, gsig, sig)
250
+ for z, q in enumerate(qs):
251
+ out[q] = (p[z], float(rms[z]))
252
+ return out
253
+
254
+ def radii(todo, ss, p, g0):
255
+ """Gate radius [rad] per night of todo for the set ss at p (fit prior centre g0): one finite-difference
256
+ evaluation (jacobian's steps) at the set's epochs and the nights' mean epochs."""
257
+ sl = sorted(ss)
258
+ m = len(sl)
259
+ tt = np.r_[t[sl], [tn[n] for n in todo]]
260
+ EE = np.r_[E[sl], E[[by[n][0] for n in todo]]]
261
+ pr = _predict13(np.asarray(p, float)[None], tt[None], EE[None])[0]
262
+ J = ((pr[1:7] - pr[7:13]) / (2 * _DP)[:, None, None]).transpose(1, 2, 0) # (epochs, 2, 6)
263
+ s_ = sig * AS
264
+ Js = J[:m].reshape(2 * m, 6)
265
+ A = Js.T @ Js
266
+ A[4, 4] += (s_ / gsig) ** 2
267
+ A[5, 5] += (s_ / (g0 * np.sqrt(2 * GM_SUN * g0) / 2)) ** 2
268
+ try:
269
+ H = np.linalg.inv(A)
270
+ except np.linalg.LinAlgError:
271
+ H = np.linalg.pinv(A)
272
+ M = np.eye(2) + J[m:] @ H @ J[m:].transpose(0, 2, 1) # prediction + measurement covariance / sig^2
273
+ K2 = gate ** 2 * ((rms_max / sig) ** 2 * (len(ss) + 1) + 12) * s_ ** 2
274
+ return np.sqrt(K2 * np.linalg.eigvalsh(M).max(1))
275
+
276
+ def pycands(n, q, med):
277
+ """The 10 detections of night n nearest to q within rcap (|mag - med| < dmag), nearest first."""
278
+ ix = by[n]
279
+ # ponytail: fixed radius, the refit decides; the validated runs used this (a
280
+ # covariance-based radius was always above the cap)
281
+ c = ix[ttree[n].query_ball_point(q, rcap * AS)]
282
+ if mag is not None:
283
+ c = c[np.abs(mag[c] - med) < dmag]
284
+ return c[np.argsort(np.linalg.norm(theta[c] - q, axis=1))][:10]
285
+
286
+ def extend(ss, p, g0):
287
+ """Night by night (nearest in time first), add the first of the 10 detections nearest to the
288
+ prediction (within rcap) that keeps the fit good. Candidates are fitted in stacks of ``budget``
289
+ tries across nights, cut at the first acceptance (the orbit, and so later predictions, change
290
+ there); the result is the same as trying them one at a time."""
291
+ ss = set(ss)
292
+ have = set(night[list(ss)])
293
+ tc = t[list(ss)].mean()
294
+ todo = sorted((n for n in nights if n not in have and (ext_days is None or abs(tn[n] - tc) <= ext_days)),
295
+ key=lambda n: abs(tn[n] - tc))
296
+ # ponytail: budget 40 first (most seeds are chance: nothing accepted), 1 after an acceptance (real
297
+ # movers accept night after night), x4 after a stack with none; tuned on dense survey tiles, not per tile
298
+ cands, pos, off, budget = {}, 0, 0, 40
299
+ R = med = None # per (ss, p): gate radii, median magnitude
300
+ while pos < len(todo):
301
+ tries, z, o = [], pos, off
302
+ while z < len(todo) and len(tries) < budget:
303
+ if z not in cands:
304
+ zz = range(z, min(z + max(1, budget // 4), len(todo)))
305
+ pr = predict(p, np.array([tn[todo[y]] for y in zz]), E[[by[todo[y]][0] for y in zz]])
306
+ if med is None and mag is not None:
307
+ med = np.median(mag[list(ss)])
308
+ if grid is not None: # native search; -1: a query left to numpy (ties, edge of rcap)
309
+ flat, cnt = grid.cands(pr, np.array([npos[todo[y]] for y in zz], np.int64),
310
+ None if mag is None else float(med), dmag, 10)
311
+ o_ = 0
312
+ for y, q, c_ in zip(zz, pr, cnt):
313
+ if c_ >= 0:
314
+ cands[y] = flat[o_:o_ + c_]
315
+ o_ += c_
316
+ else:
317
+ cands[y] = pycands(todo[y], q, med)
318
+ else:
319
+ for y, q in zip(zz, pr):
320
+ cands[y] = pycands(todo[y], q, med)
321
+ if gate is not None:
322
+ if R is None:
323
+ R = radii(todo, ss, p, g0)
324
+ gy = [y for y in zz if R[y] < rcap * AS and len(cands[y])]
325
+ if gy:
326
+ cat = np.concatenate([cands[y] for y in gy])
327
+ d2 = ((theta[cat] - predict(p, t[cat], E[cat])) ** 2).sum(1)
328
+ o_ = 0
329
+ for y in gy:
330
+ n_ = len(cands[y])
331
+ cands[y] = cands[y][d2[o_:o_ + n_] <= R[y] ** 2]
332
+ o_ += n_
333
+ c = cands[z][o:o + budget - len(tries)]
334
+ tries += [(z, k) for k in c]
335
+ z, o = (z + 1, 0) if o + len(c) >= len(cands[z]) else (z, o + len(c))
336
+ if not tries:
337
+ break
338
+ for (zh, k), (p2, rms2) in zip(tries, fitsets([list(ss | {k}) for _, k in tries], p[4])):
339
+ if rms2 <= rms_max and ok_g(p2[4]):
340
+ ss.add(k)
341
+ g0, p = p[4], p2
342
+ cands, pos, off, budget = {}, zh + 1, 0, 1
343
+ R = med = None
344
+ break
345
+ else:
346
+ pos, off, budget = z, o, budget * 4
347
+ return tuple(sorted(ss)), p
348
+
349
+ def pairs(A, B, r, u):
350
+ """Detection pairs (i of night A, j of night B) within r of each other in u, mag-consistent: one block in the
351
+ kd-tree's own order or, when the expected count exceeds _PAIRCHUNK, blocks of A's detections (the same pairs
352
+ in another order, same links; memory stays bounded on dense tiles)."""
353
+ iA = byA[A]
354
+ nA = len(iA)
355
+ if not nA:
356
+ return
357
+ k = 1 + int(4 * nA * len(by[B]) * min(1.0, np.pi * r * r / area) / _PAIRCHUNK)
358
+ for blk in [None] if k == 1 else np.array_split(np.arange(nA), k):
359
+ tA = (trees[A] if amask is None else cKDTree(u[iA])) if blk is None else cKDTree(u[iA[blk]])
360
+ pr = trees[B].sparse_distance_matrix(tA, r, output_type="ndarray")
361
+ if not len(pr):
362
+ continue
363
+ j, i = by[B][pr["i"]], iA[pr["j"] if blk is None else blk[pr["j"]]]
364
+ del pr
365
+ if mag is not None:
366
+ keep = np.abs(mag[i] - mag[j]) < dmag
367
+ i, j = i[keep], j[keep]
368
+ yield i, j
369
+
370
+ nat = _native.lib
371
+ theta, w, t = (np.ascontiguousarray(x, float) for x in (theta, w, t))
372
+ mag = None if mag is None else np.ascontiguousarray(mag, float)
373
+ grid = nat.NightGrid(theta, mag, [by[n].astype(np.int64) for n in nights], rcap * AS) if hasattr(nat, "NightGrid") else None
374
+ npos = {n: z for z, n in enumerate(nights)}
375
+ found, tried = {}, set()
376
+ bits = (len(theta) + 1).bit_length()
377
+ area = float(np.prod(np.ptp(theta, axis=0))) or 1.0 # tangent-plane area [rad^2], for pairs()
378
+ for g in np.arange(gmin + dgam / 2, gmax + dgam / 2, dgam):
379
+ u = theta + g * w
380
+ trees = {n: cKDTree(u[by[n]]) for n in nights}
381
+ grids = {}
382
+ gh = min(g + dgam / 2, gmax)
383
+ vmax = vfac * gh * np.sqrt(2 * GM_SUN * gh) # vfac x escape speed / distance [rad/day]
384
+ for ia, A in enumerate(nights):
385
+ for B in nights[ia + nseed - 1:]:
386
+ if dtmax and tn[B] - tn[A] > dtmax:
387
+ break
388
+ mids = [C for C in nights if A < C < B]
389
+ r = vmax * (tn[B] - tn[A]) + 2 * tol + (dgam / 2 * 1.1 * np.linalg.norm(En[B] - En[A]) if curvature else 0.0)
390
+ for i, j in pairs(A, B, r, u):
391
+ exact = nat is not None
392
+ if exact: # same hits; near-tol distances go to the kd-tree
393
+ npass, S, Kk, amb = nat.seed_hits(theta, w, u, t, mag, i, j, [(tn[C], by[C]) for C in mids], tol, cell,
394
+ 3.5 * sig * AS, gmin * 0.9, gmax * 1.1, dmag)
395
+ exact = not amb
396
+ hits = []
397
+ if not exact:
398
+ npass = np.zeros(len(i), int)
399
+ for C in mids if not exact else []:
400
+ if C not in grids:
401
+ grids[C] = _occupancy(u[by[C]], cell)
402
+ f = (tn[C] - t[i]) / (t[j] - t[i])
403
+ Q = u[i] + f[:, None] * (u[j] - u[i])
404
+ cnt = np.zeros(len(Q), int)
405
+ near = np.flatnonzero(_maybe_near(grids[C], Q, cell)) # exact test on these only
406
+ if len(near):
407
+ cnt[near] = trees[C].query_ball_point(Q[near], tol, return_length=True)
408
+ if not cnt.sum():
409
+ continue
410
+ s_ = np.repeat(np.arange(len(i)), cnt)
411
+ k = by[C][np.concatenate(trees[C].query_ball_point(Q[cnt > 0], tol)).astype(int)]
412
+ fs = f[s_][:, None]
413
+ R0 = theta[k] - theta[i[s_]] - fs * (theta[j[s_]] - theta[i[s_]])
414
+ R1 = w[k] - w[i[s_]] - fs * (w[j[s_]] - w[i[s_]])
415
+ gs = np.clip(-(R0 * R1).sum(1) / np.maximum((R1 ** 2).sum(1), 1e-30), gmin * 0.9, gmax * 1.1)
416
+ res = np.linalg.norm(R0 + gs[:, None] * R1, axis=1)
417
+ good = res < 3.5 * sig * AS * np.sqrt(1 + fs[:, 0] ** 2 + (1 - fs[:, 0]) ** 2)
418
+ if mag is not None:
419
+ good &= np.abs(mag[k] - mag[i[s_]]) < dmag
420
+ s_, k = s_[good], k[good]
421
+ npass += np.bincount(np.unique(s_), minlength=len(i))
422
+ hits.append((s_, k))
423
+ cand = np.flatnonzero(npass >= nseed - 2)
424
+ if not len(cand):
425
+ continue
426
+ if not exact:
427
+ S = np.concatenate([h[0] for h in hits])
428
+ Kk = np.concatenate([h[1] for h in hits])
429
+ seeds = []
430
+ o_ = np.argsort(S, kind="stable") # hits grouped by pair (Kk[S == q] per q was quadratic)
431
+ Ss, Ks = S[o_], Kk[o_]
432
+ lo, hi = np.searchsorted(Ss, cand, "left"), np.searchsorted(Ss, cand, "right")
433
+ for q, l_, h_ in zip(cand, lo, hi):
434
+ sset = tuple(sorted({i[q], j[q], *Ks[l_:h_]}))
435
+ kk = 0 # tried holds an exact int key per set, not the tuple:
436
+ for x in reversed(sset): # (index + 1) in its own bits-wide field; ~2.6x less memory
437
+ kk = (kk << bits) | (int(x) + 1)
438
+ if kk not in tried:
439
+ tried.add(kk)
440
+ seeds.append(sset)
441
+ if not seeds:
442
+ continue
443
+ fits = fitsets([list(s) for s in seeds], g)
444
+ # one wrong hit: refit without the worst point (a seed of nseed points cannot recover)
445
+ redo = [z for z, (s, (p, rms)) in enumerate(zip(seeds, fits)) if rms > rms_max and len(s) > nseed]
446
+ drop = []
447
+ for z in redo:
448
+ sl = list(seeds[z])
449
+ r = np.linalg.norm(theta[sl] - predict(fits[z][0], t[sl], E[sl]), axis=1)
450
+ drop.append(tuple(x for x, rr in zip(sl, r) if rr < r.max()))
451
+ for z, s, f2 in zip(redo, drop, fitsets([list(s) for s in drop], g)):
452
+ seeds[z], fits[z] = s, f2
453
+ for sset, (p, rms) in zip(seeds, fits):
454
+ if rms > rms_max or len(set(night[list(sset)])) < nseed or not ok_g(p[4]):
455
+ continue
456
+ if dtmax:
457
+ sset, p = extend(sset, p, g)
458
+ if len(set(night[list(sset)])) < nmin:
459
+ continue
460
+ p, rms = fitsets([list(sset)], p[4])[0]
461
+ found[sset] = (p, rms)
462
+ out, own = [], {} # own: detection -> kept links holding it
463
+ for s_ in sorted(found, key=lambda s_: (-len(s_), found[s_][1])):
464
+ hit = {}
465
+ for x in s_:
466
+ for o in own.get(x, ()):
467
+ hit[o] = hit.get(o, 0) + 1
468
+ if not any(v >= 2 for v in hit.values()):
469
+ for x in s_:
470
+ own.setdefault(x, []).append(len(out))
471
+ out.append((s_, *found[s_]))
472
+ return out
473
+
474
+
475
+ def link_detections(d, ra0, dec0, site="W84", dist_min=30.0, dist_max=150.0, **kw):
476
+ """Run ``link`` on a detection table d (dict of arrays ra, dec, mjd, V, night, id; see
477
+ catalog.detections) in the tangent frame at (ra0, dec0). Returns a list of link dicts:
478
+ n, nights, dist_au, rms, ra, dec (mean), V (median), ids, det = [[ra, dec, mjd, V], ...] (and sites, the MPC
479
+ station of each det row, when d has per-row stations)."""
480
+ if not len(d["ra"]):
481
+ return []
482
+ site = d.get("site", site) # per-row stations (catalog.with_sites) win over the single site
483
+ th, E = to_plane(d["ra"], d["dec"], d["mjd"], ra0, dec0, site)
484
+ t = d["mjd"] - d["mjd"].mean()
485
+ res = link(th, t, d["night"], E, gmin=1 / dist_max, gmax=1 / dist_min, mag=d["V"], **kw)
486
+ out = []
487
+ for s_, p, rms in res:
488
+ s_ = list(s_)
489
+ out.append(dict(n=len(s_), nights=int(len(set(d["night"][s_]))), dist_au=float(1 / p[4]), rms=float(rms),
490
+ ra=centre_ra(d["ra"][s_]), dec=float(np.mean(d["dec"][s_])), V=float(np.nanmedian(d["V"][s_])),
491
+ ids=[str(x) for x in d["id"][s_]],
492
+ det=[[float(d["ra"][k]), float(d["dec"][k]), float(d["mjd"][k]), float(d["V"][k])] for k in s_],
493
+ **({"sites": [str(d["site"][k]) for k in s_]} if "site" in d else {})))
494
+ return out
495
+
496
+
497
+ def synthetic_movers(rng, n, ra0, dec0, mjd, dist=(30, 150), site="W84"):
498
+ """n synthetic movers on random bound orbits near (ra0, dec0) at the given MJDs: returns t, E and a
499
+ list of (p, theta (len(mjd), 2)). Speeds 0.3-1.3 x circular, random direction."""
500
+ t = mjd - mjd.mean()
501
+ _, E = to_plane(np.full(len(mjd), ra0), np.full(len(mjd), dec0), mjd, ra0, dec0, site)
502
+ out = []
503
+ for _ in range(n):
504
+ g = 1 / rng.uniform(*dist)
505
+ v = np.sqrt(GM_SUN * g) * rng.uniform(0.3, 1.3) * g
506
+ ph = rng.uniform(0, 2 * np.pi)
507
+ p = np.array([*rng.uniform(-0.005, 0.005, 2), v * np.cos(ph), v * np.sin(ph), g])
508
+ out.append((p, predict(p, t, E)))
509
+ return t, E, out