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.
- orbitsift/__init__.py +2 -0
- orbitsift/_native.py +13 -0
- orbitsift/ades.py +166 -0
- orbitsift/archives/__init__.py +244 -0
- orbitsift/archives/cadc.py +97 -0
- orbitsift/archives/decam_geom.json +1 -0
- orbitsift/archives/eso.py +213 -0
- orbitsift/archives/hsc_geom.json +2378 -0
- orbitsift/archives/ing.py +70 -0
- orbitsift/archives/listing.py +22 -0
- orbitsift/archives/noirlab.py +302 -0
- orbitsift/archives/ps1.py +59 -0
- orbitsift/archives/sdss.py +52 -0
- orbitsift/archives/smoka.py +369 -0
- orbitsift/blind.py +558 -0
- orbitsift/catalog.py +328 -0
- orbitsift/cli.py +2200 -0
- orbitsift/config.py +85 -0
- orbitsift/confirm.py +1030 -0
- orbitsift/data/nsc_dr2_k4m_ksb.csv.gz +0 -0
- orbitsift/dense.py +788 -0
- orbitsift/dynamics.py +235 -0
- orbitsift/expindex.py +456 -0
- orbitsift/extend.py +690 -0
- orbitsift/external.py +204 -0
- orbitsift/extract.py +148 -0
- orbitsift/growth.py +224 -0
- orbitsift/images.py +676 -0
- orbitsift/itf.py +154 -0
- orbitsift/known.py +716 -0
- orbitsift/link.py +509 -0
- orbitsift/lov.py +642 -0
- orbitsift/mcp_server.py +164 -0
- orbitsift/multiyear.py +409 -0
- orbitsift/net.py +265 -0
- orbitsift/orbit.py +614 -0
- orbitsift/plugins.py +97 -0
- orbitsift/precovery.py +187 -0
- orbitsift/presets/a2.json +85 -0
- orbitsift/presets/confirm_v1.json +190 -0
- orbitsift/presets/confirm_v2.json +236 -0
- orbitsift/presets/lostrec.json +74 -0
- orbitsift/recover.py +377 -0
- orbitsift/rubin.py +328 -0
- orbitsift/survey.py +268 -0
- orbitsift/tiles.py +58 -0
- orbitsift/unused.py +103 -0
- orbitsift/vet.py +304 -0
- orbitsift/workflow/__init__.py +5 -0
- orbitsift/workflow/models.py +103 -0
- orbitsift/workflow/sqlite.py +189 -0
- orbitsift-0.1.0.dist-info/METADATA +443 -0
- orbitsift-0.1.0.dist-info/RECORD +56 -0
- orbitsift-0.1.0.dist-info/WHEEL +4 -0
- orbitsift-0.1.0.dist-info/entry_points.txt +3 -0
- orbitsift-0.1.0.dist-info/licenses/LICENSE +28 -0
orbitsift/lov.py
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
"""Archive search along the line of variations (``orbitsift lov``): other seasons of a short-arc object in detection
|
|
2
|
+
catalogues.
|
|
3
|
+
|
|
4
|
+
The orbit uncertainty of an arc of days to weeks is close to one-dimensional: a valley in (distance, radial velocity).
|
|
5
|
+
The line of variations (LOV) follows it: a coordinate s along the long axis of the linear (r, vr) error ellipse of the
|
|
6
|
+
fit, the other five parameters (sky offset, tangential velocity, the perpendicular (r, vr) coordinate) refitted at each
|
|
7
|
+
s, from the best fit outwards until dchi2 > 16 x scale (scale = max(1, chi2/dof)), the orbit is unbound or r < 2 AU.
|
|
8
|
+
|
|
9
|
+
1. the LOV, densified by linear state interpolation (<= 20" between neighbours at every searched epoch); its width
|
|
10
|
+
from Gaussian draws of the five free parameters at ~40 nodes, per night: across tolerance = clip(q99 + 0.5",
|
|
11
|
+
1.5", 60"), and the error of s;
|
|
12
|
+
2. stage A: detections (any catalogue, through ``sources``) within the across tolerance of the LOV at their own
|
|
13
|
+
epoch and within 0.8 mag of the magnitude predicted at their s; nights within 0.45 d of an arc point are skipped;
|
|
14
|
+
3. stage B: candidates with overlapping s windows form groups; every member of a group with >= 2 nights seeds a
|
|
15
|
+
6-parameter refit from the LOV state at its s, grown greedily with members within 4" of the refit prediction (one
|
|
16
|
+
per exposure; accepted while bound, rms <= 0.2" and every added point <= 0.6"); a hit is grown once more over all
|
|
17
|
+
candidates;
|
|
18
|
+
4. the rules (pre-registered): a *hit* has >= 2 nights in one season other than the arc's own, or >= 3 such nights in
|
|
19
|
+
all; a *strong* hit has >= 3 new-season nights over >= 2 seasons, or >= 4, and magnitude offsets within 1.2 mag of
|
|
20
|
+
each other. Seasons are counted from the arc's mid-time, split half a year from it;
|
|
21
|
+
5. controls: the same search for the arc rotated by +3, -3, +6, -6 deg about the ecliptic pole (the best fit rotated,
|
|
22
|
+
the real residuals added). A target whose controls give a strong hit is not clean;
|
|
23
|
+
6. a catalogue hit is a locator: ``verify`` measures each point on its own image at a leave-one-out prediction, and
|
|
24
|
+
``leave_one_season_out`` checks that every season is predicted by the others.
|
|
25
|
+
|
|
26
|
+
Detections come through a small interface, so any catalogue works: a *source* is a callable ``source(box, mjd0, mjd1)``
|
|
27
|
+
-> dict of equal-length arrays with the keys of ``FIELDS`` (``site`` optional), for a sky box (ra0, ra1, dec0, dec1)
|
|
28
|
+
[deg] of the 1 x 1 deg tile grid (``tiles.tile``) and a UTC MJD range. ``nsc`` is the built-in source (NSC DR2).
|
|
29
|
+
"""
|
|
30
|
+
import numpy as np
|
|
31
|
+
from scipy.spatial import cKDTree
|
|
32
|
+
|
|
33
|
+
from . import catalog, orbit, tiles
|
|
34
|
+
from .precovery import COLOUR
|
|
35
|
+
|
|
36
|
+
RULES = dict(dchi=16.0, spacing=20.0, ndraw=24, tol_min=1.5, tol_add=0.5, meas=0.3, tol_max=60.0, magtol=0.8, night=0.45,
|
|
37
|
+
sig_cat=0.15, rms_max=0.2, res_max=0.6, link=4.0, dmag_spread=1.2)
|
|
38
|
+
CONTROLS = {1: 3.0, 2: -3.0, 3: 6.0, 4: -6.0} # control k: rotation about the ecliptic pole [deg]
|
|
39
|
+
FIELDS = ("mjd", "ra", "dec", "sig", "mag", "band", "exposure") # mjd: UTC mid-exposure; sig ["]; mag nan if none
|
|
40
|
+
IMAGE = dict(snr=5.0, cat_sep=1.0, loo_min=1.0, r_min=2.0, r_max=6.0, controls=24, ctl_frac=0.1)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def night(mjd):
|
|
44
|
+
return np.floor(np.asarray(mjd) - 0.5).astype(int)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def season(mjd, tmid):
|
|
48
|
+
"""Season relative to the arc (0 = its own), split half a year from its mid-time ``tmid`` (UTC MJD)."""
|
|
49
|
+
return np.floor((np.asarray(mjd) - tmid + 182.6) / 365.25).astype(int)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def seasons(mjd, gap=120.0):
|
|
53
|
+
"""Season labels of time-sorted or unsorted UTC MJDs: a new season after a gap > ``gap`` days (an opposition across
|
|
54
|
+
New Year stays one season), labelled by the calendar year of its first row."""
|
|
55
|
+
mjd = np.asarray(mjd, float)
|
|
56
|
+
o = np.argsort(mjd)
|
|
57
|
+
first = np.r_[True, np.diff(mjd[o]) > gap]
|
|
58
|
+
year = np.floor((mjd[o] - 51544.5) / 365.25 + 2000).astype(int) # calendar year to a day
|
|
59
|
+
lab = np.empty(len(mjd), int)
|
|
60
|
+
lab[o] = year[first][np.cumsum(first) - 1]
|
|
61
|
+
return lab
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _sep(a1, d1, a2, d2):
|
|
65
|
+
return np.hypot(((np.asarray(a1) - a2 + 180) % 360 - 180) * np.cos(np.radians(d2)), np.asarray(d1) - d2) * 3600
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _arc(mjd, ra, dec, sigma, site):
|
|
69
|
+
return orbit.Arc(mjd, ra, dec, sigma, site)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _sub(arc, m):
|
|
73
|
+
"""The rows m of an arc, with its reference (states at the same t0)."""
|
|
74
|
+
return orbit.Arc(arc.mjd[m], arc.ra[m], arc.dec[m], arc.sigma[m], arc.site[m], ref=arc.ref)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _local(arc, x0, v0):
|
|
78
|
+
"""Orbit of ``arc`` by a free 6-parameter fit from the state (x0, v0) at its t0, or None if unbound."""
|
|
79
|
+
p, _ = arc.fit6(arc.to_p6(np.asarray(x0), np.asarray(v0)))
|
|
80
|
+
o2 = orbit._orbit(arc, p)
|
|
81
|
+
return o2 if o2.bound else None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _rotz(deg):
|
|
85
|
+
c, s = np.cos(np.radians(deg)), np.sin(np.radians(deg))
|
|
86
|
+
return orbit.ECL.T @ np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) @ orbit.ECL
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def control_arc(arc, deg, o):
|
|
90
|
+
"""The arc rotated by ``deg`` about the ecliptic pole: its best fit ``o`` rotated, the residuals added (same times,
|
|
91
|
+
sites, sigmas; the rotated fit is its best fit, at the same t0)."""
|
|
92
|
+
R = _rotz(deg)
|
|
93
|
+
ra, dec = orbit.radec(R @ o.x0, R @ o.v0, o.t0, arc.jd, arc.obs)
|
|
94
|
+
dec = dec[0] - o.residuals[:, 1] / 3600
|
|
95
|
+
return _arc(arc.mjd, (ra[0] - o.residuals[:, 0] / 3600 / np.cos(np.radians(dec))) % 360, dec, arc.sigma, arc.site)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ---------------------------------------------------------------- the line of variations
|
|
99
|
+
class LOV:
|
|
100
|
+
"""Nodes along the LOV of ``orb`` (the fit of ``arc``): dicts s, p (the 5 free parameters), chi2, jac, x, v, r."""
|
|
101
|
+
|
|
102
|
+
def __init__(self, arc, orb, dchi=RULES["dchi"]):
|
|
103
|
+
self.arc, self.orb = arc, orb
|
|
104
|
+
self.scale = max(1.0, orb.chi2 / max(1, 2 * len(arc) - 6))
|
|
105
|
+
x, v, r0 = orb.x0, orb.v0, orb.r
|
|
106
|
+
vr0 = x @ v / r0
|
|
107
|
+
J = np.zeros((2, 6))
|
|
108
|
+
J[0, :3], J[1, :3], J[1, 3:] = x / r0, (v - vr0 * x / r0) / r0 * 1e3, x / r0 * 1e3
|
|
109
|
+
lam, E = np.linalg.eigh(J @ orb.cov @ J.T)
|
|
110
|
+
self.c0, self.el, self.es = np.array([r0, vr0 * 1e3]), E[:, 1], E[:, 0] # long, short axis (AU, 1e-3 AU/d)
|
|
111
|
+
self.sig_long = float(np.sqrt(max(lam[1], 1e-12)))
|
|
112
|
+
self.nodes = self._walk(dchi)
|
|
113
|
+
|
|
114
|
+
def state(self, p, s):
|
|
115
|
+
r, vr = self.c0 + self.el * s + self.es * p[4]
|
|
116
|
+
return self.arc.state(p[:4], r, vr)
|
|
117
|
+
|
|
118
|
+
def node(self, s, p0):
|
|
119
|
+
k = self.arc._lsq(lambda p: self.state(p, s), p0, 200)
|
|
120
|
+
x0, v0 = self.state(k.x, s)
|
|
121
|
+
return dict(s=float(s), p=k.x, chi2=2 * k.cost, jac=k.jac, x=x0, v=v0, bound=orbit.is_bound(x0, v0), r=float(np.linalg.norm(x0)))
|
|
122
|
+
|
|
123
|
+
def _walk(self, dchi):
|
|
124
|
+
o = self.orb
|
|
125
|
+
n0 = self.node(0.0, np.r_[self.arc.fit_node(o.r, o.x0 @ o.v0 / o.r * 1e3).q, 0.0])
|
|
126
|
+
cmin, lim = min(n0["chi2"], o.chi2), dchi * self.scale
|
|
127
|
+
out = [n0]
|
|
128
|
+
for sgn in (1, -1):
|
|
129
|
+
s, p, ds, prev = 0.0, n0["p"], 0.25 * self.sig_long, n0
|
|
130
|
+
for _ in range(600):
|
|
131
|
+
nd = self.node(s + sgn * ds, p)
|
|
132
|
+
if not nd["bound"] or nd["r"] < 2.0 or nd["chi2"] - cmin > lim:
|
|
133
|
+
if ds > 0.02 * self.sig_long:
|
|
134
|
+
ds /= 4
|
|
135
|
+
continue
|
|
136
|
+
break
|
|
137
|
+
dc = abs(nd["chi2"] - prev["chi2"])
|
|
138
|
+
out.append(nd)
|
|
139
|
+
s, p, prev = nd["s"], nd["p"], nd
|
|
140
|
+
ds *= 0.7 if dc > 1.0 else (1.5 if dc < 0.25 else 1.0)
|
|
141
|
+
out.sort(key=lambda d: d["s"])
|
|
142
|
+
self.cmin = min(d["chi2"] for d in out)
|
|
143
|
+
return out
|
|
144
|
+
|
|
145
|
+
def states(self):
|
|
146
|
+
return np.array([np.r_[d["x"], d["v"]] for d in self.nodes]), np.array([d["s"] for d in self.nodes])
|
|
147
|
+
|
|
148
|
+
def dense(self, jd, ob, spacing=RULES["spacing"]):
|
|
149
|
+
"""Densified states (M, 6) and s (M,): adjacent sky positions <= ``spacing``" apart at every jd (JD TDB, observer
|
|
150
|
+
positions ob)."""
|
|
151
|
+
S, s = self.states()
|
|
152
|
+
U = orbit.unit(*orbit.radec(S[:, :3], S[:, 3:], self.orb.t0, jd, ob)) # (N, m, 3)
|
|
153
|
+
sep = np.degrees(np.arccos(np.clip((U[1:] * U[:-1]).sum(-1), -1, 1))).max(1) * 3600
|
|
154
|
+
k = np.maximum(1, np.ceil(sep / spacing)).astype(int)
|
|
155
|
+
i = np.repeat(np.arange(len(k)), k) # segment of each new state
|
|
156
|
+
f = (np.arange(k.sum()) - np.repeat(np.cumsum(k) - k, k) + 1) / np.repeat(k, k)
|
|
157
|
+
return np.r_[S[:1], S[i] + f[:, None] * (S[i + 1] - S[i])], np.r_[s[:1], s[i] + f * (s[i + 1] - s[i])]
|
|
158
|
+
|
|
159
|
+
def draws(self, ndraw=RULES["ndraw"], seed=3):
|
|
160
|
+
"""(states (K, 6), s of their node (K,)): ``ndraw`` Gaussian draws of the 5 free parameters at ~40 nodes."""
|
|
161
|
+
rng = np.random.default_rng(seed)
|
|
162
|
+
X, s = [], []
|
|
163
|
+
for i in np.unique(np.linspace(0, len(self.nodes) - 1, 40).round().astype(int)):
|
|
164
|
+
d = self.nodes[i]
|
|
165
|
+
for p in rng.multivariate_normal(d["p"], np.linalg.pinv(d["jac"].T @ d["jac"]) * self.scale, ndraw):
|
|
166
|
+
x0, v0 = self.state(p, d["s"])
|
|
167
|
+
if orbit.is_bound(x0, v0):
|
|
168
|
+
X.append(np.r_[x0, v0])
|
|
169
|
+
s.append(d["s"])
|
|
170
|
+
return np.array(X).reshape(-1, 6), np.array(s)
|
|
171
|
+
|
|
172
|
+
def summary(self):
|
|
173
|
+
el = [orbit.elements(d["x"], d["v"]) for d in self.nodes]
|
|
174
|
+
rng = lambda v: [float(min(v)), float(max(v))]
|
|
175
|
+
return dict(n_nodes=len(self.nodes), s_range=rng([d["s"] for d in self.nodes]), sig_long=self.sig_long, scale=self.scale,
|
|
176
|
+
chi2_best=self.cmin, r_range=rng([d["r"] for d in self.nodes]), a_range=rng([e["a"] for e in el]),
|
|
177
|
+
q_range=rng([e["a"] * (1 - e["e"]) for e in el]), i_range=rng([e["i"] for e in el]))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def project(Up, sp, Uq):
|
|
181
|
+
"""Polyline Up (M, 3) of unit vectors with coordinate sp (M,); points Uq (N, 3) -> distance to the polyline ["] and
|
|
182
|
+
the s of the nearest point on it (N,). A point beyond an end is measured from the end."""
|
|
183
|
+
i = cKDTree(Up).query(Uq)[1]
|
|
184
|
+
best_d, best_s = np.full(len(Uq), np.inf), np.zeros(len(Uq))
|
|
185
|
+
for j0 in (i - 1, i):
|
|
186
|
+
j0 = np.clip(j0, 0, len(Up) - 2)
|
|
187
|
+
A, AB = Up[j0], Up[j0 + 1] - Up[j0]
|
|
188
|
+
t = np.clip(((Uq - A) * AB).sum(1) / np.maximum((AB * AB).sum(1), 1e-30), 0, 1)
|
|
189
|
+
F = A + t[:, None] * AB
|
|
190
|
+
d = np.linalg.norm(Uq - F, axis=1) / np.maximum(np.linalg.norm(F, axis=1), 1e-12)
|
|
191
|
+
m = d < best_d
|
|
192
|
+
best_d[m], best_s[m] = d[m], (sp[j0] + t * (sp[j0 + 1] - sp[j0]))[m]
|
|
193
|
+
return np.degrees(best_d) * 3600, best_s
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _radec_chunks(X, t0, jd, ob, n=64):
|
|
197
|
+
"""Unit vectors (M, m, 3) of states X (M, 6) at m epochs, in chunks of n epochs."""
|
|
198
|
+
return np.concatenate([orbit.unit(*orbit.radec(X[:, :3], X[:, 3:], t0, jd[k:k + n], ob[k:k + n]))
|
|
199
|
+
for k in range(0, len(jd), n)], 1) if len(jd) else np.zeros((len(X), 0, 3))
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def widths(L, XD, sD, jd, ob, rules=RULES):
|
|
203
|
+
"""Per epoch: across tolerance ["], s window and d(position)/ds ["/unit s] from the node draws."""
|
|
204
|
+
Xd, sd = L.draws(rules["ndraw"])
|
|
205
|
+
Ud, Uw = _radec_chunks(XD, L.orb.t0, jd, ob), _radec_chunks(Xd, L.orb.t0, jd, ob)
|
|
206
|
+
tol, sw = np.zeros(len(jd)), np.zeros(len(jd))
|
|
207
|
+
for m in range(len(jd)):
|
|
208
|
+
a, s = project(Ud[:, m], sD, Uw[:, m])
|
|
209
|
+
inn = (s > sD[0]) & (s < sD[-1]) # draws beyond the LOV ends lie along it, not across
|
|
210
|
+
a99 = float(np.percentile(a[inn] if inn.sum() > 20 else a, 99))
|
|
211
|
+
tol[m] = min(max(rules["tol_min"], a99 + rules["tol_add"]), rules["tol_max"])
|
|
212
|
+
g = np.degrees(np.arccos(np.clip((Ud[1:, m] * Ud[:-1, m]).sum(-1), -1, 1))) * 3600 / np.maximum(np.diff(sD), 1e-30)
|
|
213
|
+
sw[m] = float(np.percentile(np.abs(s - sd), 99)) + rules["meas"] / max(float(np.median(g)), 1e-9)
|
|
214
|
+
return tol, sw
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def abs_mag(arc, orb, mags):
|
|
218
|
+
"""Median r-band absolute magnitude of the arc's (mag, band) rows (TNO colours, ``precovery.COLOUR``), or None."""
|
|
219
|
+
x = orbit.kepler(orb.x0, orb.v0, arc.jd - orb.t0)[0]
|
|
220
|
+
h = [m - COLOUR.get(b, 0.0) - 5 * np.log10(np.linalg.norm(p) * np.linalg.norm(p - o))
|
|
221
|
+
for (m, b), p, o in zip(mags or [], x, arc.obs) if m is not None and np.isfinite(m)]
|
|
222
|
+
return float(np.median(h)) if h else None
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# ---------------------------------------------------------------- detections
|
|
226
|
+
def nsc(box, mjd0, mjd1, sigma=0.15):
|
|
227
|
+
"""Built-in source: NSC DR2 single-night objects of a tile box (``catalog.orphan_arrays``, cached; the precovery
|
|
228
|
+
cuts), each matched to its DECam exposure (|mjd - exposure start| < 0.003 d) for the mid-exposure time, band and
|
|
229
|
+
magnitude in that band."""
|
|
230
|
+
O = catalog.orphan_arrays(box)
|
|
231
|
+
ok = (0.7 <= O["fwhm"]) & (O["fwhm"] <= 3.0) & (O["flags"] < 4) & ~O["static"] & (O["mjd"] >= mjd0 - 1) & (O["mjd"] <= mjd1 + 1)
|
|
232
|
+
ex = catalog.exposures(box)
|
|
233
|
+
if not ok.any() or not len(ex["mjd"]):
|
|
234
|
+
return dict({k: np.zeros(0) for k in ("mjd", "ra", "dec", "sig", "mag")}, band=np.zeros(0, str), exposure=np.zeros(0, str))
|
|
235
|
+
o = np.argsort(ex["mjd"])
|
|
236
|
+
em = ex["mjd"][o]
|
|
237
|
+
j = np.clip(np.searchsorted(em, O["mjd"]), 1, len(em) - 1)
|
|
238
|
+
j = np.where(np.abs(O["mjd"] - em[j - 1]) < np.abs(O["mjd"] - em[j]), j - 1, j)
|
|
239
|
+
ok &= np.abs(O["mjd"] - em[j]) < 0.003
|
|
240
|
+
e = o[j[ok]]
|
|
241
|
+
band = ex["filt"][e]
|
|
242
|
+
mag = np.full(len(e), np.nan)
|
|
243
|
+
for b, col in catalog.MAG_COLUMNS.items():
|
|
244
|
+
m = band == b
|
|
245
|
+
mag[m] = O[col][ok][m]
|
|
246
|
+
mid = ex["mjd"][e] + ex["exptime"][e] / 2 / 86400
|
|
247
|
+
keep = (mid >= mjd0) & (mid <= mjd1)
|
|
248
|
+
return dict(mjd=mid[keep], ra=O["ra"][ok][keep] % 360, dec=O["dec"][ok][keep], sig=np.full(keep.sum(), sigma), mag=mag[keep],
|
|
249
|
+
band=band[keep], exposure=ex["name"][e][keep])
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _tiles(L, start, end, site, step=2.0, spacing=360.0):
|
|
253
|
+
"""Tiles the LOV crosses between two UTC MJDs (a 2-day grid; LOV points <= 0.1 deg apart, inside the tiles' 0.15 deg
|
|
254
|
+
margin) -> {tile id: tile}."""
|
|
255
|
+
mj = np.arange(start, end + step, step)
|
|
256
|
+
jd, ob = orbit.observer(mj, site)
|
|
257
|
+
X, _ = L.dense(jd, ob, spacing)
|
|
258
|
+
ra, dec = orbit.radec(X[:, :3], X[:, 3:], L.orb.t0, jd, ob)
|
|
259
|
+
ids = np.unique(np.c_[np.floor(ra.ravel() % 360), np.floor(np.minimum(dec.ravel(), 89.999))], axis=0)
|
|
260
|
+
out = {}
|
|
261
|
+
for a, d in ids:
|
|
262
|
+
t = tiles.tile(a + 0.5, d + 0.5)
|
|
263
|
+
out[t["id"]] = t
|
|
264
|
+
return out
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def detections(L, sources, start, end, site="W84", cache=None, log=print):
|
|
268
|
+
"""Every detection of every source in the tiles the LOV crosses, de-duplicated (overlapping tiles: same source,
|
|
269
|
+
exposure and position to 0.05"). ``cache`` (a dict, shared between calls) keeps loaded tiles by (source name, tile
|
|
270
|
+
id, range): one source's tile is never served for another's."""
|
|
271
|
+
cache = {} if cache is None else cache
|
|
272
|
+
T = _tiles(L, start, end, site)
|
|
273
|
+
parts = []
|
|
274
|
+
for name, src in sources.items():
|
|
275
|
+
for tid, t in sorted(T.items()):
|
|
276
|
+
key = (name, tid, float(start), float(end))
|
|
277
|
+
if key not in cache:
|
|
278
|
+
cache[key] = {k: np.asarray(v) for k, v in src(tuple(t["box"]), start, end).items()}
|
|
279
|
+
d = cache[key]
|
|
280
|
+
n = len(d["mjd"])
|
|
281
|
+
parts.append(dict(d, source=np.full(n, name, object), site=np.asarray(d.get("site", np.full(n, site)), object)))
|
|
282
|
+
log(f" {len(T)} tiles x {len(sources)} source(s)")
|
|
283
|
+
if not parts:
|
|
284
|
+
return None
|
|
285
|
+
D = {k: np.concatenate([p[k] for p in parts]) for k in FIELDS + ("source", "site")}
|
|
286
|
+
D["exposure"] = D["exposure"].astype(str)
|
|
287
|
+
key = np.char.add(np.char.add(D["source"].astype(str), "|"), D["exposure"])
|
|
288
|
+
_, u = np.unique(np.c_[np.unique(key, return_inverse=True)[1], np.round(D["ra"] * 72000), np.round(D["dec"] * 72000)],
|
|
289
|
+
axis=0, return_index=True)
|
|
290
|
+
return {k: v[np.sort(u)] for k, v in D.items()}
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
# ---------------------------------------------------------------- stage A
|
|
294
|
+
def stage_a(arc, orb, L, D, H=None, rules=RULES, log=print):
|
|
295
|
+
"""Candidates: detections within the across tolerance of the LOV at their epoch and the magnitude window."""
|
|
296
|
+
if D is None or not len(D["mjd"]):
|
|
297
|
+
return [], {}
|
|
298
|
+
am = np.sort(arc.mjd)
|
|
299
|
+
j = np.clip(np.searchsorted(am, D["mjd"]), 1, len(am) - 1)
|
|
300
|
+
far = np.minimum(np.abs(D["mjd"] - am[j - 1]), np.abs(D["mjd"] - am[j])) >= rules["night"]
|
|
301
|
+
D = {k: v[far] for k, v in D.items()}
|
|
302
|
+
ekey = np.char.add(np.char.add(D["source"].astype(str), "|"), D["exposure"])
|
|
303
|
+
ue, first, inv = np.unique(ekey, return_index=True, return_inverse=True)
|
|
304
|
+
if not len(ue):
|
|
305
|
+
return [], {}
|
|
306
|
+
# exposure epochs (per site), one per night for the widths and the densification
|
|
307
|
+
emjd, esite = D["mjd"][first], D["site"][first]
|
|
308
|
+
ejd, eob = np.zeros(len(ue)), np.zeros((len(ue), 3))
|
|
309
|
+
for s in set(esite.tolist()):
|
|
310
|
+
m = esite == s
|
|
311
|
+
ejd[m], eob[m] = orbit.observer(emjd[m], s)
|
|
312
|
+
en = night(emjd)
|
|
313
|
+
_, wn = np.unique(en, return_index=True)
|
|
314
|
+
XD, sD = L.dense(ejd[wn], eob[wn], rules["spacing"])
|
|
315
|
+
# coarse pass, all detections at once: distance to the LOV sampled every 0.1 deg at their own epoch
|
|
316
|
+
XC, _ = L.dense(ejd[wn], eob[wn], 360.0)
|
|
317
|
+
Uq = orbit.unit(D["ra"], D["dec"])
|
|
318
|
+
near = np.zeros(len(Uq), bool)
|
|
319
|
+
lim = np.cos(np.radians((180.0 + rules["tol_max"] + 30.0) / 3600)) # half step + tolerance + slack
|
|
320
|
+
order = np.argsort(inv, kind="stable") # detections by exposure
|
|
321
|
+
bound = np.searchsorted(inv[order], np.arange(len(ue) + 1))
|
|
322
|
+
step = max(1, int(4e6 // max(1, len(XC)))) # ~100 MB per einsum block
|
|
323
|
+
for e0 in range(0, len(ue), 512):
|
|
324
|
+
e1 = min(e0 + 512, len(ue))
|
|
325
|
+
UC = _radec_chunks(XC, orb.t0, ejd[e0:e1], eob[e0:e1]) # (n_c, exposures, 3)
|
|
326
|
+
q = order[bound[e0]:bound[e1]]
|
|
327
|
+
for k in range(0, len(q), step):
|
|
328
|
+
qq = q[k:k + step]
|
|
329
|
+
near[qq] = np.einsum("cnk,nk->cn", UC[:, inv[qq] - e0], Uq[qq]).max(0) > lim
|
|
330
|
+
sel = np.unique(inv[near])
|
|
331
|
+
log(f" stage A: {len(ue)} exposures, {len(Uq)} detections, {near.sum()} near the LOV on {len(sel)} exposures; "
|
|
332
|
+
f"dense LOV {len(sD)} states")
|
|
333
|
+
if not len(sel):
|
|
334
|
+
return [], dict(n_exposures=len(ue), n_detections=len(Uq), n_dense=len(sD))
|
|
335
|
+
tol_n, sw_n = widths(L, XD, sD, ejd[wn], eob[wn], rules)
|
|
336
|
+
W = {int(n): (a, w) for n, a, w in zip(en[wn], tol_n, sw_n)}
|
|
337
|
+
tmid = 0.5 * (arc.mjd.min() + arc.mjd.max())
|
|
338
|
+
cands = []
|
|
339
|
+
qi = order[near[order]]
|
|
340
|
+
lo = np.searchsorted(inv[qi], sel)
|
|
341
|
+
hi = np.searchsorted(inv[qi], sel, "right")
|
|
342
|
+
for c0 in range(0, len(sel), 64):
|
|
343
|
+
E = sel[c0:c0 + 64]
|
|
344
|
+
UD = _radec_chunks(XD, orb.t0, ejd[E], eob[E])
|
|
345
|
+
for n, e in enumerate(E):
|
|
346
|
+
q = qi[lo[c0 + n]:hi[c0 + n]]
|
|
347
|
+
tol, sw = W[int(en[e])]
|
|
348
|
+
acr, s = project(UD[:, n], sD, Uq[q])
|
|
349
|
+
m = acr <= tol
|
|
350
|
+
if m.any():
|
|
351
|
+
cands.append((q[m], acr[m], s[m], np.full(m.sum(), tol), np.full(m.sum(), sw), np.full(m.sum(), e)))
|
|
352
|
+
if not cands:
|
|
353
|
+
return [], dict(n_exposures=len(ue), n_detections=len(Uq), n_near=int(near.sum()), n_dense=len(sD))
|
|
354
|
+
q, acr, s, tol, sw, e = (np.concatenate(z) for z in zip(*cands))
|
|
355
|
+
dm = np.full(len(q), np.nan)
|
|
356
|
+
if H is not None: # magnitude at the nearest dense state, at the detection's epoch
|
|
357
|
+
ia = np.clip(np.searchsorted(sD, s), 0, len(sD) - 1)
|
|
358
|
+
x = orbit.kepler(XD[ia, :3], XD[ia, 3:], (ejd[e] - orb.t0)[:, None], rows=True)[:, 0]
|
|
359
|
+
pred = H + np.array([COLOUR.get(b, 0.0) for b in D["band"][q]]) + 5 * np.log10(np.linalg.norm(x, axis=1) * np.linalg.norm(x - eob[e], axis=1))
|
|
360
|
+
dm = D["mag"][q] - pred
|
|
361
|
+
keep = ~(np.abs(dm) > rules["magtol"]) # no magnitude: kept
|
|
362
|
+
q, acr, s, tol, sw, e, dm = q[keep], acr[keep], s[keep], tol[keep], sw[keep], e[keep], dm[keep]
|
|
363
|
+
out = [dict(e=int(ee), source=str(D["source"][qq]), exposure=str(D["exposure"][qq]), mid=float(D["mjd"][qq]), site=str(D["site"][qq]),
|
|
364
|
+
ra=float(D["ra"][qq]), dec=float(D["dec"][qq]), mag=float(D["mag"][qq]), band=str(D["band"][qq]),
|
|
365
|
+
dm=None if not np.isfinite(d_) else float(d_), across=float(a_), s=float(s_), tol=float(t_), sw=float(w_),
|
|
366
|
+
night=int(night(D["mjd"][qq])), season=int(season(D["mjd"][qq], tmid)))
|
|
367
|
+
for qq, a_, s_, t_, w_, ee, d_ in zip(q, acr, s, tol, sw, e, dm)]
|
|
368
|
+
sea = {}
|
|
369
|
+
for k in sel:
|
|
370
|
+
z = sea.setdefault(int(season(emjd[k], tmid)), [0, set(), 0.0])
|
|
371
|
+
z[0] += 1
|
|
372
|
+
z[1].add(int(en[k]))
|
|
373
|
+
z[2] = max(z[2], W[int(en[k])][0])
|
|
374
|
+
stats = dict(n_exposures=len(ue), n_detections=len(Uq), n_near=int(near.sum()), n_dense=len(sD), n_cands=len(out),
|
|
375
|
+
seasons={str(y): dict(n_exp=a, n_nights=len(b), tol_max=round(c, 2)) for y, (a, b, c) in sorted(sea.items())})
|
|
376
|
+
return out, stats
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
# ---------------------------------------------------------------- stage B
|
|
380
|
+
def _extend(arc, G, sigma):
|
|
381
|
+
return arc.extend([g["mid"] for g in G], [g["ra"] for g in G], [g["dec"] for g in G], sigma=sigma, site=[g["site"] for g in G])
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def refit(arc, G, p0, rules=RULES):
|
|
385
|
+
"""6-parameter fit of the arc plus points G from p0 -> (ok, p6, x0, v0, rms, residuals of G ["])."""
|
|
386
|
+
a = _extend(arc, G, rules["sig_cat"])
|
|
387
|
+
q, _ = a.fit6(p0)
|
|
388
|
+
x, v = a.from_p6(q)
|
|
389
|
+
r2 = a.residuals(x, v) * np.r_[a.sigma, a.sigma]
|
|
390
|
+
n = len(a)
|
|
391
|
+
res = np.hypot(r2[:n], r2[n:])[len(arc):]
|
|
392
|
+
rms = float(np.sqrt(np.mean(r2 ** 2)))
|
|
393
|
+
return bool(orbit.is_bound(x, v) and rms <= rules["rms_max"] and res.max() <= rules["res_max"]), q, x, v, rms, res
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _pool(pool):
|
|
397
|
+
"""(jd, observer positions, ra, dec, exposure index) arrays of candidates (any sites)."""
|
|
398
|
+
mid, site = np.array([c["mid"] for c in pool]), np.array([c["site"] for c in pool], object)
|
|
399
|
+
jd, ob = np.zeros(len(pool)), np.zeros((len(pool), 3))
|
|
400
|
+
for s in set(site.tolist()):
|
|
401
|
+
m = site == s
|
|
402
|
+
jd[m], ob[m] = orbit.observer(mid[m], s)
|
|
403
|
+
return jd, ob, np.array([c["ra"] for c in pool]), np.array([c["dec"] for c in pool]), np.array([c["e"] for c in pool])
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def grow(arc, orb, G, q, x, v, pool, ob, rules=RULES):
|
|
407
|
+
"""Add pool members within ``link``" of the current prediction, nearest first, one per exposure, refit after each."""
|
|
408
|
+
jd, obs, ra, de, ee = ob
|
|
409
|
+
used, tried = {g["e"] for g in G}, np.zeros(len(pool), bool)
|
|
410
|
+
while True:
|
|
411
|
+
pr, pd = orbit.radec(x, v, orb.t0, jd, obs)
|
|
412
|
+
d = _sep(ra, de, pr[0], pd[0])
|
|
413
|
+
d[np.isin(ee, list(used)) | tried] = np.inf
|
|
414
|
+
i = int(np.argmin(d)) if len(d) else 0
|
|
415
|
+
if not len(d) or d[i] >= rules["link"]:
|
|
416
|
+
return G, q, x, v
|
|
417
|
+
tried[i] = True
|
|
418
|
+
r = refit(arc, G + [pool[i]], q, rules)
|
|
419
|
+
if r[0]:
|
|
420
|
+
G, (q, x, v) = G + [pool[i]], r[1:4]
|
|
421
|
+
used.add(pool[i]["e"])
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def verdict(G, arc_nights):
|
|
425
|
+
"""(hit, new nights, {season: nights}) by the pre-registered rule; season 0 (the arc's own) does not count."""
|
|
426
|
+
nn = sorted({c["night"] for c in G} - set(arc_nights))
|
|
427
|
+
ss = {}
|
|
428
|
+
for c in G:
|
|
429
|
+
if c["night"] in nn and c["season"] != 0:
|
|
430
|
+
ss.setdefault(c["season"], set()).add(c["night"])
|
|
431
|
+
ns = {y: len(v) for y, v in sorted(ss.items())}
|
|
432
|
+
return bool(max(ns.values(), default=0) >= 2 or sum(ns.values()) >= 3), nn, ns
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def strong(ns, dm, rules=RULES):
|
|
436
|
+
"""The strong tier: >= 3 new-season nights over >= 2 seasons, or >= 4; magnitude offsets within dmag_spread."""
|
|
437
|
+
n = sum(ns.values())
|
|
438
|
+
return bool(((n >= 3 and len(ns) >= 2) or n >= 4) and (np.ptp(dm) if dm else 0.0) <= rules["dmag_spread"])
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def stage_b(arc, orb, L, C, rules=RULES):
|
|
442
|
+
"""Groups, seeded refits, growth, iteration over all candidates -> results (strong first) and group counts."""
|
|
443
|
+
S, sn = L.states()
|
|
444
|
+
an = sorted(set(night(arc.mjd).tolist()))
|
|
445
|
+
C = [dict(c, i=i) for i, c in enumerate(c for c in C if c["night"] not in an)]
|
|
446
|
+
groups, cur, hi = [], [], -np.inf
|
|
447
|
+
for c in sorted(C, key=lambda c: c["s"]):
|
|
448
|
+
if cur and c["s"] - c["sw"] > hi:
|
|
449
|
+
groups.append(cur)
|
|
450
|
+
cur, hi = [], -np.inf
|
|
451
|
+
cur.append(c)
|
|
452
|
+
hi = max(hi, c["s"] + c["sw"])
|
|
453
|
+
if cur:
|
|
454
|
+
groups.append(cur)
|
|
455
|
+
multi = [g for g in groups if len({c["night"] for c in g}) >= 2]
|
|
456
|
+
res, seen = [], set()
|
|
457
|
+
for g in multi:
|
|
458
|
+
gob = _pool(g)
|
|
459
|
+
for c in sorted(g, key=lambda c: c["across"]): # every member is a seed
|
|
460
|
+
st = np.array([np.interp(c["s"], sn, S[:, j]) for j in range(6)])
|
|
461
|
+
r = refit(arc, [c], arc.to_p6(st[:3], st[3:]), rules)
|
|
462
|
+
if not r[0]:
|
|
463
|
+
continue
|
|
464
|
+
G, q, x, v = grow(arc, orb, [c], *r[1:4], g, gob, rules)
|
|
465
|
+
key = frozenset(m["i"] for m in G)
|
|
466
|
+
if len({m["night"] for m in G}) < 2 or key in seen:
|
|
467
|
+
continue
|
|
468
|
+
seen.add(key)
|
|
469
|
+
hit, nn, ns = verdict(G, an)
|
|
470
|
+
res.append(dict(hit=hit, q=q, x=x, v=v, members=[m["i"] for m in G]))
|
|
471
|
+
cob = _pool(C) if C else None
|
|
472
|
+
for r in res:
|
|
473
|
+
G = [C[i] for i in r["members"]]
|
|
474
|
+
if r["hit"]: # iteration: grow over ALL candidates
|
|
475
|
+
G, r["q"], r["x"], r["v"] = grow(arc, orb, G, r["q"], r["x"], r["v"], C, cob, rules)
|
|
476
|
+
ok, q, x, v, rms, rr = refit(arc, G, r["q"], rules)
|
|
477
|
+
hit, nn, ns = verdict(G, an)
|
|
478
|
+
dm = [c["dm"] for c in G if c["dm"] is not None]
|
|
479
|
+
r.update(hit=bool(hit and ok), n=len(G), new_nights=len(nn), nights=nn, new_season_nights={str(k): n for k, n in ns.items()},
|
|
480
|
+
members=[c["i"] for c in G], rms=rms, res=rr.round(3).tolist(), elements=orbit.elements(x, v), x=x, v=v,
|
|
481
|
+
points=[{k: c[k] for k in ("source", "exposure", "mid", "site", "ra", "dec", "mag", "band", "dm", "s", "across", "night", "season")}
|
|
482
|
+
for c in G])
|
|
483
|
+
r["strong"] = bool(r["hit"] and strong(ns, dm, rules))
|
|
484
|
+
r.pop("q")
|
|
485
|
+
res.sort(key=lambda r: (-r["strong"], -r["hit"], -r["new_nights"], -r["n"]))
|
|
486
|
+
out, sk = [], set()
|
|
487
|
+
for r in res:
|
|
488
|
+
k = frozenset(r["members"])
|
|
489
|
+
if k not in sk:
|
|
490
|
+
sk.add(k)
|
|
491
|
+
out.append(r)
|
|
492
|
+
return out, dict(n_groups=len(groups), n_multi=len(multi))
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def search(arc, sources, start, end, mags=None, H=None, site="W84", r_min=5.0, r_max=200.0, cache=None, rules=RULES, log=print,
|
|
496
|
+
start_state=None):
|
|
497
|
+
"""The LOV search of one arc (orbit.Arc) in ``sources`` ({name: source}) between two UTC MJDs. mags: the arc's
|
|
498
|
+
(mag, band) rows for the magnitude window, or H: r-band absolute magnitude (neither: no magnitude cut); start_state:
|
|
499
|
+
(x0, v0) at arc.t0 to start a local fit from instead of ``orbit.fit``'s grid (controls: the rotated best fit).
|
|
500
|
+
-> dict(status, lov, H, stage_a, n_groups, n_multi, n_hits, n_strong, results)."""
|
|
501
|
+
orb = _local(arc, *start_state) if start_state else orbit.fit(arc, r_min, r_max)
|
|
502
|
+
if orb is None:
|
|
503
|
+
return dict(status="no_orbit", n_hits=0, n_strong=0, results=[])
|
|
504
|
+
L = LOV(arc, orb, rules["dchi"])
|
|
505
|
+
H = abs_mag(arc, orb, mags) if H is None else H
|
|
506
|
+
log(f" LOV: {len(L.nodes)} nodes, a {L.summary()['a_range'][0]:.0f}-{L.summary()['a_range'][1]:.0f} AU")
|
|
507
|
+
C, st = stage_a(arc, orb, L, detections(L, sources, start, end, site, cache, log), H, rules, log)
|
|
508
|
+
R, g = stage_b(arc, orb, L, C, rules)
|
|
509
|
+
log(f" stage B: {len(C)} candidates, {g['n_multi']} multi-night groups, {sum(r['hit'] for r in R)} hits, "
|
|
510
|
+
f"{sum(r['strong'] for r in R)} strong")
|
|
511
|
+
return dict(status="searched", orbit=orb, lov=L.summary(), H=H, stage_a=st, **g, n_hits=sum(r["hit"] for r in R),
|
|
512
|
+
n_strong=sum(r["strong"] for r in R), results=R[:30])
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def run(arc, sources, start, end, mags=None, H=None, controls=tuple(CONTROLS), site="W84", r_min=5.0, r_max=200.0, rules=RULES,
|
|
516
|
+
log=print):
|
|
517
|
+
"""``search`` on the arc and on its controls (CONTROLS: rotations about the ecliptic pole), sharing one tile cache;
|
|
518
|
+
then leave-one-season-out on the arc plus the best strong hit. -> dict(real, controls {k: search}, clean, loso)."""
|
|
519
|
+
cache = {}
|
|
520
|
+
log("real arc")
|
|
521
|
+
real = search(arc, sources, start, end, mags, H, site, r_min, r_max, cache, rules, log)
|
|
522
|
+
if real["status"] != "searched":
|
|
523
|
+
return dict(real=real, controls={}, clean=None)
|
|
524
|
+
H = real["H"] if H is None else H
|
|
525
|
+
o = real["orbit"]
|
|
526
|
+
ctl = {}
|
|
527
|
+
for k in controls:
|
|
528
|
+
log(f"control k{k} ({CONTROLS[k]:+g} deg)")
|
|
529
|
+
R = _rotz(CONTROLS[k])
|
|
530
|
+
ctl[k] = search(control_arc(arc, CONTROLS[k], o), sources, start, end, None, H, site, r_min, r_max, cache, rules, log,
|
|
531
|
+
(R @ o.x0, R @ o.v0))
|
|
532
|
+
out = dict(real=real, controls=ctl, clean=not any(c.get("n_strong") for c in ctl.values()))
|
|
533
|
+
best = next((r for r in real.get("results", []) if r["strong"]), None)
|
|
534
|
+
if best:
|
|
535
|
+
P = best["points"]
|
|
536
|
+
a2 = arc.extend([p["mid"] for p in P], [p["ra"] for p in P], [p["dec"] for p in P], sigma=rules["sig_cat"], site=[p["site"] for p in P])
|
|
537
|
+
out["loso"] = leave_one_season_out(a2, r_min, r_max, start=_local(a2, best["x"], best["v"]))
|
|
538
|
+
return out
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
# ---------------------------------------------------------------- checks of a hit
|
|
542
|
+
def _pred(orb, mjd, site, n=300, seed=5):
|
|
543
|
+
"""Best-fit RA, Dec at UTC MJDs from ``site`` and the 68% radius ["] of n linear-covariance draws."""
|
|
544
|
+
S = np.r_[[orb.state], np.random.default_rng(seed).multivariate_normal(orb.state, orb.cov, n)]
|
|
545
|
+
RA, DE = orbit.predict(S, orb.t0, np.atleast_1d(mjd), site)
|
|
546
|
+
return RA[0], DE[0], np.percentile(_sep(RA[1:], DE[1:], RA[0], DE[0]), 68.3, axis=0)
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def leave_one_season_out(arc, r_min=5.0, r_max=200.0, gap=120.0, n=300, start=None):
|
|
550
|
+
"""Each season (``seasons``: split at gaps > ``gap`` days) left out once: the orbit of the others (a local fit from
|
|
551
|
+
the orbit of all rows, ``start`` or ``orbit.fit``) predicts its first and last rows. A season passes when every offset
|
|
552
|
+
is <= max(1", 3 x the 68% radius of the prediction from n covariance draws).
|
|
553
|
+
-> {season: dict(rows, rms, a, offsets, s68, passed)} (passed None: fewer than 4 rows left, or no bound orbit)."""
|
|
554
|
+
lab = seasons(arc.mjd, gap)
|
|
555
|
+
full = start or orbit.fit(arc, r_min, r_max)
|
|
556
|
+
out = {}
|
|
557
|
+
for y in sorted(set(lab.tolist())):
|
|
558
|
+
keep, m = lab != y, np.flatnonzero(lab == y)
|
|
559
|
+
if keep.sum() < 4:
|
|
560
|
+
out[str(y)] = dict(rows=int(len(m)), passed=None, why="fewer than 4 rows left")
|
|
561
|
+
continue
|
|
562
|
+
o = _local(_sub(arc, keep), full.x0, full.v0) if full else None
|
|
563
|
+
if o is None:
|
|
564
|
+
out[str(y)] = dict(rows=int(len(m)), passed=None, why="no orbit without this season")
|
|
565
|
+
continue
|
|
566
|
+
k = m[[int(np.argmin(arc.mjd[m])), int(np.argmax(arc.mjd[m]))]]
|
|
567
|
+
k = np.unique(k)
|
|
568
|
+
off, s68 = [], []
|
|
569
|
+
for j in k:
|
|
570
|
+
ra, de, s = _pred(o, arc.mjd[j], arc.site[j], n)
|
|
571
|
+
off.append(float(_sep(arc.ra[j], arc.dec[j], ra[0], de[0])))
|
|
572
|
+
s68.append(float(s[0]))
|
|
573
|
+
out[str(y)] = dict(rows=int(len(m)), rms=o.rms, a=o.elements()["a"], offsets=off, s68=s68,
|
|
574
|
+
passed=bool(all(d <= max(1.0, 3 * s) for d, s in zip(off, s68))))
|
|
575
|
+
return out
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def verify(arc, points, cutouts, r_min=5.0, r_max=200.0, rules=IMAGE, state=None):
|
|
579
|
+
"""Measure each hit point on its own image. Per point (dict with mid, ra, dec, site and night, e.g. a hit's
|
|
580
|
+
``points``): the orbit of the arc plus the other points predicts it (68% radius s68); ``loo_ok`` if the catalogue
|
|
581
|
+
position is within max(1", 3 s68). ``cutouts(point)`` -> paths of cutouts (``archives.write_cut`` format) holding
|
|
582
|
+
it; on the first that covers it a PSF fit (``extend.point``) within R = clip(3 s68, 2", 6") of the prediction:
|
|
583
|
+
``img_ok`` at S/N >= 5, point-like, not on a Legacy Survey source and within 1" of the catalogue position; the same
|
|
584
|
+
fit at 24 control offsets (60-120") gives the control pass rate. Verified = loo_ok and img_ok; the arc is refitted
|
|
585
|
+
with the verified image positions. ``confirmed``: verified points on >= 2 nights of one season other than the arc's,
|
|
586
|
+
refit bound with rms <= 0.2". The orbits are local fits from ``state`` (x0, v0 at arc.t0: the hit's ``x``, ``v``) or
|
|
587
|
+
from ``orbit.fit`` of the arc plus all points. Point status: ``measured``, ``off_image`` (no cutout holds it) or
|
|
588
|
+
``failed`` (a download or a frame's calibration query failed: ``error``; unknown, not absent).
|
|
589
|
+
-> dict(points, verified, failed, new_season_nights, orbit, confirmed)."""
|
|
590
|
+
from . import extend, images
|
|
591
|
+
sig = RULES["sig_cat"]
|
|
592
|
+
P = [dict(p) for p in points]
|
|
593
|
+
if state is None:
|
|
594
|
+
full = orbit.fit(_extend(arc, P, sig), r_min, r_max)
|
|
595
|
+
state = (full.x0, full.v0) if full else None
|
|
596
|
+
for j, p in enumerate(P):
|
|
597
|
+
o = _local(_extend(arc, P[:j] + P[j + 1:], sig), *state) if state else None
|
|
598
|
+
if o is None:
|
|
599
|
+
p.update(status="no_loo_orbit", loo_ok=False, img_ok=False)
|
|
600
|
+
continue
|
|
601
|
+
ra, de, s = _pred(o, p["mid"], p["site"])
|
|
602
|
+
ra, de, s68 = float(ra[0]), float(de[0]), float(s[0])
|
|
603
|
+
R = float(np.clip(3 * s68, rules["r_min"], rules["r_max"]))
|
|
604
|
+
p.update(pred_ra=ra, pred_dec=de, s68=s68, R=R, loo_sep=float(_sep(p["ra"], p["dec"], ra, de)))
|
|
605
|
+
p["loo_ok"] = p["loo_sep"] <= max(rules["loo_min"], 3 * s68)
|
|
606
|
+
p.update(status="off_image", img_ok=False)
|
|
607
|
+
ok = lambda m: bool(m and m["snr"] >= rules["snr"] and images.point_like(m["snr"], m["shape"]) and not m["masked"] and m["offset"] <= R)
|
|
608
|
+
try:
|
|
609
|
+
paths = cutouts(p) or []
|
|
610
|
+
except extend.SKIP as e: # a failed download is a failure, never "not on the image"
|
|
611
|
+
p.update(status="failed", error=f"cutouts: {type(e).__name__}: {str(e)[:200]}")
|
|
612
|
+
continue
|
|
613
|
+
for path in paths:
|
|
614
|
+
try:
|
|
615
|
+
fr = extend.Frame(path, ra, de)
|
|
616
|
+
x, y = fr.sky2pix(ra, de)
|
|
617
|
+
if not (np.isfinite(x[0]) and 20 < x[0] < fr.r.shape[1] - 20 and 20 < y[0] < fr.r.shape[0] - 20):
|
|
618
|
+
continue
|
|
619
|
+
m = extend.point(fr, ra, de, R)
|
|
620
|
+
c = np.cos(np.radians(de))
|
|
621
|
+
ctl = [ok(extend.point(fr, ra + dx / 3600 / c, de + dy / 3600, R)) for dx, dy in extend.CONTROLS[:rules["controls"]]]
|
|
622
|
+
except extend.SKIP as e: # e.g. the Gaia or Legacy Survey query of the calibration
|
|
623
|
+
p.update(status="failed", error=f"{path}: {type(e).__name__}: {str(e)[:200]}")
|
|
624
|
+
continue
|
|
625
|
+
p.update(status="measured", path=str(path), meas=m, ctl_n=len(ctl), ctl_pass=int(sum(ctl)),
|
|
626
|
+
img_ok=ok(m) and float(_sep(m["ra"], m["dec"], p["ra"], p["dec"])) <= rules["cat_sep"])
|
|
627
|
+
p.pop("error", None)
|
|
628
|
+
break
|
|
629
|
+
V = [p for p in P if p["loo_ok"] and p["img_ok"]]
|
|
630
|
+
o = None
|
|
631
|
+
if V:
|
|
632
|
+
a2 = arc.extend([p["mid"] for p in V], [p["meas"]["ra"] for p in V], [p["meas"]["dec"] for p in V],
|
|
633
|
+
sigma=[max(p["meas"]["sig"], 0.05) for p in V], site=[p["site"] for p in V])
|
|
634
|
+
o = _local(a2, *state)
|
|
635
|
+
tmid = 0.5 * (arc.mjd.min() + arc.mjd.max())
|
|
636
|
+
per = {}
|
|
637
|
+
for p in V:
|
|
638
|
+
y = int(season(p["mid"], tmid))
|
|
639
|
+
if y != 0 and int(night(p["mid"])) not in set(night(arc.mjd).tolist()):
|
|
640
|
+
per.setdefault(y, set()).add(int(night(p["mid"])))
|
|
641
|
+
return dict(points=P, verified=len(V), failed=sum(p["status"] == "failed" for p in P), new_season_nights={str(k): len(v) for k, v in sorted(per.items())},
|
|
642
|
+
orbit=o, confirmed=bool(o is not None and o.bound and o.rms <= RULES["rms_max"] and max(map(len, per.values()), default=0) >= 2))
|