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/dense.py
ADDED
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
"""Anchor linker for dense tiles (``link --mode dense``): the core of the survey's 2026 NSC DR2 production run.
|
|
2
|
+
|
|
3
|
+
``link.link`` seeds a link from every pair of nights and every distance slice. On tiles with many exposures per night
|
|
4
|
+
and many artefacts that is where the time goes, and most of what it links there is chance. This linker starts from
|
|
5
|
+
anchors instead and uses what the catalogue knows about each exposure (pointing, depth):
|
|
6
|
+
|
|
7
|
+
0. Row reductions before any pairing (``expcap``, ``clump``). An exposure with more than ``EXPMAX`` rows in the tile is
|
|
8
|
+
dropped whole (the static-source veto failed there) and covers nothing. The clump mask drops the rows of a sky cell
|
|
9
|
+
that holds more rows of its own exposure than max(``CMIN``, ``CLUMP`` x the exposure's mean), in 30" cells and then
|
|
10
|
+
in 120" cells on the survivors: ghosts, halos, stray light and trails, which move coherently from night to night
|
|
11
|
+
where no control reproduces them. A real object gives one row per exposure and only loses the rows that fall in a
|
|
12
|
+
masked cell.
|
|
13
|
+
1. Flags per row (``prep``): ``SEED`` (no row of another night within 0.5": not stationary), ``MERGED`` (a catalogue
|
|
14
|
+
row of >= 2 same-night detections), ``U`` (uncovered: no other deep enough exposure of the night covers the row, so a
|
|
15
|
+
same-night partner was impossible).
|
|
16
|
+
2. Same-night partners: rows of other exposures of the night whose offset fits a bound orbit at some distance.
|
|
17
|
+
3. Anchors: ``SEED`` rows with a partner or ``MERGED`` (confirmed on their night) or ``U``. A row that could have had a
|
|
18
|
+
partner and has none is never an anchor: that removes the single junk detections of nights with several exposures.
|
|
19
|
+
4. Seeds: the k nearest nights (within ``dtmax``) with an exposure covering the anchor deeply enough; a second row in
|
|
20
|
+
the bound-orbit capsule, a third on a later night of the list from a closed-form (gamma, gamma-dot).
|
|
21
|
+
5. Growth: a 6-parameter Gauss-Newton fit (per-row sigma from FWHM and S/N, one fixed distance prior: a link depends
|
|
22
|
+
only on its members), then night by night inside the fit's prediction ellipse; single detections join here. A link
|
|
23
|
+
stays in one season (the extension reaches ``dtext`` beyond its arc); multi-season objects need ``link.link``.
|
|
24
|
+
6. Kept: >= ``nmin`` nights; a link without any night of >= 2 detections needs ``nminu`` nights. Each link carries its
|
|
25
|
+
evidence counters (``tn``: nights with >= 2 detections, ``found`` / ``expn``: nights where the fit predicts a deep
|
|
26
|
+
exposure and the object is / should be there, ``intra_n`` / ``intra_c``: rows where another exposure of the night
|
|
27
|
+
could / did confirm it).
|
|
28
|
+
|
|
29
|
+
The compiled core (``orbitsift-native``, ``dense_link``) and ``_link_py`` here are the same algorithm; the core is the
|
|
30
|
+
survey's own (``dlcore``) with its input and output changed and six exact speed-ups (native/src/dense.rs, S1-S6: same
|
|
31
|
+
links, same order). On the test tiles both give the links of the survey's
|
|
32
|
+
binary: the same members, the same evidence counters, fit parameters and rms equal to float rounding (``RTOL``).
|
|
33
|
+
The Python code is the reference and the fallback without the extension: 6x slower than the core on a sparse catalogue
|
|
34
|
+
tile (5,004 rows: 1.3 s against 0.2 s), ~400x where many seeds grow (each a Gauss-Newton fit in Python).
|
|
35
|
+
"""
|
|
36
|
+
import math
|
|
37
|
+
|
|
38
|
+
import numpy as np
|
|
39
|
+
|
|
40
|
+
from . import _native, catalog
|
|
41
|
+
from .link import AS, to_plane
|
|
42
|
+
from .orbit import GM_SUN, centre_ra
|
|
43
|
+
|
|
44
|
+
F_SEED, F_MERGED, F_U = 1, 2, 4
|
|
45
|
+
VE = 0.0176 # AU / day: the observer's largest speed (orbit + rotation)
|
|
46
|
+
SIGFLOOR = 0.07 # arcsec per axis: astrometric floor (0.05" measured + systematics between exposures)
|
|
47
|
+
RDUP = 0.5 # arcsec: a row with a row of another night this close is stationary, never a seed
|
|
48
|
+
EXPMAX = 100000 # rows: an exposure with more rows in the tile is dropped whole (0: off)
|
|
49
|
+
CLUMP, CMIN, CELLS = 5.0, 6, (30.0, 120.0) # clump mask: factor over the exposure mean, floor, cell sizes ["] (CLUMP 0: off)
|
|
50
|
+
MAX_ROWS = 1000000 # rows after the reductions: a denser tile is not searched (``too_dense``)
|
|
51
|
+
RTOL = 1e-9 # relative difference of p, rms, nrms allowed between the core and _link_py
|
|
52
|
+
|
|
53
|
+
# The parameters in the order the core reads them; angles in arcsec (converted in ``_vector``).
|
|
54
|
+
PAR = dict(gmin=1 / 80, gmax=1 / 25, # 1 / distance [1/AU]; the box is widened to 0.9 gmin - 1.1 gmax
|
|
55
|
+
dtmax=40.0, # days: the three seed nights lie within this window
|
|
56
|
+
nmin=4, # nights of a link
|
|
57
|
+
dmag=1.0, # |V - reference V| (pairs: the anchor's; extension: the link median)
|
|
58
|
+
ktri=3.5, # sigmas: pair, three-point and three-night tests
|
|
59
|
+
kext=3.5, # sigmas: extension gate (prediction covariance + detection sigma)
|
|
60
|
+
nrms_max=2.0, # largest sqrt(chi2 / 2N) of a link
|
|
61
|
+
rcap=600.0, # arcsec: a night whose prediction is worse than this is not searched
|
|
62
|
+
k=8, # seed nights: the k nearest (in time) that cover the anchor deeply enough
|
|
63
|
+
maxb=200000, maxc=20000, # caps on candidate lists per (anchor, night) and (pair, night): counters skipb, skipc
|
|
64
|
+
dtext=60.0, # days: the extension reaches this far beyond the current arc
|
|
65
|
+
rcov=0.95 * 3600 + 400.0, # arcsec: an exposure covers the anchor within this (+ vcov |dt|) of its pointing
|
|
66
|
+
vcov=100.0, # arcsec / day
|
|
67
|
+
dcov=0.5, # mag: a covering exposure reaches V_anchor - dcov
|
|
68
|
+
bmargin=1.05, # margin on the bound-orbit speed limit
|
|
69
|
+
veto=0, # 1: drop links failing the completeness / same-night rules (``vet_ok``) in the core
|
|
70
|
+
npass=3, nminu=6, # extension passes; nights of a link without any night of >= 2 detections
|
|
71
|
+
sigcap=0.3, # arcsec: largest detection sigma
|
|
72
|
+
dtint=2e-4, # days: two detections of one night are distinct exposures if farther apart in time
|
|
73
|
+
bcstrong=0, # 1: the other two seed rows must also be confirmed or uncovered
|
|
74
|
+
rmiss=0.95 * 3600) # arcsec: exposure footprint radius (completeness, same-night evidence)
|
|
75
|
+
_ARCSEC = ("rcap", "rcov", "vcov", "sigcap", "rmiss")
|
|
76
|
+
STATS = ("anchors", "pairs", "base", "ctest", "seeds", "seedok", "trial", "raw", "vetoed", "skipb", "skipc", "unique")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _vector(par):
|
|
80
|
+
p = dict(PAR, **par)
|
|
81
|
+
bad = set(p) - set(PAR)
|
|
82
|
+
if bad:
|
|
83
|
+
raise ValueError(f"unknown dense parameter(s): {', '.join(sorted(bad))}")
|
|
84
|
+
for k in _ARCSEC:
|
|
85
|
+
p[k] = p[k] * AS
|
|
86
|
+
return [float(p[k]) for k in PAR], p
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ---------------------------------------------------------------- row reductions
|
|
90
|
+
def exposure_of(mjd, ndet, start, exptime):
|
|
91
|
+
"""Index of the exposure (start MJD, exptime [s]) of each catalogue row, or -1: the exposure whose
|
|
92
|
+
[start, start + exptime] holds the row's mjd (2e-4 d slack), else the nearest start or end within 0.002 d
|
|
93
|
+
(0.02 d for rows merged from several detections, whose mjd is a mean)."""
|
|
94
|
+
o = np.argsort(start, kind="stable")
|
|
95
|
+
s, ex = np.asarray(start, float)[o], np.asarray(exptime, float)[o] / 86400
|
|
96
|
+
mjd = np.asarray(mjd, float)
|
|
97
|
+
i = np.searchsorted(s, mjd, "right") - 1
|
|
98
|
+
best, bd = np.full(len(mjd), -1), np.full(len(mjd), np.inf)
|
|
99
|
+
for j in (i, i + 1, i - 1): # same order and strict < as the survey's converter
|
|
100
|
+
ok = (j >= 0) & (j < len(s))
|
|
101
|
+
jj = np.clip(j, 0, max(len(s) - 1, 0))
|
|
102
|
+
if not len(s):
|
|
103
|
+
break
|
|
104
|
+
inside = (s[jj] - 2e-4 <= mjd) & (mjd <= s[jj] + ex[jj] + 2e-4)
|
|
105
|
+
d = np.where(inside, 0.0, np.minimum(np.abs(mjd - s[jj]), np.abs(mjd - s[jj] - ex[jj])))
|
|
106
|
+
b = ok & (d < bd)
|
|
107
|
+
best[b], bd[b] = jj[b], d[b]
|
|
108
|
+
lim = np.where(np.nan_to_num(np.asarray(ndet, float), nan=1.0) > 1, 0.02, 0.002)
|
|
109
|
+
return np.where((best >= 0) & (bd <= lim), o[np.maximum(best, 0)], -1)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def expcap(expi, nexp, cap=EXPMAX):
|
|
113
|
+
"""Exposures (bool, length nexp) with more than ``cap`` rows (0: none)."""
|
|
114
|
+
return np.bincount(expi, minlength=nexp) > cap if cap else np.zeros(nexp, bool)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _ckey(expi, ra, dec, s):
|
|
118
|
+
"""Packed (scale s, exposure, sky cell of CELLS[s] arcsec) key."""
|
|
119
|
+
g = CELLS[s]
|
|
120
|
+
iy = np.floor((np.asarray(dec) + 90.0) * 3600 / g).astype(np.int64)
|
|
121
|
+
ix = np.floor(np.asarray(ra) * 3600 * np.cos(np.radians((iy + 0.5) * g / 3600 - 90.0)) / g).astype(np.int64)
|
|
122
|
+
return (s << 62) | (np.asarray(expi, np.int64) << 42) | (ix << 21) | iy
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def clump(expi, ra, dec, nexp, factor=CLUMP):
|
|
126
|
+
"""Rows in over-dense patches of their own exposure -> (bool per row, masked fraction of the exposures' area).
|
|
127
|
+
A cell is masked when it holds more rows of one exposure than max(CMIN, factor x that exposure's mean density x
|
|
128
|
+
the cell area), first in 30" cells, then in 120" cells on the rows left. The mean comes from the occupied 4'
|
|
129
|
+
blocks of the exposure (an underestimate of the area for sparse exposures, where CMIN rules anyway)."""
|
|
130
|
+
bad = np.zeros(len(ra), bool)
|
|
131
|
+
if not factor or not len(ra):
|
|
132
|
+
return bad, 0.0
|
|
133
|
+
m = (1 << 21) - 1
|
|
134
|
+
marea = 0.0
|
|
135
|
+
for s, g in enumerate(CELLS):
|
|
136
|
+
ok = np.flatnonzero(~bad)
|
|
137
|
+
u, inv, c = np.unique(_ckey(expi[ok], np.asarray(ra)[ok] % 360, np.asarray(dec)[ok], s), return_inverse=True,
|
|
138
|
+
return_counts=True)
|
|
139
|
+
e = (u >> 42) & ((1 << 20) - 1)
|
|
140
|
+
if s == 0:
|
|
141
|
+
blk = np.unique((e << 42) | (((u >> 21) & m) >> 3 << 21) | ((u & m) >> 3))
|
|
142
|
+
area = 64 * g * g * np.bincount(blk >> 42, minlength=nexp)
|
|
143
|
+
mu = np.bincount(expi, minlength=nexp) / np.maximum(area, 1.0) # rows per arcsec^2
|
|
144
|
+
b = c > np.maximum(CMIN, factor * mu[e] * g * g)
|
|
145
|
+
bad[ok[b[inv.ravel()]]] = True
|
|
146
|
+
marea += b.sum() * g * g
|
|
147
|
+
return bad, float(marea / max(area.sum(), 1.0))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def sigma(fwhm, magerr, cap=PAR["sigcap"]):
|
|
151
|
+
"""Per-axis astrometric sigma ["]: floor + centroid error fwhm / (2.355 SNR), SNR = 1.086 / magerr."""
|
|
152
|
+
s = np.sqrt(SIGFLOOR ** 2 + (np.asarray(fwhm) * np.asarray(magerr) / 2.557) ** 2)
|
|
153
|
+
return np.where(np.isfinite(s), np.minimum(s, cap), cap)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def prep(d, ex, ra0, dec0, site="W84", rmiss=PAR["rmiss"]):
|
|
157
|
+
"""Rows and exposures -> the core's arrays (rows sorted by night, flags).
|
|
158
|
+
d: ra, dec, mjd, V, night, ndet, sig ["], expi (index into ex); ex: mid (MJD), ra, dec, depth (V limit; -99 for an
|
|
159
|
+
exposure that covers nothing). Rows need a finite V. rmiss: exposure footprint radius ["] for the ``U`` flag."""
|
|
160
|
+
from scipy.spatial import cKDTree
|
|
161
|
+
keep = np.isfinite(d["V"]) & np.isfinite(d["ra"])
|
|
162
|
+
src = np.flatnonzero(keep)
|
|
163
|
+
src = src[np.argsort(d["night"][src], kind="stable")]
|
|
164
|
+
un, night = np.unique(d["night"][src], return_inverse=True)
|
|
165
|
+
night = night.ravel()
|
|
166
|
+
t0 = float(np.floor(d["mjd"][src].mean())) if len(src) else 0.0
|
|
167
|
+
th, E = to_plane(d["ra"][src], d["dec"][src], d["mjd"][src], ra0, dec0, site)
|
|
168
|
+
emjd = np.asarray(ex["mid"], float)
|
|
169
|
+
ok = np.isfinite(emjd)
|
|
170
|
+
eth, eE = to_plane(np.where(ok, ex["ra"], ra0), np.where(ok, ex["dec"], dec0), np.where(ok, emjd, t0), ra0, dec0, site)
|
|
171
|
+
en_night = np.floor(np.where(ok, emjd, 0) - 0.5)
|
|
172
|
+
en = np.searchsorted(un, en_night.astype(np.int64))
|
|
173
|
+
en = np.where(ok & (en < len(un)) & (un[np.minimum(en, max(len(un) - 1, 0))] == en_night) if len(un) else False, en, -1)
|
|
174
|
+
P = dict(x=th[:, 0].copy(), y=th[:, 1].copy(), t=d["mjd"][src] - t0, E=E, sig=np.asarray(d["sig"])[src] * AS,
|
|
175
|
+
V=np.asarray(d["V"])[src].astype(float), night=night.astype(np.int32), exp=np.asarray(d["expi"])[src].astype(np.int32),
|
|
176
|
+
src=src, t0=t0, ra0=ra0, dec0=dec0, nights=un, ecx=eth[:, 0].copy(), ecy=eth[:, 1].copy(),
|
|
177
|
+
et=np.where(ok, emjd, t0) - t0, edep=np.asarray(ex["depth"], float), eE=eE,
|
|
178
|
+
enight=np.asarray(en, np.int64).astype(np.int32))
|
|
179
|
+
n = len(src)
|
|
180
|
+
fl = np.full(n, F_SEED, np.int32)
|
|
181
|
+
if n:
|
|
182
|
+
pr = cKDTree(th / AS).query_pairs(RDUP, output_type="ndarray")
|
|
183
|
+
if len(pr):
|
|
184
|
+
pr = pr[night[pr[:, 0]] != night[pr[:, 1]]]
|
|
185
|
+
fl[np.unique(pr)] &= ~F_SEED
|
|
186
|
+
fl[np.asarray(d["ndet"])[src] >= 2] |= F_MERGED
|
|
187
|
+
cov = np.zeros(n, bool) # covered: another deep exposure of the night holds the row
|
|
188
|
+
cut = np.searchsorted(night, np.arange(len(un) + 1))
|
|
189
|
+
for e in np.flatnonzero(P["enight"] >= 0):
|
|
190
|
+
s = slice(cut[P["enight"][e]], cut[P["enight"][e] + 1])
|
|
191
|
+
cov[s] |= ((P["exp"][s] != e) & (np.abs(P["et"][e] - P["t"][s]) > PAR["dtint"]) & (P["edep"][e] >= P["V"][s] + 0.3)
|
|
192
|
+
& (np.hypot(P["ecx"][e] - P["x"][s], P["ecy"][e] - P["y"][s]) <= rmiss * AS))
|
|
193
|
+
fl[~cov] |= F_U
|
|
194
|
+
P["fl"] = fl
|
|
195
|
+
return P
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# ---------------------------------------------------------------- the linker
|
|
199
|
+
def link(P, native=None, **par):
|
|
200
|
+
"""Links of prepared rows P (``prep``) -> (links, stats). A link: dict(m (row indices of P, sorted), p (alpha, beta,
|
|
201
|
+
alpha-dot, beta-dot, gamma, gamma-dot at tref, in P's tangent frame), tref, nrms, rms ["], nights, tn, found, expn,
|
|
202
|
+
intra_n, intra_c, vmed). native: None = the core if installed, True = require it, False = the Python code."""
|
|
203
|
+
q, _ = _vector(par)
|
|
204
|
+
lib = _native.lib if native is not False else None
|
|
205
|
+
if native and not hasattr(lib, "dense_link"):
|
|
206
|
+
raise RuntimeError("orbitsift-native with dense_link is not installed (pip install ./native)")
|
|
207
|
+
if not len(P["x"]):
|
|
208
|
+
return [], dict.fromkeys(STATS, 0)
|
|
209
|
+
if hasattr(lib, "dense_link"):
|
|
210
|
+
rows = [np.ascontiguousarray(a, float) for a in (P["x"], P["y"], P["t"], P["E"][:, 0], P["E"][:, 1], P["E"][:, 2],
|
|
211
|
+
P["sig"], P["V"])]
|
|
212
|
+
irows = [np.ascontiguousarray(a, np.int32) for a in (P["night"], P["exp"], P["fl"])]
|
|
213
|
+
exps = [np.ascontiguousarray(a, float) for a in (P["ecx"], P["ecy"], P["et"], P["edep"], P["eE"][:, 0], P["eE"][:, 1],
|
|
214
|
+
P["eE"][:, 2])]
|
|
215
|
+
out, st = lib.dense_link(rows, irows, exps, np.ascontiguousarray(P["enight"], np.int32), len(P["nights"]), q)
|
|
216
|
+
else:
|
|
217
|
+
out, st = _link_py(P, q)
|
|
218
|
+
keys = ("m", "p", "tref", "nrms", "rms", "nights", "tn", "found", "expn", "intra_n", "intra_c", "vmed")
|
|
219
|
+
return [dict(zip(keys, (list(l[0]), list(l[1]), *l[2:]))) for l in out], dict(zip(STATS, (int(x) for x in st)))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def vet_ok(l):
|
|
223
|
+
"""The survey's completeness and same-night rules on a link's counters: True = passes. Missed: fewer than 70% (and
|
|
224
|
+
at least 2 fewer) of the nights where the fit predicts a deep exposure; unconfirmed: no row confirmed on its night
|
|
225
|
+
although 2 could have been (or 1, with rms >= 0.15")."""
|
|
226
|
+
miss = l["expn"] > 0 and l["found"] < 0.7 * l["expn"] and l["found"] + 1 < l["expn"]
|
|
227
|
+
return not (miss or (l["intra_c"] == 0 and (l["intra_n"] >= 2 or (l["intra_n"] == 1 and l["rms"] >= 0.15))))
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _rho(g):
|
|
231
|
+
return g * math.sqrt(2.0 * GM_SUN * g) # bound limit of the angular rate [rad / day]
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class _Grid:
|
|
235
|
+
"""The core's per-night grid (same cell size and indexing), so every candidate list and cap count is the core's."""
|
|
236
|
+
|
|
237
|
+
def __init__(self, x, y, lo, hi, bb):
|
|
238
|
+
n = float(max(hi - lo, 1))
|
|
239
|
+
self.cs = min(max(math.sqrt(2.0 * (bb[1] - bb[0]) * (bb[3] - bb[2]) / n), 3.0 * AS), 100.0 * AS)
|
|
240
|
+
self.x0, self.y0 = bb[0], bb[2]
|
|
241
|
+
self.nx, self.ny = int((bb[1] - bb[0]) / self.cs) + 1, int((bb[3] - bb[2]) / self.cs) + 1
|
|
242
|
+
cell = (np.minimum(((y[lo:hi] - bb[2]) / self.cs).astype(np.int64), self.ny - 1) * self.nx
|
|
243
|
+
+ np.minimum(((x[lo:hi] - bb[0]) / self.cs).astype(np.int64), self.nx - 1))
|
|
244
|
+
self.idx = lo + np.argsort(cell, kind="stable")
|
|
245
|
+
self.start = np.r_[0, np.cumsum(np.bincount(cell, minlength=self.nx * self.ny))]
|
|
246
|
+
|
|
247
|
+
def _span(self, b):
|
|
248
|
+
ia, ib = math.floor((b[0] - self.x0) / self.cs), math.floor((b[1] - self.x0) / self.cs)
|
|
249
|
+
ja, jb = math.floor((b[2] - self.y0) / self.cs), math.floor((b[3] - self.y0) / self.cs)
|
|
250
|
+
if ib < 0 or jb < 0 or ia >= self.nx or ja >= self.ny:
|
|
251
|
+
return None
|
|
252
|
+
return max(ia, 0), min(ib, self.nx - 1), max(ja, 0), min(jb, self.ny - 1)
|
|
253
|
+
|
|
254
|
+
def each(self, b):
|
|
255
|
+
"""Rows in the cells touching the box [x0, x1, y0, y1]."""
|
|
256
|
+
s = self._span(b)
|
|
257
|
+
if s is None:
|
|
258
|
+
return np.zeros(0, np.int64)
|
|
259
|
+
ia, ib, ja, jb = s
|
|
260
|
+
r = np.arange(ja, jb + 1) * self.nx
|
|
261
|
+
lo, hi = self.start[r + ia], self.start[r + ib + 1]
|
|
262
|
+
return np.concatenate([self.idx[a:b_] for a, b_ in zip(lo, hi)]) if len(r) > 1 else self.idx[lo[0]:hi[0]]
|
|
263
|
+
|
|
264
|
+
def count(self, b):
|
|
265
|
+
s = self._span(b)
|
|
266
|
+
if s is None:
|
|
267
|
+
return 0
|
|
268
|
+
ia, ib, ja, jb = s
|
|
269
|
+
r = np.arange(ja, jb + 1) * self.nx
|
|
270
|
+
return int((self.start[r + ib + 1] - self.start[r + ia]).sum())
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _csum(a, axis=0):
|
|
274
|
+
"""Sum in index order from 0.0 (as the core's loops add): bit-equal to its sums, unlike np.sum's pairwise one."""
|
|
275
|
+
a = np.asarray(a, float)
|
|
276
|
+
z = np.zeros((1,) + a.shape[1:]) if axis == 0 else None
|
|
277
|
+
return np.cumsum(np.concatenate([z, a]), axis=0)[-1]
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _solve(L, s, rhs):
|
|
281
|
+
"""The core's triangular solves of the scaled Cholesky factor L (scales s), Python floats."""
|
|
282
|
+
z = [0.0] * 6
|
|
283
|
+
for a in range(6):
|
|
284
|
+
v = rhs[a] * s[a]
|
|
285
|
+
for k in range(a):
|
|
286
|
+
v -= L[a][k] * z[k]
|
|
287
|
+
z[a] = v / L[a][a]
|
|
288
|
+
for a in range(5, -1, -1):
|
|
289
|
+
v = z[a]
|
|
290
|
+
for k in range(a + 1, 6):
|
|
291
|
+
v -= L[k][a] * z[k]
|
|
292
|
+
z[a] = v / L[a][a]
|
|
293
|
+
return [z[a] * s[a] for a in range(6)]
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _link_py(P, q):
|
|
297
|
+
"""The core's algorithm in Python (``native/src/dense.rs``, same operations in the same order where a
|
|
298
|
+
rounding could change a decision) -> (links as the core returns them, counters)."""
|
|
299
|
+
(gmin, gmax, dtmax, nmin, dmag, ktri, kext, nrms_max, rcap, kseed, maxb, maxc, dtext, rcov, vcov, dcov, bmargin, veto,
|
|
300
|
+
npass, nminu, sigcap, dtint, bcstrong, rmiss) = q
|
|
301
|
+
nmin, kseed, maxb, maxc, npass, nminu = (int(v) for v in (nmin, kseed, maxb, maxc, npass, nminu))
|
|
302
|
+
x, y, t, sig, V = (np.ascontiguousarray(P[k], float) for k in ("x", "y", "t", "sig", "V"))
|
|
303
|
+
ex, ey, ez = (np.ascontiguousarray(P["E"][:, k], float) for k in range(3))
|
|
304
|
+
night, exp, fl = (np.asarray(P[k], np.int64) for k in ("night", "exp", "fl"))
|
|
305
|
+
ecx, ecy, et, edep = (np.asarray(P[k], float) for k in ("ecx", "ecy", "et", "edep"))
|
|
306
|
+
eex, eey, eez = (np.asarray(P["eE"][:, k], float) for k in range(3))
|
|
307
|
+
enight = np.asarray(P["enight"], np.int64)
|
|
308
|
+
n, nn = len(x), len(P["nights"])
|
|
309
|
+
if np.any(np.diff(night) < 0):
|
|
310
|
+
raise ValueError("rows must be sorted by night")
|
|
311
|
+
wx, wy = ex - x * ez, ey - y * ez
|
|
312
|
+
ns = np.r_[0, np.cumsum(np.bincount(night, minlength=nn))]
|
|
313
|
+
if np.any(ns[1:] == ns[:-1]):
|
|
314
|
+
raise ValueError("empty night")
|
|
315
|
+
bb = [float(x.min()), float(x.max()), float(y.min()), float(y.max())]
|
|
316
|
+
ntm = np.array([_csum(t[ns[k]:ns[k + 1]]) / (ns[k + 1] - ns[k]) for k in range(nn)])
|
|
317
|
+
i0 = np.array([ns[k] + int(np.argmin(t[ns[k]:ns[k + 1]])) for k in range(nn)])
|
|
318
|
+
i1 = np.array([ns[k] + int(np.argmax(t[ns[k]:ns[k + 1]])) for k in range(nn)])
|
|
319
|
+
nexp = [np.flatnonzero(enight == k) for k in range(nn)]
|
|
320
|
+
grids = [_Grid(x, y, ns[k], ns[k + 1], bb) for k in range(nn)]
|
|
321
|
+
glo, ghi = 0.9 * gmin, 1.1 * gmax
|
|
322
|
+
gdm = bmargin * _rho(ghi)
|
|
323
|
+
st = [0] * 12
|
|
324
|
+
|
|
325
|
+
def pairwin(i, J):
|
|
326
|
+
"""pair (i, J) inside the bound-orbit rate window for some gamma (8 samples + the closest-approach gamma)."""
|
|
327
|
+
dt = np.abs(t[J] - t[i])
|
|
328
|
+
ax, ay = x[J] - x[i], y[J] - y[i]
|
|
329
|
+
bx, by = wx[J] - wx[i], wy[J] - wy[i]
|
|
330
|
+
tol = ktri * np.sqrt(sig[i] * sig[i] + sig[J] * sig[J])
|
|
331
|
+
b2 = bx * bx + by * by
|
|
332
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
333
|
+
gs = np.where(b2 > 0.0, np.clip(-(ax * bx + ay * by) / b2, glo, ghi), glo)
|
|
334
|
+
ok = np.zeros(len(J), bool)
|
|
335
|
+
for k in range(9):
|
|
336
|
+
g = glo + (ghi - glo) * k / 7.0 if k < 8 else gs
|
|
337
|
+
rx, ry = ax + g * bx, ay + g * by
|
|
338
|
+
rg = g * np.sqrt(2.0 * GM_SUN * g) if k == 8 else _rho(g)
|
|
339
|
+
ok |= np.sqrt(rx * rx + ry * ry) <= bmargin * rg * dt + tol
|
|
340
|
+
return ok
|
|
341
|
+
|
|
342
|
+
def three(i, m, j):
|
|
343
|
+
f = (t[m] - t[i]) / (t[j] - t[i])
|
|
344
|
+
r0x, r0y = x[m] - x[i] - f * (x[j] - x[i]), y[m] - y[i] - f * (y[j] - y[i])
|
|
345
|
+
r1x, r1y = wx[m] - wx[i] - f * (wx[j] - wx[i]), wy[m] - wy[i] - f * (wy[j] - wy[i])
|
|
346
|
+
r2 = r1x * r1x + r1y * r1y
|
|
347
|
+
g = min(max(-(r0x * r1x + r0y * r1y) / r2, glo), ghi) if r2 > 0.0 else glo
|
|
348
|
+
rx, ry = r0x + g * r1x, r0y + g * r1y
|
|
349
|
+
tol = ktri * math.sqrt(sig[m] * sig[m] + (1.0 - f) * (1.0 - f) * sig[i] * sig[i] + f * f * sig[j] * sig[j])
|
|
350
|
+
return rx * rx + ry * ry <= tol * tol
|
|
351
|
+
|
|
352
|
+
def triple(a, b, C):
|
|
353
|
+
"""third rows C of the seed (a, b) -> (C kept, gamma, gamma-dot): least |R0 + g R1 + gd R2| over the box."""
|
|
354
|
+
tb, tc = t[b] - t[a], t[C] - t[a]
|
|
355
|
+
f = tc / tb
|
|
356
|
+
r0 = (x[C] - x[a] - f * (x[b] - x[a]), y[C] - y[a] - f * (y[b] - y[a]))
|
|
357
|
+
r1 = (wx[C] - wx[a] - f * (wx[b] - wx[a]), wy[C] - wy[a] - f * (wy[b] - wy[a]))
|
|
358
|
+
r2 = (tc * (x[C] - x[b]), tc * (y[C] - y[b]))
|
|
359
|
+
tol = ktri * np.sqrt(sig[C] * sig[C] + (1.0 - f) * (1.0 - f) * sig[a] * sig[a] + f * f * sig[b] * sig[b])
|
|
360
|
+
n1, n2 = r1[0] * r1[0] + r1[1] * r1[1], r2[0] * r2[0] + r2[1] * r2[1]
|
|
361
|
+
det = r1[0] * r2[1] - r1[1] * r2[0]
|
|
362
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
363
|
+
okd = np.abs(det) > 1e-12 * np.sqrt(n1 * n2)
|
|
364
|
+
g, gd = (-r0[0] * r2[1] + r0[1] * r2[0]) / det, (-r1[0] * r0[1] + r1[1] * r0[0]) / det
|
|
365
|
+
inside = okd & (g >= glo) & (g <= ghi) & (np.abs(gd) <= gdm)
|
|
366
|
+
best = [np.full(len(C), np.inf), np.zeros(len(C)), np.zeros(len(C))]
|
|
367
|
+
for ge in (glo, ghi):
|
|
368
|
+
v = (r0[0] + ge * r1[0], r0[1] + ge * r1[1])
|
|
369
|
+
e = np.where(n2 > 0.0, np.clip(-(v[0] * r2[0] + v[1] * r2[1]) / n2, -gdm, gdm), 0.0)
|
|
370
|
+
qq = (v[0] + e * r2[0]) * (v[0] + e * r2[0]) + (v[1] + e * r2[1]) * (v[1] + e * r2[1])
|
|
371
|
+
s = qq < best[0]
|
|
372
|
+
best[0], best[1], best[2] = np.where(s, qq, best[0]), np.where(s, ge, best[1]), np.where(s, e, best[2])
|
|
373
|
+
for de in (-gdm, gdm):
|
|
374
|
+
v = (r0[0] + de * r2[0], r0[1] + de * r2[1])
|
|
375
|
+
e = np.where(n1 > 0.0, np.clip(-(v[0] * r1[0] + v[1] * r1[1]) / n1, glo, ghi), glo)
|
|
376
|
+
qq = (v[0] + e * r1[0]) * (v[0] + e * r1[0]) + (v[1] + e * r1[1]) * (v[1] + e * r1[1])
|
|
377
|
+
s = qq < best[0]
|
|
378
|
+
best[0], best[1], best[2] = np.where(s, qq, best[0]), np.where(s, e, best[1]), np.where(s, de, best[2])
|
|
379
|
+
keep = inside | (best[0] <= tol * tol)
|
|
380
|
+
return C[keep], np.where(inside, g, best[1])[keep], np.where(inside, gd, best[2])[keep]
|
|
381
|
+
|
|
382
|
+
def predc(a, b, g, gd, tc, ec):
|
|
383
|
+
tb = t[b] - t[a]
|
|
384
|
+
f = tc / tb
|
|
385
|
+
ua = (x[a] + g * wx[a], y[a] + g * wy[a])
|
|
386
|
+
ub = (x[b] + g * wx[b] + gd * tb * x[b], y[b] + g * wy[b] + gd * tb * y[b])
|
|
387
|
+
den = 1.0 + gd * tc - g * ec[2]
|
|
388
|
+
return (ua[0] + f * (ub[0] - ua[0]) - g * ec[0]) / den, (ua[1] + f * (ub[1] - ua[1]) - g * ec[1]) / den
|
|
389
|
+
|
|
390
|
+
def jac(p, tau, e0, e1, e2, need=True):
|
|
391
|
+
"""model (x, y) and its Jacobian rows (k, 6) at time offsets tau (k,), observer (e0, e1, e2)."""
|
|
392
|
+
g = p[4]
|
|
393
|
+
t2 = tau * tau
|
|
394
|
+
c = 0.5 * GM_SUN * g * g * g * t2
|
|
395
|
+
cg = 1.5 * GM_SUN * g * g * t2
|
|
396
|
+
den = 1.0 + p[5] * tau - c - g * e2
|
|
397
|
+
X = (p[0] * (1.0 - c) + p[2] * tau - g * e0) / den
|
|
398
|
+
Y = (p[1] * (1.0 - c) + p[3] * tau - g * e1) / den
|
|
399
|
+
if not need:
|
|
400
|
+
return None, None, X, Y
|
|
401
|
+
jx, jy = np.zeros(tau.shape + (6,)), np.zeros(tau.shape + (6,))
|
|
402
|
+
jx[..., 0] = jy[..., 1] = (1.0 - c) / den
|
|
403
|
+
jx[..., 2] = jy[..., 3] = tau / den
|
|
404
|
+
jx[..., 4], jx[..., 5] = (-p[0] * cg - e0 + X * (cg + e2)) / den, -X * tau / den
|
|
405
|
+
jy[..., 4], jy[..., 5] = (-p[1] * cg - e1 + Y * (cg + e2)) / den, -Y * tau / den
|
|
406
|
+
return jx, jy, X, Y
|
|
407
|
+
|
|
408
|
+
def jac1(p, tau, i):
|
|
409
|
+
"""``jac`` for one row (or exposure) with Python floats: the same operations."""
|
|
410
|
+
e0, e1, e2 = float(ex[i]), float(ey[i]), float(ez[i])
|
|
411
|
+
g = p[4]
|
|
412
|
+
t2 = tau * tau
|
|
413
|
+
c = 0.5 * GM_SUN * g * g * g * t2
|
|
414
|
+
cg = 1.5 * GM_SUN * g * g * t2
|
|
415
|
+
den = 1.0 + p[5] * tau - c - g * e2
|
|
416
|
+
X = (p[0] * (1.0 - c) + p[2] * tau - g * e0) / den
|
|
417
|
+
Y = (p[1] * (1.0 - c) + p[3] * tau - g * e1) / den
|
|
418
|
+
return ((1.0 - c) / den, 0.0, tau / den, 0.0, (-p[0] * cg - e0 + X * (cg + e2)) / den, -X * tau / den), \
|
|
419
|
+
(0.0, (1.0 - c) / den, 0.0, tau / den, (-p[1] * cg - e1 + Y * (cg + e2)) / den, -Y * tau / den), X, Y
|
|
420
|
+
|
|
421
|
+
def fit(m, tref, p, pri, iters):
|
|
422
|
+
"""Gauss-Newton -> (p, chi2, factor) or None; ``covariance(factor)`` gives the covariance (only when used)."""
|
|
423
|
+
m = np.asarray(m)
|
|
424
|
+
p = [float(v) for v in p]
|
|
425
|
+
tau, e0, e1, e2, xm, ym = t[m] - tref, ex[m], ey[m], ez[m], x[m], y[m]
|
|
426
|
+
w = 1.0 / (sig[m] * sig[m])
|
|
427
|
+
k = len(m)
|
|
428
|
+
A = np.zeros((k + 1, 43)) # row 0 stays 0.0: the core's sums start there
|
|
429
|
+
for it in range(iters + 1):
|
|
430
|
+
jx, jy, X, Y = jac(p, tau, e0, e1, e2)
|
|
431
|
+
rx, ry = xm - X, ym - Y
|
|
432
|
+
A[1:, 0] = w * (rx * rx + ry * ry)
|
|
433
|
+
A[1:, 1:7] = w[:, None] * (jx * rx[:, None] + jy * ry[:, None])
|
|
434
|
+
A[1:, 7:] = (w[:, None, None] * (jx[:, :, None] * jx[:, None, :] + jy[:, :, None] * jy[:, None, :])).reshape(k, 36)
|
|
435
|
+
S = A.cumsum(0)[-1].tolist() # sequential sums, as the core's loops
|
|
436
|
+
chi, gv = S[0], S[1:7]
|
|
437
|
+
nm = [S[7 + 6 * a:13 + 6 * a] for a in range(6)]
|
|
438
|
+
nm[4][4] += 1.0 / (pri[1] * pri[1])
|
|
439
|
+
gv[4] += (pri[0] - p[4]) / (pri[1] * pri[1])
|
|
440
|
+
nm[5][5] += 1.0 / (pri[2] * pri[2])
|
|
441
|
+
gv[5] -= p[5] / (pri[2] * pri[2])
|
|
442
|
+
s = [0.0] * 6
|
|
443
|
+
for a in range(6):
|
|
444
|
+
if nm[a][a] <= 0.0: # (a NaN goes on, as in the core)
|
|
445
|
+
return None
|
|
446
|
+
s[a] = 1.0 / math.sqrt(nm[a][a])
|
|
447
|
+
L = [[0.0] * 6 for _ in range(6)]
|
|
448
|
+
for a in range(6):
|
|
449
|
+
for b in range(a + 1):
|
|
450
|
+
v = nm[b][a] * s[a] * s[b]
|
|
451
|
+
for q_ in range(b):
|
|
452
|
+
v -= L[a][q_] * L[b][q_]
|
|
453
|
+
if a == b:
|
|
454
|
+
if v <= 1e-13:
|
|
455
|
+
return None
|
|
456
|
+
L[a][a] = math.sqrt(v)
|
|
457
|
+
else:
|
|
458
|
+
L[a][b] = v / L[b][b]
|
|
459
|
+
if it == iters:
|
|
460
|
+
return p, chi, (L, s)
|
|
461
|
+
dp = _solve(L, s, gv)
|
|
462
|
+
p = [p[a] + dp[a] for a in range(6)]
|
|
463
|
+
return None
|
|
464
|
+
|
|
465
|
+
def covariance(F):
|
|
466
|
+
cov = [[0.0] * 6 for _ in range(6)]
|
|
467
|
+
for a in range(6):
|
|
468
|
+
z = _solve(*F, [1.0 if b == a else 0.0 for b in range(6)])
|
|
469
|
+
for b in range(6):
|
|
470
|
+
cov[b][a] = z[b]
|
|
471
|
+
return cov
|
|
472
|
+
|
|
473
|
+
def pcov1(jx, jy, cov):
|
|
474
|
+
"""J cov J^T of one point and its largest eigenvalue, summed in the core's order."""
|
|
475
|
+
c11 = c12 = c22 = 0.0
|
|
476
|
+
for a in range(6):
|
|
477
|
+
ca, xa_, ya_ = cov[a], jx[a], jy[a]
|
|
478
|
+
for b in range(6):
|
|
479
|
+
c11 += xa_ * ca[b] * jx[b]
|
|
480
|
+
c12 += xa_ * ca[b] * jy[b]
|
|
481
|
+
c22 += ya_ * ca[b] * jy[b]
|
|
482
|
+
h = 0.5 * (c11 - c22)
|
|
483
|
+
return c11, c12, c22, 0.5 * (c11 + c22) + math.sqrt(h * h + c12 * c12)
|
|
484
|
+
|
|
485
|
+
def pcov(jx, jy, cov):
|
|
486
|
+
"""``pcov1`` for rows of jx, jy."""
|
|
487
|
+
c11 = c12 = c22 = 0.0
|
|
488
|
+
for a in range(6):
|
|
489
|
+
for b in range(6):
|
|
490
|
+
c11 = c11 + jx[..., a] * cov[a][b] * jx[..., b]
|
|
491
|
+
c12 = c12 + jx[..., a] * cov[a][b] * jy[..., b]
|
|
492
|
+
c22 = c22 + jy[..., a] * cov[a][b] * jy[..., b]
|
|
493
|
+
h = 0.5 * (c11 - c22)
|
|
494
|
+
return c11, c12, c22, 0.5 * (c11 + c22) + np.sqrt(h * h + c12 * c12)
|
|
495
|
+
|
|
496
|
+
def vmed(m):
|
|
497
|
+
return float(np.median(V[m]))
|
|
498
|
+
|
|
499
|
+
def bound(p, k):
|
|
500
|
+
if not glo <= p[4] <= ghi:
|
|
501
|
+
return False
|
|
502
|
+
lim = k * bmargin * _rho(p[4])
|
|
503
|
+
return p[2] * p[2] + p[3] * p[3] + p[5] * p[5] <= lim * lim
|
|
504
|
+
|
|
505
|
+
gm = 0.5 * (gmin + gmax)
|
|
506
|
+
pri = (gm, 0.5 * (gmax - gmin), 0.5 * _rho(gm))
|
|
507
|
+
|
|
508
|
+
def grow(a, b, c, g, gd):
|
|
509
|
+
tref = t[a]
|
|
510
|
+
|
|
511
|
+
def xy(p, ii):
|
|
512
|
+
return jac(p, t[ii] - tref, ex[ii], ey[ii], ez[ii], need=False)[2:]
|
|
513
|
+
tb = t[b] - tref
|
|
514
|
+
ua = (x[a] + g * wx[a], y[a] + g * wy[a])
|
|
515
|
+
ub = (x[b] + g * wx[b] + gd * tb * x[b], y[b] + g * wy[b] + gd * tb * y[b])
|
|
516
|
+
p = [ua[0], ua[1], (ub[0] - ua[0]) / tb, (ub[1] - ua[1]) / tb, g, gd]
|
|
517
|
+
m = [a, b, c]
|
|
518
|
+
st[4] += 1
|
|
519
|
+
r = fit(m, tref, p, pri, 6)
|
|
520
|
+
if r is None:
|
|
521
|
+
return None
|
|
522
|
+
p, chi, F = r
|
|
523
|
+
if math.sqrt(chi / 6.0) > nrms_max or not bound(p, 1.25):
|
|
524
|
+
return None
|
|
525
|
+
cov = covariance(F)
|
|
526
|
+
es = {int(exp[a]), int(exp[b]), int(exp[c])}
|
|
527
|
+
st[5] += 1
|
|
528
|
+
for _ in range(npass):
|
|
529
|
+
tm = t[m]
|
|
530
|
+
t0_, t1_ = tm.min(), tm.max()
|
|
531
|
+
nts = [k for k in range(nn) if t0_ - dtext <= ntm[k] <= t1_ + dtext]
|
|
532
|
+
nts.sort(key=lambda k: (abs(ntm[k] - tref), k))
|
|
533
|
+
added = False
|
|
534
|
+
for k in nts:
|
|
535
|
+
r0, r1 = i0[k], i1[k]
|
|
536
|
+
jx, jy, xa, ya = jac1(p, float(t[r0] - tref), r0)
|
|
537
|
+
c11, c12, c22, lmax = pcov1(jx, jy, cov)
|
|
538
|
+
if kext * math.sqrt(lmax) > rcap:
|
|
539
|
+
continue
|
|
540
|
+
rad = min(rcap, kext * math.sqrt(lmax + sigcap * sigcap)) + AS
|
|
541
|
+
_, _, xb, yb = jac1(p, float(t[r1] - tref), r1)
|
|
542
|
+
vm = vmed(m)
|
|
543
|
+
R = grids[k].each([min(xa, xb) - rad, max(xa, xb) + rad, min(ya, yb) - rad, max(ya, yb) + rad])
|
|
544
|
+
R = R[np.abs(V[R] - vm) <= dmag]
|
|
545
|
+
R = R[[int(e_) not in es for e_ in exp[R]]] # (a member's exposure: the member too)
|
|
546
|
+
if not len(R):
|
|
547
|
+
continue
|
|
548
|
+
X, Y = xy(p, R)
|
|
549
|
+
rx, ry = x[R] - X, y[R] - Y
|
|
550
|
+
s2 = sig[R] * sig[R]
|
|
551
|
+
a11, a22 = c11 + s2, c22 + s2
|
|
552
|
+
qq = (a22 * rx * rx - 2.0 * c12 * rx * ry + a11 * ry * ry) / (a11 * a22 - c12 * c12)
|
|
553
|
+
okc = (qq <= kext * kext) & (rx * rx + ry * ry <= rcap * rcap)
|
|
554
|
+
R, qq = R[okc], qq[okc]
|
|
555
|
+
fails = 0
|
|
556
|
+
for i in R[np.lexsort((R, qq))].tolist():
|
|
557
|
+
if int(exp[i]) in es:
|
|
558
|
+
continue
|
|
559
|
+
st[6] += 1
|
|
560
|
+
r = fit(m + [i], tref, p, pri, 3)
|
|
561
|
+
if r is not None and math.sqrt(r[1] / (2 * (len(m) + 1))) <= nrms_max and glo <= r[0][4] <= ghi:
|
|
562
|
+
p, cov = r[0], covariance(r[2])
|
|
563
|
+
m = m + [i]
|
|
564
|
+
es.add(int(exp[i]))
|
|
565
|
+
added = True
|
|
566
|
+
else:
|
|
567
|
+
fails += 1
|
|
568
|
+
if fails >= 4:
|
|
569
|
+
break
|
|
570
|
+
if not added:
|
|
571
|
+
break
|
|
572
|
+
if len(m) < nmin:
|
|
573
|
+
return None
|
|
574
|
+
r = fit(m, tref, p, pri, 6)
|
|
575
|
+
if r is None:
|
|
576
|
+
return None
|
|
577
|
+
p, chi, F = r
|
|
578
|
+
cov = covariance(F)
|
|
579
|
+
nrms = math.sqrt(chi / (2 * len(m)))
|
|
580
|
+
if nrms > nrms_max or not bound(p, 1.0):
|
|
581
|
+
return None
|
|
582
|
+
m = sorted(m)
|
|
583
|
+
ma = np.array(m)
|
|
584
|
+
vm = vmed(ma)
|
|
585
|
+
X, Y = xy(p, ma)
|
|
586
|
+
r2 = float(_csum((x[ma] - X) * (x[ma] - X) + (y[ma] - Y) * (y[ma] - Y)))
|
|
587
|
+
nights = tn = intra_n = intra_c = 0
|
|
588
|
+
for k in np.unique(night[ma]):
|
|
589
|
+
mk = ma[night[ma] == k]
|
|
590
|
+
nights += 1
|
|
591
|
+
multi = len(mk) >= 2
|
|
592
|
+
tn += bool(multi or (fl[mk] & F_MERGED).any())
|
|
593
|
+
e = nexp[k]
|
|
594
|
+
for i in mk:
|
|
595
|
+
if fl[i] & F_MERGED:
|
|
596
|
+
intra_n += 1
|
|
597
|
+
intra_c += 1
|
|
598
|
+
continue
|
|
599
|
+
if ((e != exp[i]) & (np.abs(et[e] - t[i]) > dtint) & (edep[e] > vm + 0.3)
|
|
600
|
+
& (np.hypot(ecx[e] - x[i], ecy[e] - y[i]) <= rmiss)).any():
|
|
601
|
+
intra_n += 1
|
|
602
|
+
intra_c += multi
|
|
603
|
+
rms = math.sqrt(r2 / (2 * len(m))) / AS
|
|
604
|
+
if nights < nmin or (tn == 0 and nights < nminu):
|
|
605
|
+
return None
|
|
606
|
+
t0_, t1_ = t[ma].min(), t[ma].max()
|
|
607
|
+
E_ = np.flatnonzero((et >= t0_ - 5.0) & (et <= t1_ + 5.0) & (edep > vm + 0.3))
|
|
608
|
+
expd = []
|
|
609
|
+
if len(E_):
|
|
610
|
+
jx, jy, X, Y = jac(p, et[E_] - tref, eex[E_], eey[E_], eez[E_])
|
|
611
|
+
lm = pcov(jx, jy, cov)[3]
|
|
612
|
+
for z in np.flatnonzero(~((np.hypot(X - ecx[E_], Y - ecy[E_]) > rmiss) | (np.sqrt(lm) > 5.0 * AS))):
|
|
613
|
+
if enight[E_[z]] not in expd:
|
|
614
|
+
expd.append(int(enight[E_[z]]))
|
|
615
|
+
un = set(night[ma].tolist())
|
|
616
|
+
found, expn = sum(1 for k in expd if k in un), len(expd)
|
|
617
|
+
if veto and ((expn > 0 and found < 0.7 * expn and found + 1 < expn)
|
|
618
|
+
or (intra_c == 0 and (intra_n >= 2 or (intra_n == 1 and rms >= 0.15)))):
|
|
619
|
+
st[8] += 1
|
|
620
|
+
return None
|
|
621
|
+
return (m, p, tref, nrms, rms, nights, tn, found, expn, intra_n, intra_c, vm)
|
|
622
|
+
|
|
623
|
+
# same-night partners
|
|
624
|
+
vmax = 1.02 * (ghi * VE + bmargin * _rho(ghi))
|
|
625
|
+
seed = (fl & F_SEED) != 0
|
|
626
|
+
part = [np.zeros(0, np.int64)] * n
|
|
627
|
+
for i in np.flatnonzero(seed):
|
|
628
|
+
k = night[i]
|
|
629
|
+
r = vmax * max(t[i1[k]] - t[i], t[i] - t[i0[k]]) + ktri * math.sqrt(2.0) * sigcap + AS
|
|
630
|
+
J = grids[k].each([x[i] - r, x[i] + r, y[i] - r, y[i] + r])
|
|
631
|
+
J = J[(J != i) & (exp[J] != exp[i]) & seed[J] & (np.abs(t[J] - t[i]) >= dtint) & (np.abs(V[J] - V[i]) <= dmag)]
|
|
632
|
+
if len(J):
|
|
633
|
+
part[i] = np.sort(J[pairwin(i, J)])
|
|
634
|
+
strong_d = ((fl & (F_MERGED | F_U)) != 0) | np.array([len(p_) > 0 for p_ in part], bool)
|
|
635
|
+
tolm = ktri * math.sqrt(3.0) * sigcap + 2.0 * AS
|
|
636
|
+
links = []
|
|
637
|
+
for a in range(n):
|
|
638
|
+
is_t = bool(fl[a] & F_MERGED) or len(part[a]) > 0
|
|
639
|
+
if not seed[a] or not (is_t or fl[a] & F_U):
|
|
640
|
+
continue
|
|
641
|
+
st[0] += 1
|
|
642
|
+
strong = (not is_t) or bool(bcstrong)
|
|
643
|
+
na = night[a]
|
|
644
|
+
nl, lo, hi = [], na - 1, na + 1
|
|
645
|
+
while len(nl) < kseed:
|
|
646
|
+
dl = abs(ntm[lo] - t[a]) if lo >= 0 else math.inf
|
|
647
|
+
dh = abs(ntm[hi] - t[a]) if hi < nn else math.inf
|
|
648
|
+
if min(dl, dh) > dtmax:
|
|
649
|
+
break
|
|
650
|
+
if dl <= dh:
|
|
651
|
+
k, lo = lo, lo - 1
|
|
652
|
+
else:
|
|
653
|
+
k, hi = hi, hi + 1
|
|
654
|
+
e = nexp[k]
|
|
655
|
+
if ((edep[e] >= V[a] - dcov) & (np.hypot(ecx[e] - x[a], ecy[e] - y[a]) <= rcov + vcov * np.abs(et[e] - t[a]))).any():
|
|
656
|
+
nl.append(k)
|
|
657
|
+
okv = seed & (np.abs(V - V[a]) <= dmag) & (strong_d | (not strong))
|
|
658
|
+
for bi, nb in enumerate(nl):
|
|
659
|
+
bb_ = [math.inf, -math.inf, math.inf, -math.inf]
|
|
660
|
+
for r in (i0[nb], i1[nb]):
|
|
661
|
+
dt, e = abs(t[r] - t[a]), (ex[r], ey[r], ez[r])
|
|
662
|
+
rad = 1.05 * bmargin * _rho(ghi) * dt / (1.0 - ghi * abs(e[2])) + tolm + 3.0 * AS
|
|
663
|
+
for g in (glo, 0.5 * (glo + ghi), ghi):
|
|
664
|
+
den = 1.0 - g * e[2]
|
|
665
|
+
cx = (x[a] * (1.0 - g * ez[a]) + g * (ex[a] - e[0])) / den
|
|
666
|
+
cy = (y[a] * (1.0 - g * ez[a]) + g * (ey[a] - e[1])) / den
|
|
667
|
+
bb_ = [min(bb_[0], cx - rad), max(bb_[1], cx + rad), min(bb_[2], cy - rad), max(bb_[3], cy + rad)]
|
|
668
|
+
if grids[nb].count(bb_) > maxb:
|
|
669
|
+
st[9] += 1
|
|
670
|
+
continue
|
|
671
|
+
B = grids[nb].each(bb_)
|
|
672
|
+
st[1] += len(B)
|
|
673
|
+
B = B[okv[B]]
|
|
674
|
+
B = B[pairwin(a, B)] if len(B) else B
|
|
675
|
+
if not (fl[a] & F_MERGED) and len(part[a]):
|
|
676
|
+
B = np.array([b for b in B if any(three(a, int(q_), int(b)) for q_ in part[a])], np.int64)
|
|
677
|
+
st[2] += len(B)
|
|
678
|
+
for nc in nl[bi + 1:]:
|
|
679
|
+
if abs(ntm[nc] - ntm[nb]) > dtmax:
|
|
680
|
+
continue
|
|
681
|
+
gr, r0, r1 = grids[nc], i0[nc], i1[nc]
|
|
682
|
+
ends = [(t[r0] - t[a], (ex[r0], ey[r0], ez[r0])), (t[r1] - t[a], (ex[r1], ey[r1], ez[r1]))]
|
|
683
|
+
for b in B:
|
|
684
|
+
pa, pb = predc(a, b, glo, 0.0, *ends[0]), predc(a, b, ghi, 0.0, *ends[0])
|
|
685
|
+
h = float(np.hypot(pa[0] - pb[0], pa[1] - pb[1]))
|
|
686
|
+
v = h / (4.0 * gr.cs)
|
|
687
|
+
ns_ = 1 if v != v else 64 if v > 64 else max(1, math.ceil(v))
|
|
688
|
+
cs, cnt = [], 0
|
|
689
|
+
for s in range(ns_):
|
|
690
|
+
box = [math.inf, -math.inf, math.inf, -math.inf]
|
|
691
|
+
for gg in (glo + (ghi - glo) * s / ns_, glo + (ghi - glo) * (s + 1) / ns_):
|
|
692
|
+
for gd in (-gdm, gdm):
|
|
693
|
+
for tc, ec in ends:
|
|
694
|
+
qx, qy = predc(a, b, gg, gd, tc, ec)
|
|
695
|
+
box = [min(box[0], qx - tolm), max(box[1], qx + tolm), min(box[2], qy - tolm), max(box[3], qy + tolm)]
|
|
696
|
+
cnt += gr.count(box)
|
|
697
|
+
if cnt > maxc:
|
|
698
|
+
break
|
|
699
|
+
cs.append(gr.each(box))
|
|
700
|
+
if cnt > maxc:
|
|
701
|
+
st[10] += 1
|
|
702
|
+
continue
|
|
703
|
+
C = np.unique(np.concatenate(cs)) if cs else np.zeros(0, np.int64)
|
|
704
|
+
st[3] += len(C)
|
|
705
|
+
C = C[okv[C]]
|
|
706
|
+
if not len(C):
|
|
707
|
+
continue
|
|
708
|
+
for c, g, gd in zip(*triple(a, b, C)):
|
|
709
|
+
lk = grow(a, int(b), int(c), float(g), float(gd))
|
|
710
|
+
if lk is not None:
|
|
711
|
+
st[7] += 1
|
|
712
|
+
links.append(lk)
|
|
713
|
+
uniq = {}
|
|
714
|
+
for lk in sorted(links, key=lambda lk: (lk[0], lk[2])):
|
|
715
|
+
uniq.setdefault(tuple(lk[0]), lk)
|
|
716
|
+
st[11] = len(uniq)
|
|
717
|
+
keep, owner = [], {}
|
|
718
|
+
for lk in sorted(uniq.values(), key=lambda lk: (-lk[5], -len(lk[0]), lk[3], lk[0])):
|
|
719
|
+
cnt = {}
|
|
720
|
+
for i in lk[0]:
|
|
721
|
+
for k in owner.get(i, ()):
|
|
722
|
+
cnt[k] = cnt.get(k, 0) + 1
|
|
723
|
+
if any(v >= 2 for v in cnt.values()):
|
|
724
|
+
continue
|
|
725
|
+
for i in lk[0]:
|
|
726
|
+
owner.setdefault(i, []).append(len(keep))
|
|
727
|
+
keep.append(lk)
|
|
728
|
+
return keep, st
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
# ---------------------------------------------------------------- a catalogue tile
|
|
732
|
+
def link_tile(d, ex, ra0, dec0, site="W84", dist_min=25.0, dist_max=80.0, expmax=EXPMAX, clump_factor=CLUMP,
|
|
733
|
+
max_rows=None, native=None, **par):
|
|
734
|
+
"""The dense linker on catalogue rows d (``catalog.detections``: ra, dec, mjd, V, night, ndet, fwhm, flags, bmag, id)
|
|
735
|
+
and the DECam exposures ex (``catalog.exposures``) -> (links in ``link.link_detections`` format plus the evidence
|
|
736
|
+
counters, info). As in the survey's production: rows with flags > 1 or a band magnitude brighter than 20 are dropped,
|
|
737
|
+
rows are given an exposure (``exposure_of``; rows of no DECam exposure are dropped), then ``expcap`` and ``clump``.
|
|
738
|
+
Rows that name their exposure (d["exp"], names of ex["name"]: tables with several detectors exposed at one time, as
|
|
739
|
+
``rubin`` makes) keep it; give such a table its footprint radius as rmiss and rcov [arcsec].
|
|
740
|
+
info: rows at each step, exposures dropped, masked area, ``too_dense`` (more than max_rows left: nothing linked),
|
|
741
|
+
the core's counters."""
|
|
742
|
+
max_rows = MAX_ROWS if max_rows is None else max_rows
|
|
743
|
+
n0 = len(d["ra"])
|
|
744
|
+
start = np.asarray(ex["mjd"], float)
|
|
745
|
+
if "exp" in d:
|
|
746
|
+
pos = {str(n): i for i, n in enumerate(ex["name"])}
|
|
747
|
+
expi = np.array([pos.get(str(n), -1) for n in d["exp"]], int)
|
|
748
|
+
else:
|
|
749
|
+
expi = exposure_of(d["mjd"], d["ndet"], start, ex["exptime"]) if n0 else np.zeros(0, int)
|
|
750
|
+
used = np.zeros(len(start), bool)
|
|
751
|
+
used[expi[expi >= 0]] = True # exposures of any row: their coverage counts
|
|
752
|
+
cut = (np.nan_to_num(np.asarray(d["flags"], float)) <= 1) & ~(np.asarray(d["bmag"], float) < 20)
|
|
753
|
+
sel = np.flatnonzero((expi >= 0) & cut)
|
|
754
|
+
nexp = len(start)
|
|
755
|
+
big = expcap(expi[sel], nexp, expmax)
|
|
756
|
+
sel = sel[~big[expi[sel]]]
|
|
757
|
+
bad, marea = clump(expi[sel], d["ra"][sel], d["dec"][sel], nexp, clump_factor)
|
|
758
|
+
sel = sel[~bad]
|
|
759
|
+
info = dict(rows=n0, rows_cut=int((~cut).sum()), rows_with_exposure=int((expi >= 0).sum()), exposures=int(used.sum()), exposures_dropped=int(big.sum()),
|
|
760
|
+
rows_after_cap=int(len(sel) + bad.sum()), rows_masked=int(bad.sum()), masked_area_frac=round(marea, 5),
|
|
761
|
+
rows_linked=int(len(sel)), too_dense=len(sel) > max_rows)
|
|
762
|
+
if info["too_dense"] or not len(sel):
|
|
763
|
+
return [], info
|
|
764
|
+
depth = catalog.vlimit(ex)
|
|
765
|
+
dep = np.where(np.isfinite(depth), depth, np.nanmedian(depth) if np.isfinite(depth).any() else 23.0)
|
|
766
|
+
dep[big] = -99.0 # dropped exposures cover nothing
|
|
767
|
+
e = np.flatnonzero(used) # the exposures of the tile's rows
|
|
768
|
+
lut = np.full(nexp, -1)
|
|
769
|
+
lut[e] = np.arange(len(e))
|
|
770
|
+
d95 = np.where(np.isfinite(ex["depth"]), ex["depth"], 23.0)[expi[sel]]
|
|
771
|
+
bm = np.where(np.isfinite(d["bmag"][sel]), d["bmag"][sel], d95)
|
|
772
|
+
magerr = np.minimum(0.217 * 10 ** (0.4 * (bm - d95)), 0.5)
|
|
773
|
+
rows = dict(ra=d["ra"][sel], dec=d["dec"][sel], mjd=d["mjd"][sel], V=d["V"][sel], night=d["night"][sel],
|
|
774
|
+
ndet=d["ndet"][sel], sig=sigma(d["fwhm"][sel], magerr), expi=lut[expi[sel]])
|
|
775
|
+
exs = dict(mid=start[e] + np.asarray(ex["exptime"], float)[e] / 2 / 86400, ra=np.asarray(ex["ra"])[e],
|
|
776
|
+
dec=np.asarray(ex["dec"])[e], depth=dep[e])
|
|
777
|
+
P = prep(rows, exs, ra0, dec0, site, par.get("rmiss", PAR["rmiss"]))
|
|
778
|
+
raw, stats = link(P, native=native, **dict(par, gmin=1 / dist_max, gmax=1 / dist_min))
|
|
779
|
+
info["stats"] = stats
|
|
780
|
+
out = []
|
|
781
|
+
for lk in raw:
|
|
782
|
+
s = sel[P["src"][lk["m"]]]
|
|
783
|
+
out.append(dict(n=len(s), nights=int(lk["nights"]), dist_au=float(1 / lk["p"][4]), rms=float(lk["rms"]),
|
|
784
|
+
nrms=float(lk["nrms"]), ra=centre_ra(d["ra"][s]), dec=float(np.mean(d["dec"][s])), V=float(lk["vmed"]),
|
|
785
|
+
ids=[str(v) for v in d["id"][s]], tn=int(lk["tn"]), found=int(lk["found"]), expn=int(lk["expn"]),
|
|
786
|
+
intra_n=int(lk["intra_n"]), intra_c=int(lk["intra_c"]), vet_ok=vet_ok(lk),
|
|
787
|
+
det=[[float(d["ra"][k]), float(d["dec"][k]), float(d["mjd"][k]), float(d["V"][k])] for k in s]))
|
|
788
|
+
return out, info
|