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/cli.py ADDED
@@ -0,0 +1,2200 @@
1
+ """Command-line interface: ``orbitsift <command> --help`` for each command.
2
+
3
+ Every command also takes ``--json`` (one JSON document on stdout, the human text goes to stderr),
4
+ ``--dry-run`` (report what would be fetched or computed, do nothing) and ``--force`` (recompute an output
5
+ that is up to date). Exit codes are in ``EXIT``; the JSON schemas in docs/cli.md.
6
+ """
7
+ import argparse
8
+ import contextlib
9
+ import hashlib
10
+ import http.client
11
+ import json
12
+ import math
13
+ import os
14
+ import sys
15
+ import time
16
+ import traceback
17
+ import urllib.error
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+
22
+ from . import __version__, ades, catalog, config, net, plugins, tiles
23
+
24
+ SCHEMA = "orbitsift/1"
25
+ EXIT = {"ok": 0, "no_result": 1, "bad_input": 2, "network": 3, "internal": 4, "interrupted": 130}
26
+ VETOES = ("miss", "crtrail", "intra", "kep", "near", "static", "nights", "kepler") # vet's veto_<name> flags
27
+ KNOWN_MATCH_ARCSEC = 120.0 # verdict known:<name> when a known object is predicted this close
28
+ CONFIRM = {"nights": 2, "rms_arcsec": 0.12, "dmag": 0.5} # >= 2 new nights, fit rms, |median mag offset|
29
+ NET_ERRORS = (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException, net.ServiceError)
30
+
31
+
32
+ class BadInput(Exception):
33
+ """Wrong arguments or input files (exit 2)."""
34
+
35
+
36
+ class NoResult(Exception):
37
+ """The command ran but found nothing (exit 1); ``verdict`` says what."""
38
+
39
+ def __init__(self, verdict, message):
40
+ super().__init__(message)
41
+ self.verdict = verdict
42
+
43
+
44
+ def _dump(obj, path, a=None):
45
+ if a is not None and getattr(a, "key", None):
46
+ obj["inputs"] = dict(key=a.key, orbitsift=__version__)
47
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
48
+ with open(path, "w") as f:
49
+ json.dump(obj, f, indent=1, default=lambda x: x.tolist() if hasattr(x, "tolist") else str(x))
50
+ print(f"wrote {path}")
51
+
52
+
53
+ def _clean(x):
54
+ """JSON-safe copy: numpy to Python, non-finite floats to None."""
55
+ if isinstance(x, dict):
56
+ return {str(k): _clean(v) for k, v in x.items()}
57
+ if isinstance(x, (list, tuple)):
58
+ return [_clean(v) for v in x]
59
+ if hasattr(x, "tolist"):
60
+ return _clean(x.tolist())
61
+ if isinstance(x, float) and not math.isfinite(x):
62
+ return None
63
+ if isinstance(x, (str, int, float, bool)) or x is None:
64
+ return x
65
+ return str(x)
66
+
67
+
68
+ # presets of link --mode: mid 15-30 AU (Uranus Trojans, Centaurs); far 80-1500 AU (extreme TNOs, distant planets):
69
+ # seeds over 120 days, and vet keeps only >= 5-night links with a bound two-body fit within 0.3"
70
+ MODES = dict(tno={}, mid=dict(dist_min=15.0, dist_max=30.0, dtmax=20.0),
71
+ far=dict(dist_min=80.0, dist_max=1500.0, dtmax=120.0, survive_nights=5, kepler_rms_max=0.3),
72
+ multiyear=dict(dist_min=80.0, dist_max=3000.0, passes=((80.0, 150.0, 120.0), (150.0, 300.0, 250.0), (300.0, 3000.0, 600.0)),
73
+ survive_nights=4, kepler_rms_max=0.3),
74
+ dense=dict(dist_min=25.0, dist_max=80.0))
75
+ # multiyear: 3 nights within 120 / 250 / 600 days seed a link at 80-150 / 150-300 / 300-3000 AU, which is then extended over
76
+ # every night of every year; for slow movers that the archive caught on scattered nights only (vet: bound fit within 0.3")
77
+ # dense: the anchor linker of orbitsift.dense (exposure cap, clump mask, same-night partners), 25-80 AU; one tile
78
+ NEAR_PASSES = (("N", 8.0, 14.0, 20.0), ("F", 14.0, 35.0, 40.0)) # name, AU min, AU max, seed nights within [d]
79
+ NEAR_MARGIN = 2.5 # deg of data around the core: an 8-AU object moves degrees in 40 days
80
+ NEAR_KW = dict(sig=0.2, dgam=2e-3, nmin=4, dmag=1.0, rcap=900.0, vfac=1.1, curvature=True)
81
+
82
+
83
+ def _near_core(box, t):
84
+ """Near mode: (core box, data box = core + NEAR_MARGIN, the data box's tiles)."""
85
+ core = [t["ra0"], t["ra1"], t["dec0"], t["dec1"]] if t else list(box)
86
+ mr = NEAR_MARGIN / np.cos(np.radians(min(89.0, max(abs(core[2]), abs(core[3])) + NEAR_MARGIN)))
87
+ data = [core[0] - mr, core[1] + mr, max(core[2] - NEAR_MARGIN, -90.0), min(core[3] + NEAR_MARGIN, 90.0)]
88
+ return core, data, tiles.tiles_in(*data)
89
+
90
+
91
+ BLOCK_RMS_MAX = 0.25 # cross-tile: at 3x3 density the default 0.5" lets real links grow with chance detections
92
+ BLOCK_MAX_DETECTIONS = 200000 # cross-tile blocks with more detections (deep fields) are skipped
93
+
94
+
95
+ def _region(a):
96
+ """(box, tile or None, tag) from --tile / --box."""
97
+ if a.tile:
98
+ t = tiles.tile(*a.tile)
99
+ return t["box"], t, t["id"]
100
+ if getattr(a, "box", None):
101
+ ra0, ra1, dec0, dec1 = a.box
102
+ return [ra0, ra1, dec0, dec1], None, f"box_{ra0:g}_{ra1:g}_{dec0:g}_{dec1:g}"
103
+ raise BadInput("give --tile RA DEC or --box RA0 RA1 DEC0 DEC1")
104
+
105
+
106
+ def _obs(path, trk):
107
+ obs = ades.read(path)
108
+ if trk is None:
109
+ if len(obs) != 1:
110
+ raise BadInput(f"{path} holds {len(obs)} tracks ({', '.join(obs)}): choose one with --trk")
111
+ trk = next(iter(obs))
112
+ if trk not in obs:
113
+ raise BadInput(f"track {trk} not in {path}")
114
+ return trk, obs[trk]
115
+
116
+
117
+ def _arc(obs, cfg):
118
+ from .orbit import Arc
119
+ return Arc([o["mjd"] for o in obs], [o["ra"] for o in obs], [o["dec"] for o in obs], cfg["orbit"]["sigma"],
120
+ [o["stn"] or cfg["site"] for o in obs])
121
+
122
+
123
+ def _fit(arc, cfg, quiet=False, backend="internal", obs=None, bound=True):
124
+ """Best orbit of arc; backend 'findorb' fits ``obs`` (ades.read rows) with Find_Orb instead (orbit.info
125
+ holds its details: version, ephemeris, rejected observations, its own elements at arc.t0)."""
126
+ from . import orbit
127
+ t = time.time()
128
+ if backend == "findorb":
129
+ from .external import findorb_fit
130
+ r = findorb_fit(obs, cfg["orbit"]["sigma"], cfg["site"], arc.t0)
131
+ o = r and r[0]
132
+ if o is not None:
133
+ o.info = r[1]
134
+ else:
135
+ o = orbit.fit(arc, cfg["orbit"]["r_min"], cfg["orbit"]["r_max"], bound=bound)
136
+ if o is None:
137
+ raise NoResult("no_bound_orbit", "no bound orbit fits these observations") if bound else NoResult("no_orbit", "no orbit found")
138
+ if not quiet:
139
+ e, h = o.elements(), orbit.helio_elements(o.x0, o.v0, o.t0)
140
+ if backend == "findorb":
141
+ f = o.info["findorb"]
142
+ print(f"Find_Orb {f['version']} ({f['ephemeris']}): {f['n_rejected']} of {len(arc)} observations rejected, "
143
+ f"epoch JD {o.t0:.5f}")
144
+ print(f"{len(arc)} obs, arc {arc.days:.0f} d, rms {o.rms:.3f}\", r {o.r:.2f} AU ({time.time() - t:.0f} s)")
145
+ print(f" barycentric a {e['a']:.2f} AU e {e['e']:.3f} i {e['i']:.2f} deg")
146
+ print(f" heliocentric a {h['a']:.2f} AU e {h['e']:.3f} i {h['i']:.2f} deg node {h['node']:.2f} peri {h['peri']:.2f} M {h['M']:.2f}")
147
+ if arc.days < 300:
148
+ print(" short arc: a and e are poorly constrained, see the sample spread (--samples)")
149
+ return o
150
+
151
+
152
+ def _mags(obs):
153
+ by = {}
154
+ for o in obs:
155
+ if o["mag"] is not None:
156
+ by.setdefault(o["band"], []).append(o["mag"])
157
+ return {b: float(np.median(m)) for b, m in by.items()}
158
+
159
+
160
+ def link_point_sources(rows, min_snr=4.0, max_offset=1.0, max_bad=1):
161
+ """The input detections measured on their own images (forced's validation rows): those measured at S/N >= min_snr
162
+ within max_offset ["] whose PSF width ratio is outside the point-source window (images.point_like) are not point
163
+ sources; more than max_bad of them reject the link (a cosmic-ray or artefact link can fit an orbit to 0.1").
164
+ -> dict(tested, not_point, passed)."""
165
+ from . import images
166
+ t = [r for r in rows if r.get("snr_fit", 0) >= min_snr and np.hypot(*r.get("offset", [9, 9])) <= max_offset]
167
+ bad = [r for r in t if not images.point_like(r["snr_fit"], r.get("s_ratio", 0))]
168
+ return dict(tested=len(t), not_point=len(bad), passed=len(bad) <= max_bad)
169
+
170
+
171
+ def _confirm(arc, points, mags, rms, bound=True):
172
+ """The confirmation rules on new detections of a tracked object: points [(mjd, mag, band)], rms ["] and
173
+ boundness of the orbit fitted to arc + points. -> (verdict, checks). The known-object check is not part
174
+ of it (do it on the full arc: vet --ident, or a wide sb_ident / MPC search)."""
175
+ from .precovery import mag_in
176
+ arc_nights = set(catalog.night(arc.mjd).tolist())
177
+ nights = sorted({int(catalog.night(m)) for m, _, _ in points} - arc_nights)
178
+ dm = [m - mag_in(mags, b) for _, m, b in points if m is not None]
179
+ dmag = float(np.median(dm)) if dm else None
180
+ checks = dict(new_nights=len(nights), nights_ok=len(nights) >= CONFIRM["nights"], rms_arcsec=rms,
181
+ rms_ok=bool(bound and rms is not None and rms <= CONFIRM["rms_arcsec"]), bound=bool(bound),
182
+ dmag=dmag, mag_ok=dmag is not None and abs(dmag) <= CONFIRM["dmag"], known_checked=False)
183
+ bad = [k for k in ("nights", "rms", "mag") if not checks[f"{k}_ok"]]
184
+ return ("consistent" if not bad else "not_consistent:" + ",".join(bad)), checks
185
+
186
+
187
+ # ---- results (also stored in each output file as "summary", so an up-to-date re-run returns it) ----
188
+
189
+ def _link_rows(doc):
190
+ return [dict(index=k, nights=l["nights"], n=l["n"], dist_au=l["dist_au"], rms_arcsec=l["rms"], V=l["V"], ra=l["ra"],
191
+ dec=l["dec"]) for k, l in enumerate(doc["links"])]
192
+
193
+
194
+ def _link_summary(doc, tag):
195
+ s = dict(verdict="not_searched" if doc.get("not_searched") else "linked" if doc["links"] else "no_links", region=tag,
196
+ source=doc.get("source", "nsc_dr2"), detections=doc["n_detections"], nights=doc["nights"],
197
+ n_links=len(doc["links"]), edge_links_dropped=doc["edge_links_dropped"], links=_link_rows(doc))
198
+ for k in ("not_searched", "tiles_left_out"):
199
+ if doc.get(k):
200
+ s[k] = doc[k]
201
+ return s
202
+
203
+
204
+ def _link_verdict(v):
205
+ vetoes = [w for w in VETOES if v.get(f"veto_{w}")]
206
+ vetoes += [f"plugin_{n}" for n in v.get("veto_plugins", [])]
207
+ if v["survives"]:
208
+ k = v.get("known") or []
209
+ return (f"known:{k[0][0]}" if k and k[0][1] <= KNOWN_MATCH_ARCSEC else "survives"), vetoes
210
+ return ("vetoed:" + ",".join(vetoes) if vetoes else "unchecked:static_query_failed"), vetoes
211
+
212
+
213
+ def _vet_summary(doc):
214
+ rows = _link_rows(doc)
215
+ for r, l in zip(rows, doc["links"]):
216
+ v = l["vet"]
217
+ r["verdict"], r["vetoes"] = _link_verdict(v)
218
+ r["known_checked"] = "known" in v
219
+ r["known"] = [dict(name=n, dist_arcsec=d, V=m) for n, d, m in v.get("known", [])]
220
+ r["kepler"] = v.get("kepler")
221
+ r["plugins"] = v.get("plugins", {})
222
+ verdicts = [r["verdict"] for r in rows]
223
+ top = ("candidates" if "survives" in verdicts else "known_only" if any(x.startswith("known:") for x in verdicts)
224
+ else "no_survivors")
225
+ return dict(verdict=top, region=(doc.get("tile") or {}).get("id"), n_links=len(rows),
226
+ survivors=sum(l["vet"]["survives"] for l in doc["links"]), vetted=doc["vetted"],
227
+ complete=not any(x.startswith("unchecked") for x in verdicts), links=rows)
228
+
229
+
230
+ # ---- commands ----
231
+
232
+ def cmd_fetch(a, cfg):
233
+ box, t, tag = _region(a)
234
+ rows = catalog.orphans(box)
235
+ ex = catalog.exposures(box)
236
+ d = catalog.detections(rows)
237
+ c = ((box[0] + box[1]) / 2, (box[2] + box[3]) / 2)
238
+ n = tiles.nights_covering(ex, *c)[0]
239
+ print(f"{tag}: {len(rows)} single-night objects, {len(d['ra'])} after cuts and static veto "
240
+ f"({len(d['ra']) / tiles.area(box):.0f}/deg2) on {len(np.unique(d['night']))} nights; "
241
+ f"{len(ex['mjd'])} DECam exposures nearby, {len(n)} nights cover the centre. Cached in {config.cache_dir()}")
242
+ return dict(verdict="fetched", region=tag, box=box, single_night_objects=len(rows), detections=len(d["ra"]),
243
+ nights=int(len(np.unique(d["night"]))), exposures=len(ex["mjd"]), nights_covering_centre=len(n),
244
+ cache_dir=str(config.cache_dir()))
245
+
246
+
247
+ def _rows_file(a):
248
+ """--rows: a rows file, or a folder of tile files <tile id>.csv.gz (then --tile says which)."""
249
+ p = Path(a.rows)
250
+ if p.is_dir():
251
+ if not a.tile:
252
+ raise BadInput("--rows DIR holds one file per tile: give --tile RA DEC")
253
+ p = p / f"{tiles.tile(*a.tile)['id']}.csv.gz"
254
+ if not p.exists():
255
+ raise BadInput(f"{p}: no such rows file")
256
+ return p
257
+
258
+
259
+ def _detections(a, box):
260
+ """(n single-night rows, detections) from NSC DR2, from a local table of standard rows (--rows: cleaned by whoever
261
+ made it, so no shape cut here), or from a source plugin (--source)."""
262
+ if getattr(a, "rows", None):
263
+ from .multiyear import read_rows
264
+ rows = [r for r in read_rows(_rows_file(a)) if (float(r["ra"]) - box[0]) % 360 <= box[1] - box[0] and box[2] <= float(r["dec"]) <= box[3]]
265
+ return len(rows), catalog.detections(rows, fwhm_range=(0.0, 99.0))
266
+ if not getattr(a, "source", None):
267
+ rows = catalog.orphans(box)
268
+ return len(rows), catalog.with_sites(catalog.detections(rows))
269
+ src = plugins.get("sources").get(a.source)
270
+ if src is None:
271
+ raise BadInput(f"no working source plugin '{a.source}' (see orbitsift plugins)")
272
+ d = {k: np.asarray(v) for k, v in src.detections(list(box)).items()}
273
+ return len(d["ra"]), d
274
+
275
+
276
+ def cmd_link(a, cfg, out=None):
277
+ from .link import link_detections
278
+ box, t, tag = _region(a)
279
+ p = dict(cfg["link"])
280
+ mode = getattr(a, "mode", "tno")
281
+ p.update({k: v for k, v in MODES[mode].items() if k in p})
282
+ if mode != "tno":
283
+ p["mode"] = mode
284
+ for k, v in (("dist_min", a.dist and a.dist[0]), ("dist_max", a.dist and a.dist[1]), ("dtmax", a.dtmax), ("nmin", a.min_nights)):
285
+ if v:
286
+ p[k] = v
287
+ blocks = getattr(a, "blocks", 1) or 1
288
+ left, dense = [], False # tiles of the block left out as too dense; the centre was one
289
+ local = getattr(a, "rows", None)
290
+ if local and (blocks > 1 or getattr(a, "near", False) or getattr(a, "source", None)):
291
+ raise BadInput("--rows links one local table: no --blocks, --near or --source")
292
+ if local and mode == "dense" and not a.exposures:
293
+ raise BadInput("--mode dense with --rows needs --exposures (the table of the rows' exposures)")
294
+ if getattr(a, "near", False):
295
+ if blocks > 1 or getattr(a, "source", None):
296
+ raise BadInput("--near takes neither --blocks nor --source")
297
+ return _link_near(a, cfg, box, t, tag, out)
298
+ if mode == "dense" and (blocks > 1 or getattr(a, "source", None)):
299
+ raise BadInput("--mode dense links one region of NSC DR2 (it needs the exposures): no --blocks, no --source")
300
+ if blocks > 1: # cross-tile: the n x n neighbours' rows, links kept in the centre tile
301
+ if not t or getattr(a, "source", None):
302
+ raise BadInput("--blocks needs --tile and NSC DR2 (no --source)")
303
+ rows = catalog.block_orphans(t, tiles.block(t, blocks), left_out=left)
304
+ n_rows, d = len(rows), catalog.with_sites(catalog.detections(rows))
305
+ p["rms_max"] = BLOCK_RMS_MAX
306
+ dense = len(d["ra"]) > BLOCK_MAX_DETECTIONS or t["id"] in left
307
+ if dense:
308
+ print(f"{tag}: too dense ({len(d['ra'])} detections in the {blocks}x{blocks} block, max {BLOCK_MAX_DETECTIONS}, "
309
+ f"or > {catalog.MAX_DENSITY}/deg2 in the tile): not searched")
310
+ d = {k: v[:0] for k, v in d.items()}
311
+ else:
312
+ n_rows, d = _detections(a, box)
313
+ t0 = time.time()
314
+ kw = {k: v for k, v in p.items() if k != "mode"}
315
+ dinfo = None
316
+ if mode == "dense":
317
+ from . import _native, dense as anchor
318
+ if not hasattr(_native.lib, "dense_link") and len(d["ra"]) > 20000:
319
+ print(f"{tag}: orbitsift-native is not installed: the Python linker takes ~1000 times longer than the compiled "
320
+ "one on a tile this size (pip install ./native)")
321
+ ex, foot = None if local else catalog.exposures(box), {}
322
+ if local:
323
+ from .multiyear import read_exposures
324
+ ex = read_exposures(a.exposures)
325
+ if "radius" in ex: # a table of single detectors: its footprint instead of DECam's
326
+ r = 3600 * float(np.nanmedian(ex["radius"]))
327
+ foot = dict(rmiss=r, rcov=r + 400.0)
328
+ links, dinfo = anchor.link_tile(d, ex, (box[0] + box[1]) / 2, (box[2] + box[3]) / 2, cfg["site"],
329
+ p["dist_min"], p["dist_max"], dtmax=p["dtmax"], nmin=p["nmin"], dmag=p["dmag"], **foot)
330
+ if dinfo["too_dense"]:
331
+ print(f"{tag}: too dense ({dinfo['rows_linked']} rows after the exposure cap and the clump mask, max "
332
+ f"{anchor.MAX_ROWS}): not searched")
333
+ elif "passes" in MODES[mode]: # multi-year: distance passes whose seed windows span seasons
334
+ p["passes"] = [list(x) for x in MODES[mode]["passes"]]
335
+ links = _one_per_object([dict(l, passname=f"{r0:g}-{r1:g}") for r0, r1, dt in MODES[mode]["passes"]
336
+ for l in link_detections(d, (box[0] + box[1]) / 2, (box[2] + box[3]) / 2, cfg["site"],
337
+ **dict(kw, dist_min=r0, dist_max=r1, dtmax=dt))])
338
+ else:
339
+ links = link_detections(d, (box[0] + box[1]) / 2, (box[2] + box[3]) / 2, cfg["site"], **kw)
340
+ edge = 0
341
+ if t:
342
+ core = [l for l in links if tiles.in_core(t, l["ra"], l["dec"])]
343
+ edge, links = len(links) - len(core), core
344
+ doc = dict(orbitsift=__version__, tile=t, box=box, site=cfg["site"], params=p, n_orphans=n_rows,
345
+ n_detections=len(d["ra"]), nights=int(len(np.unique(d["night"]))), seconds=round(time.time() - t0, 1),
346
+ edge_links_dropped=edge, links=links)
347
+ if blocks > 1:
348
+ doc["blocks"] = blocks
349
+ doc["tiles_left_out"] = left
350
+ if dense:
351
+ doc["not_searched"] = "too_dense"
352
+ if dinfo is not None:
353
+ doc["dense"] = dinfo
354
+ if dinfo["too_dense"]:
355
+ doc["not_searched"] = "too_dense"
356
+ if getattr(a, "source", None):
357
+ doc["source"] = a.source
358
+ if local:
359
+ doc["source"] = "rows"
360
+ doc["tables"] = dict(rows=str(_rows_file(a)), exposures=a.exposures)
361
+ print(f"{tag}: {len(d['ra'])} detections, {doc['nights']} nights -> {len(links)} links "
362
+ f"(>= 5 nights: {sum(l['nights'] >= 5 for l in links)}) in {doc['seconds']} s")
363
+ doc["summary"] = _link_summary(doc, tag)
364
+ _dump(doc, out or a.out, a)
365
+ return doc
366
+
367
+
368
+ def _one_per_object(links):
369
+ """Links of several passes, longest and tightest first, dropping any that shares >= 2 detections with a kept one."""
370
+ keep, own = [], {}
371
+ for l in sorted(links, key=lambda l: (-l["nights"], l["rms"])):
372
+ hit = {}
373
+ for x in l["ids"]:
374
+ for o in own.get(x, ()):
375
+ hit[o] = hit.get(o, 0) + 1
376
+ if not any(v >= 2 for v in hit.values()):
377
+ for x in l["ids"]:
378
+ own.setdefault(x, []).append(len(keep))
379
+ keep.append(l)
380
+ return keep
381
+
382
+
383
+ def _link_near(a, cfg, box, t, tag, out):
384
+ """Near mode: 8-35 AU, any direction of motion, two passes, seeds only from the core (the tile's cell or the box);
385
+ every pair is tried in exactly one core, the margin supplies the later nights. Links are kept wherever their mean
386
+ falls (neighbouring cores can report the same object: merge on shared detections)."""
387
+ from .link import link_detections
388
+ core, data, ts = _near_core(box, t)
389
+ centre, left = tiles.tile((core[0] + core[1]) / 2, (core[2] + core[3]) / 2), []
390
+ rows = catalog.block_orphans(centre, ts, left_out=left)
391
+ d = catalog.with_sites(catalog.detections(rows, veto="lsnd"))
392
+ ra0, dec0 = (core[0] + core[1]) / 2, (core[2] + core[3]) / 2
393
+ amask = ((d["ra"] - core[0]) % 360 < core[1] - core[0]) & (d["dec"] >= core[2]) & (d["dec"] < core[3])
394
+ t0, links = time.time(), []
395
+ for name, rmin, rmax, dtmax in NEAR_PASSES:
396
+ for l in link_detections(d, ra0, dec0, cfg["site"], rmin, rmax, dtmax=dtmax, amask=amask,
397
+ ext_days=3 * dtmax, **NEAR_KW):
398
+ links.append(dict(l, passname=name))
399
+ keep = _one_per_object(links)
400
+ p = dict(near=True, dist_min=8.0, dist_max=35.0, passes=[list(x) for x in NEAR_PASSES], margin=NEAR_MARGIN, **NEAR_KW)
401
+ doc = dict(orbitsift=__version__, tile=t, box=core, data_box=data, site=cfg["site"], params=p, n_orphans=len(rows),
402
+ n_detections=len(d["ra"]), nights=int(len(np.unique(d["night"]))), seconds=round(time.time() - t0, 1),
403
+ edge_links_dropped=0, links=keep, tiles_left_out=left)
404
+ if centre["id"] in left:
405
+ doc["not_searched"] = "too_dense"
406
+ print(f"{tag} (near, core + {NEAR_MARGIN} deg): {len(d['ra'])} detections, {doc['nights']} nights -> {len(keep)} links "
407
+ f"(>= 5 nights: {sum(l['nights'] >= 5 for l in keep)}) in {doc['seconds']} s")
408
+ doc["summary"] = _link_summary(doc, tag)
409
+ _dump(doc, out or a.out, a)
410
+ return doc
411
+
412
+
413
+ def _vet_table(doc):
414
+ print(" # nights dist rms\" V RA Dec result")
415
+ for k, l in enumerate(doc["links"]):
416
+ v = l["vet"]
417
+ why = [w for w in VETOES if v.get(f"veto_{w}")]
418
+ why += [f"plugin:{n}" for n in v.get("veto_plugins", [])]
419
+ res = "SURVIVES" if v["survives"] else ("veto " + ",".join(why) if why else "static check failed (TAP)")
420
+ if v.get("known"):
421
+ res += " known nearby: " + ", ".join(f"{n} ({d:.0f}\")" for n, d, _ in v["known"][:3])
422
+ print(f"{k:2d} {l['nights']:5d} {l['dist_au']:5.0f} {l['rms']:.3f} {l['V']:4.1f} {l['ra']:9.4f} {l['dec']:+8.4f} {res}")
423
+
424
+
425
+ def cmd_vet(a, cfg, doc=None, out=None):
426
+ from . import vet
427
+ if doc is None:
428
+ doc = json.load(open(a.links))
429
+ if "links" not in doc:
430
+ raise BadInput(f"{a.links}: not a 'link' output file")
431
+ if doc.get("source"):
432
+ raise BadInput(f"links from source '{doc['source']}': the core vetoes use NSC DR2 data; vet them with that "
433
+ "source's own vetter plugin (links of local tables, 'rows': docs/RUBIN.md)")
434
+ vet.vet(doc, cfg["site"], static=not a.no_static, kepler=not a.no_kepler, ident=a.ident, vetters=plugins.get("vetters"),
435
+ **cfg["vet"])
436
+ _vet_table(doc)
437
+ print(f"{doc['vetted']['survivors']} of {len(doc['links'])} links survive")
438
+ doc["summary"] = _vet_summary(doc)
439
+ _dump(doc, out or a.out, a)
440
+ return doc["summary"]
441
+
442
+
443
+ def _fit_summary(trk, od, pct=None):
444
+ return dict(verdict="fitted", trk=trk, n_obs=od["n"], arc_days=od["arc_days"], rms_arcsec=od["rms_arcsec"], r_au=od["r_au"],
445
+ bound=od["bound"], short_arc=od["arc_days"] < 300, frame=od["frame"], center=od["center"],
446
+ t0_jd_tdb=od["t0_jd_tdb"], elements_bary=od["elements_bary"], elements_helio=od["elements_helio"],
447
+ sample_percentiles=pct, **({k: od[k] for k in ("backend", "findorb")} if "findorb" in od else {}))
448
+
449
+
450
+ def _odict(o):
451
+ """Orbit JSON, with the backend's details when it is not the internal fit."""
452
+ return {**o.to_dict(), **getattr(o, "info", {})}
453
+
454
+
455
+ def cmd_fit(a, cfg):
456
+ from . import orbit
457
+ trk, obs = _obs(a.obs, a.trk)
458
+ arc = _arc(obs, cfg)
459
+ if a.r_min:
460
+ cfg["orbit"]["r_min"] = a.r_min
461
+ backend, warn = a.backend, []
462
+ if backend == "auto": # multi-season arcs: Find_Orb (perturbations) when installed
463
+ backend = "internal"
464
+ if 1 + int((np.diff(np.sort(arc.mjd)) > 120).sum()) >= cfg["orbit"]["findorb_min_seasons"]:
465
+ from .external import findorb_exe
466
+ try:
467
+ findorb_exe()
468
+ backend = "findorb"
469
+ except FileNotFoundError:
470
+ warn.append(f"long_arc_internal_fit: arc of >= {cfg['orbit']['findorb_min_seasons']} seasons fitted with the internal "
471
+ "two-body orbit (no planetary perturbations, uncertainties too small); install Find_Orb (ORBITSIFT_FINDORB or fo on PATH)")
472
+ print("warning: " + warn[-1], file=sys.stderr)
473
+ o = _fit(arc, cfg, backend=backend, obs=obs, bound=not a.unbound)
474
+ out = dict(trk=trk, orbit=_odict(o))
475
+ if a.samples: # Find_Orb: linear draws from its covariance, at its epoch
476
+ S = orbit.sample(arc, o, a.samples, "linear" if backend == "findorb" else "auto", bound=not a.unbound)
477
+ el = np.array([[orbit.elements(s[:3], s[3:])[k] for k in ("a", "e", "i")] for s in S])
478
+ pct = {k: np.percentile(el[:, j], [5, 50, 95]).round(3).tolist() for j, k in enumerate(("a", "e", "i"))}
479
+ print(f" {len(S)} samples, barycentric 5/50/95%: a {pct['a']} e {pct['e']} i {pct['i']}")
480
+ out.update(samples=np.round(S, 10).tolist(), samples_frame=[o.frame, o.center], sample_percentiles=pct)
481
+ out["summary"] = _fit_summary(trk, out["orbit"], out.get("sample_percentiles"))
482
+ if warn:
483
+ out["warnings"] = out["summary"]["warnings"] = warn
484
+ _dump(out, a.out, a)
485
+ return out["summary"]
486
+
487
+
488
+ def cmd_precover(a, cfg):
489
+ from . import orbit, precovery
490
+ trk, obs = _obs(a.obs, a.trk)
491
+ arc = _arc(obs, cfg)
492
+ o = _fit(arc, cfg)
493
+ S = orbit.sample(arc, o, a.samples)
494
+ p = dict(cfg["precovery"])
495
+ mags = _mags(obs)
496
+ res = precovery.search(arc, S, mags, cfg["site"], max_tiles=a.max_tiles, **p)
497
+ print(f"{len(res['candidates'])} candidates; best:")
498
+ for c in res["candidates"][:10]:
499
+ print(f" {c['exposure']} {c['band']} {c['mag']:.2f} n={c['n']} rms {c['rms']:.3f}\" a {c['elements']['a']:.1f}")
500
+ rows = []
501
+ for k, c in enumerate(res["candidates"]):
502
+ v, checks = _confirm(arc, [(q["mid"], q["mag"], q["band"]) for q in c["points"]], mags, c["rms"], c["bound"])
503
+ rows.append(dict(index=k, exposure=c["exposure"], mjd=c["mid"], band=c["band"], mag=c["mag"], n=c["n"],
504
+ rms_arcsec=c["rms"], bound=c["bound"], a_au=c["elements"]["a"], e=c["elements"]["e"],
505
+ i=c["elements"]["i"], verdict=v, checks=checks))
506
+ vs = [r["verdict"] for r in rows]
507
+ summary = dict(verdict="consistent" if "consistent" in vs else "not_consistent" if rows else "no_candidates", trk=trk,
508
+ searched_exposures=res["n_exposures"], expected_detections=res["expected"], tiles=res["tiles"],
509
+ tiles_searched=res["tiles_searched"], n_candidates=len(rows), n_consistent=vs.count("consistent"),
510
+ candidates=rows[:50], confirm_rules=CONFIRM)
511
+ _dump(dict(trk=trk, orbit=o.to_dict(), **res, summary=summary), a.out, a)
512
+ return summary
513
+
514
+
515
+ def _forced_end(a, cfg):
516
+ return a.end or cfg["forced"]["end"] or str(np.datetime64("today"))
517
+
518
+
519
+ def cmd_forced(a, cfg):
520
+ import importlib.util
521
+ from . import images, orbit
522
+ if a.measure_backend == "photutils" and importlib.util.find_spec("photutils") is None:
523
+ raise BadInput("photutils is not installed: pip install 'orbitsift[photutils]'")
524
+ measure = images.measure_photutils if a.measure_backend == "photutils" else images.measure
525
+ trk, obs = _obs(a.obs, a.trk)
526
+ arc = _arc(obs, cfg)
527
+ o = _fit(arc, cfg)
528
+ S = orbit.sample(arc, o, a.samples)
529
+ f = cfg["forced"]
530
+ start, end = a.start or f["start"], _forced_end(a, cfg)
531
+ from astropy.time import Time
532
+ T = images.ccd_targets(S, o.t0, Time(start).mjd, Time(end).mjd, a.max_ext or f["max_ext"], cfg["site"])
533
+ print(f"{len(T)} public DECam CCDs contain the prediction")
534
+ ddir = Path(a.download_dir) if a.download_dir else config.cache_dir() / "ccd"
535
+ if T: # Gaia stars of every CCD in a few bulk queries
536
+ RA, DE = orbit.predict(S[:1], o.t0, np.array([h["mjd_arch"] for h in T]), cfg["site"])
537
+ images.gaia_prefetch(list(zip(RA[0], DE[0])))
538
+ R, stamps = [], []
539
+ for h in T:
540
+ p = images.retrieve(h, ddir)
541
+ rep = [x for x in obs if abs(x["mjd"] - images.mjd_of(h["file_dateobs"])) < 0.1]
542
+
543
+ def pred(mid):
544
+ near = [x for x in rep if abs(x["mjd"] - mid) < 30 / 86400]
545
+ if near: # exposure of a reported detection: validation
546
+ return near[0]["ra"], near[0]["dec"], np.eye(2) * 0.3 ** 2
547
+ RA, DE = orbit.predict(S, o.t0, [mid], cfg["site"])
548
+ xy = np.c_[((RA[:, 0] - RA[0, 0] + 180) % 360 - 180) * np.cos(np.radians(DE[0, 0])) * 3600, (DE[:, 0] - DE[0, 0]) * 3600]
549
+ lo, hi = np.percentile(xy, [0.5, 99.5], 0)
550
+ m = ((xy >= lo) & (xy <= hi)).all(1)
551
+ return float(RA[0, 0]), float(DE[0, 0]), np.cov(xy[m].T) + np.eye(2) * 1e-4
552
+ try:
553
+ r, st = measure(p, pred)
554
+ except (net.ServiceError, urllib.error.URLError) as e: # a calibration query that got no answer: unknown, not absent
555
+ r, st = dict(file=p.name, err=repr(e), failed="network"), None
556
+ except Exception as e:
557
+ r, st = dict(file=p.name, err=repr(e)), None
558
+ r["validation"] = any(abs(x["mjd"] - r.get("mid", 0)) < 30 / 86400 for x in rep)
559
+ r["accepted"] = bool(not r.get("err") and not r["validation"] and r.get("snr_fit", 0) >= (a.min_snr or f["min_snr"])
560
+ and r.get("dmah_psf", 99) <= 3 and images.point_like(r.get("snr_fit", 0), r.get("s_ratio", 0)) and r.get("stars", {}).get("n", 0) >= 3)
561
+ R.append(r)
562
+ if st:
563
+ stamps.append((st, f"{r['date_obs'][:10]} {r['filt']} S/N {r.get('snr_fit', 0):.0f}" + (" (val)" if r["validation"] else "")))
564
+ print(f" {r['file']:40s} {r.get('filt', ''):2s} S/N {r.get('snr_fit', float('nan')):5.1f} offset {np.round(r.get('offset', [np.nan] * 2), 2)}"
565
+ f" {'VALIDATION' if r['validation'] else 'accepted' if r['accepted'] else r.get('err', '')}")
566
+ val = [r for r in R if r["validation"] and "offset" in r]
567
+ vrms = None
568
+ if val:
569
+ off = np.array([r["offset"] for r in val])
570
+ vrms = float(np.sqrt(np.mean(off ** 2)))
571
+ print(f"validation on {len(val)} reported detections: rms offset {vrms:.3f}\" per coordinate")
572
+ paths = [ddir / r["file"] for r in R if "err" not in r]
573
+ for r in R:
574
+ if r["accepted"]:
575
+ r["static"] = images.static_check(r, paths)
576
+ if sum(s["snr"] > 5 for s in r["static"]) >= 2:
577
+ r["accepted"] = False
578
+ r["reject"] = "source at the same sky position on other nights (static)"
579
+ if a.plot and stamps:
580
+ images.montage([s for s, _ in stamps], [l for _, l in stamps], f"{trk}_forced.png")
581
+ print(f"{sum(r['accepted'] for r in R)} measurements accepted by the default cuts: inspect them before export")
582
+ acc = [r for r in R if r["accepted"]]
583
+ verdict, checks = "no_accepted_measurements", None
584
+ if acc:
585
+ a2 = arc.extend([r["mid"] for r in acc], [r["ra"] for r in acc], [r["dec"] for r in acc], site=cfg["site"])
586
+ try:
587
+ o2 = _fit(a2, cfg, True, a.backend, obs + [dict(mjd=r["mid"], ra=r["ra"], dec=r["dec"], stn=cfg["site"], astCat="Gaia3")
588
+ for r in acc])
589
+ except NoResult:
590
+ o2 = None
591
+ verdict, checks = _confirm(arc, [(r["mid"], r.get("mag"), r["filt"]) for r in acc], _mags(obs),
592
+ o2.rms if o2 else None, bool(o2 and o2.bound))
593
+ point = link_point_sources(val)
594
+ if not point["passed"]:
595
+ verdict = "rejected:link_not_point_like"
596
+ failed = sum(r.get("failed") == "network" for r in R)
597
+ if failed:
598
+ print(f"{failed} CCD(s) not measured because a service did not answer: re-run (downloads and answers are cached)")
599
+ summary = dict(verdict=verdict, trk=trk, ccds=len(T), measured=sum("err" not in r for r in R), failed=failed, complete=not failed,
600
+ validation=dict(n=len(val), rms_arcsec=vrms, **point), accepted=len(acc), checks=checks, confirm_rules=CONFIRM,
601
+ measurements=[dict(file=r["file"], date_obs=r.get("date_obs"), filt=r.get("filt"), snr=r.get("snr_fit"),
602
+ validation=r["validation"], accepted=r["accepted"],
603
+ reason=r.get("reject") or r.get("err")) for r in R])
604
+ _dump(dict(trk=trk, orbit=o.to_dict(), measurements=R, summary=summary), a.out, a)
605
+ return summary
606
+
607
+
608
+ def cmd_extend(a, cfg):
609
+ from astropy.time import Time
610
+
611
+ from . import extend, orbit
612
+ from .precovery import mag_in
613
+ trk, obs = _obs(a.obs, a.trk)
614
+ arc = _arc(obs, cfg)
615
+ mags = _mags(obs)
616
+ names = [x.strip() for x in a.archives.split(",") if x.strip()]
617
+ bad = set(names) - set(extend.ARCHIVES)
618
+ if bad:
619
+ raise BadInput(f"unknown archive(s) {', '.join(sorted(bad))} (choose from {', '.join(extend.ARCHIVES)})")
620
+ V = mag_in(mags, "r") + 0.3 # TNO V - r ~ 0.3
621
+ start, end = a.start, a.end or str(np.datetime64("today"))
622
+ R = extend.run(arc, V, start, end, names, a.samples, a.ssois_clones, a.max_ext, a.max_exposures, a.per_night, a.max_iter,
623
+ a.min_snr, cfg["orbit"]["r_min"], cfg["orbit"]["r_max"], cloud=a.cloud, loo=a.loo,
624
+ exposures=a.exposures, allow_ssois=a.allow_ssois, allow_cutouts=a.allow_cutouts)
625
+ pts = R["points"]
626
+ o = R["orbit"]
627
+ if a.backend == "findorb" and pts: # the reported fit (the search itself uses the internal one)
628
+ o = _fit(R["arc"], cfg, True, "findorb", obs + [dict(mjd=p["mid"], ra=p["ra"], dec=p["dec"], rmsRA=max(p["sig"], 0.05),
629
+ rmsDec=max(p["sig"], 0.05), stn=p["site"], astCat="Gaia3") for p in pts])
630
+ nights = sorted({p["night"] for p in pts})
631
+ tested = {p["night"] for p in pts if p["static"] == "passed"} # nights with no other-night frame do not count
632
+ loo = R.get("leave_one_out")
633
+ dm = [p["mag"] - (V - 0.3) for p in pts if p["mag"] is not None] # Gaia-G zero points; TNO G - r ~ 0
634
+ dmag = float(np.median(dm)) if dm else None
635
+ sp = R["second_pass"]
636
+ checks = dict(new_nights=len(nights), static_tested_nights=len(tested), nights_ok=len(tested) >= CONFIRM["nights"],
637
+ rms_arcsec=o.rms if o else None,
638
+ rms_ok=bool(o and o.bound and o.rms <= CONFIRM["rms_arcsec"]), bound=bool(o and o.bound), dmag=dmag,
639
+ mag_ok=dmag is not None and abs(dmag) <= CONFIRM["dmag"], second_pass=sum(s["ok"] for s in sp),
640
+ second_pass_ok=bool(sp) and all(s["ok"] for s in sp),
641
+ loo_ok=bool(loo) and all(z["passed"] is not False for z in loo.values()), known_checked=False)
642
+ bad = [k for k in ("nights", "rms", "mag", "second_pass", "loo") if not checks[f"{k}_ok"]]
643
+ verdict = "consistent" if pts and not bad else ("not_consistent:" + ",".join(bad) if pts else "no_new_nights")
644
+ for p in pts:
645
+ print(f" {Time(p['mid'], format='mjd').iso[:16]} {p['inst']:8s} {p['filt']:3s} S/N {p['snr']:5.1f} shape {p['shape']:.2f} "
646
+ f"G {p['mag']:.2f} sigma {p['sig']:.3f}\"")
647
+ if o:
648
+ h = orbit.helio_elements(o.x0, o.v0, o.t0)
649
+ print(f"{len(pts)} new points on {len(nights)} new nights; arc {arc.days:.0f} -> {R['arc'].days:.0f} d, rms {o.rms:.3f}\", "
650
+ f"a {h['a']:.2f} AU e {h['e']:.3f} i {h['i']:.2f} deg")
651
+ for inst in sorted({x["inst"] for x in R["listed"]}): # login archives: what to request, by hand
652
+ L = [x for x in R["listed"] if x["inst"] == inst]
653
+ print(f" listed only: {len(L)} {inst} exposures ({Time(L[0]['mjd'], format='mjd').iso[:10]} .. "
654
+ f"{Time(L[-1]['mjd'], format='mjd').iso[:10]}, ids in the output) -> {L[0]['listed']}")
655
+ print(f"verdict {verdict}")
656
+ keep = ("origin", "archive", "inst", "site", "filt", "mid", "exptime", "ra", "dec", "sig", "snr", "mag", "shape", "offset", "night",
657
+ "iteration", "zp", "psf_fwhm", "wcs_rms", "nstar", "static", "static_snr")
658
+ out = lambda L: [{k: p.get(k) for k in keep + ("reject",)} for p in L]
659
+ summary = dict(verdict=verdict, trk=trk, arc_days=[arc.days, R["arc"].days], new_nights=len(nights), n_points=len(pts),
660
+ checks=checks, confirm_rules=CONFIRM, rules=extend.RULES, iterations=R["iterations"], frames_measured=R["frames"],
661
+ archives=names, listed=len(R["listed"]), elements_helio=orbit.helio_elements(o.x0, o.v0, o.t0) if o else None)
662
+ if "leave_one_out" in R:
663
+ summary["leave_one_out"] = {str(n): z for n, z in R["leave_one_out"].items()}
664
+ _dump(dict(trk=trk, orbit=_odict(o) if o else None, points=out(pts), rejected=out(R["rejected"]), second_pass=sp,
665
+ listed=R["listed"], summary=summary), a.out, a)
666
+ return summary
667
+
668
+
669
+ def cmd_libration(a, cfg):
670
+ from . import dynamics, orbit
671
+ if a.elements:
672
+ t0 = a.epoch
673
+ state = orbit.state_from_elements(*a.elements, t0)
674
+ X = dynamics.clones(state, a.clones)
675
+ name = "elements"
676
+ else:
677
+ trk, obs = _obs(a.obs, a.trk)
678
+ arc = _arc(obs, cfg)
679
+ o = _fit(arc, cfg, backend=a.fit_backend, obs=obs)
680
+ X = dynamics.clones(o.state, a.clones, cov=o.cov) if a.fit_backend == "findorb" else orbit.sample(arc, o, a.clones + 1)
681
+ t0, name = o.t0, trk
682
+ print(f"integrating {len(X)} particles for {a.kyr:g} kyr (Sun + 4 giants" + (", REBOUND WHFast" if a.backend == "rebound" else "") + ")...")
683
+ R = dynamics.libration(t0, X, a.kyr, backend=a.backend)
684
+ s = R["summary"]
685
+ print(f"L4 {s['frac_L4']:.0%} L5 {s['frac_L5']:.0%} escaped {s['frac_escaped']:.0%} other {s['frac_other']:.0%}"
686
+ + (f"; libration centre {s['centre_median']:.1f} deg, amplitude {s['amp_median']:.1f} deg" if s["centre_median"] else "")
687
+ + f" ({s['seconds']:.0f} s)")
688
+ if a.plot:
689
+ import matplotlib
690
+ matplotlib.use("Agg")
691
+ import matplotlib.pyplot as plt
692
+ fig, ax = plt.subplots(figsize=(8, 4))
693
+ for lr in R["lam_rel"]:
694
+ ax.plot(R["t"] / 1000, lr, lw=0.5)
695
+ ax.set_xlabel("time [kyr]")
696
+ ax.set_ylabel("lambda - lambda_Neptune [deg]")
697
+ fig.savefig(f"{name}_libration.png", dpi=110)
698
+ fr = {k: s[f"frac_{k}"] for k in ("L4", "L5", "escaped", "other")}
699
+ summary = dict(verdict=max(fr, key=fr.get), name=name, particles=s["n"], kyr=s["kyr"], fractions=fr,
700
+ centre_median_deg=s["centre_median"], amp_median_deg=s["amp_median"], nominal=s["nominal"]["cls"],
701
+ **({k: s[k] for k in ("backend", "rebound")} if a.backend == "rebound" else {}))
702
+ _dump(dict(name=name, t0_jd_tdb=t0, summary=s, clones=R["clones"], result=summary), a.out, a)
703
+ return summary
704
+
705
+
706
+ def cmd_classify(a, cfg):
707
+ from . import dynamics, external, orbit
708
+ trk, obs = _obs(a.obs, a.trk)
709
+ arc = _arc(obs, cfg)
710
+ o = _fit(arc, cfg, backend=a.fit_backend, obs=obs)
711
+ if o is None or o.cov is None:
712
+ raise BadInput(f"{trk}: no orbit with a covariance to draw clones from")
713
+ x = orbit.convert(o.state, o.t0, "ecliptic", "heliocentric") # the frame of Find_Orb's covariance
714
+ B = np.kron(np.eye(2), orbit.ECL)
715
+ print(f"{trk}: REBOUND MERCURIUS, nominal + {a.clones} clones, {a.myr:g} Myr ...")
716
+ t = time.time()
717
+ run = external.rebound_classes_run(o.t0, x, B @ o.cov @ B.T, a.myr * 1e6, a.clones, infl=a.infl)
718
+ k = dynamics.classify(run)
719
+ amp = [c["amp"] for c in k["clones"] if c["lab"] == k["cls"] and c["amp"] is not None]
720
+ a0 = run["a"][0][np.isfinite(run["a"][0])]
721
+ sa = float(np.diff(np.percentile(a0[1:], [16, 84]))[0] / 2 / a0[0]) if len(a0) > 2 else float("inf")
722
+ verdict = k["cls"]
723
+ if arc.days < 300 or sa > 0.05: # one apparition, or a too uncertain: the class means nothing
724
+ verdict = f"not classified ({'single apparition' if arc.days < 300 else 'sigma_a/a > 5%'})"
725
+ summary = dict(verdict=verdict, majority=k["cls"], sigma_a_rel=sa, arc_days=arc.days, trk=trk, agree=k["agree"], secure=k["agree"] >= 0.8, labels=k["labels"], des=k["des"],
726
+ des_agree=k["des_agree"], libration_amp_deg=float(np.median(amp)) if amp else None, clones=a.clones, myr=a.myr,
727
+ infl=a.infl, removed=int(np.isfinite(run["t_rm"]).sum()), dE=run["dE"], rebound=run["rebound"], seconds=round(time.time() - t))
728
+ print(f"{verdict}: majority {k['cls']} ({k['agree']:.0%} of {a.clones + 1} orbits{', secure' if summary['secure'] else ''}); "
729
+ f"DES rules: {k['des']} ({k['des_agree']:.0%}); sigma_a/a {sa:.2%}, arc {arc.days:.0f} d")
730
+ _dump(dict(trk=trk, t0_jd_tdb=o.t0, summary=summary, clones=k["clones"]), a.out, a)
731
+ return summary
732
+
733
+
734
+ def cmd_itf(a, cfg):
735
+ from . import itf
736
+ trk, obs = _obs(a.obs, a.trk)
737
+ if not Path(a.itf).exists():
738
+ raise BadInput(f"{a.itf}: no such file (download https://www.minorplanetcenter.net/iau/ITF/itf.txt.gz)")
739
+ Z = itf.load(a.itf, exclude=tuple(x.strip() for x in (a.exclude or "").split(",") if x.strip()))
740
+ r = itf.search(_arc(obs, cfg), Z, a.samples)
741
+ print(f"{trk}: {len(Z['t'])} ITF tracklets, {r['searched']} at times when the cloud is < {itf.CAP:.0f}\", {r['in_cloud']} inside it; "
742
+ f"{r['fits']} joint fits, {len(r['unconverged'])} unconverged; {len(r['hits'])} fit with the arc (controls on the shifted ITF: {r['controls']})")
743
+ for h in r["hits"]:
744
+ print(f" {h['trk']} {h['stn']} MJD {h['mjd']:.4f} n {h['n']} rms {h['rms']:.3f}\" max {h['res_max']:.2f}\" cloud {h['ext']:.0f}\"")
745
+ summary = dict(verdict="tracklets_to_verify" if r["hits"] else "undecided:unconverged" if r["unconverged"] else "none_found", trk=trk, **r)
746
+ _dump(dict(trk=trk, summary=summary), a.out, a)
747
+ return summary
748
+
749
+
750
+ def cmd_unused(a, cfg):
751
+ from . import archives, orbit, unused
752
+ trk, obs = _obs(a.obs, a.trk)
753
+ arc = _arc(obs, cfg)
754
+ o = _fit(arc, cfg)
755
+ if o is None:
756
+ raise BadInput(f"{trk}: no orbit")
757
+ V = a.V if a.V is not None else float(np.median([x["mag"] for x in obs if x.get("mag")] or [22.5])) + 0.3 # TNO V - r
758
+ S = orbit.sample(arc, o, a.clones + 1, "both")
759
+ ex = unused.eligible(S, o.t0, V, [x["mjd"] for x in obs], a.start, a.end, cfg["site"])
760
+ print(f"{trk}: V {V:.2f}, {len(ex)} eligible unused exposures (NSC DR2 era)")
761
+ rows = []
762
+ for x in ex[: a.max_exposures]:
763
+ r = dict(x, **unused.measure(x, archives.cache("unused", "x").parent))
764
+ rows.append(r)
765
+ print(f" {x['name']} {x['filt']:2s} margin {x['margin']:.2f} ext95 {x['ext95']:.1f}\" -> "
766
+ + (f"S/N {r['snr']:.1f}" if r["status"] == "ok" else r["status"]))
767
+ s = unused.summarize(rows)
768
+ print(f"{s['verdict']}: N {s['n']}, f_det {s['f_det']}, stack S/N {s['stack']}; controls passing {s['controls_pass']} of {s['controls']}")
769
+ summary = dict(s, trk=trk, V=V, eligible=len(ex))
770
+ _dump(dict(trk=trk, summary=summary, rows=[{k: (v.tolist() if hasattr(v, "tolist") else v) for k, v in r.items()} for r in rows]), a.out, a)
771
+ return summary
772
+
773
+
774
+ def cmd_identify(a, cfg):
775
+ from astropy.time import Time
776
+
777
+ from . import known, orbit
778
+ trk, obs = _obs(a.obs, a.trk)
779
+ arc = _arc(obs, cfg)
780
+ o = _fit(arc, cfg)
781
+ if o is None:
782
+ raise BadInput(f"{trk}: no orbit")
783
+ S = orbit.sample(arc, o, a.clones + 1, a.cloud)
784
+ hits = known.screen(S, o.t0, known.sbdb_outer(refresh=a.refresh))
785
+ mjd = Time(a.date or str(np.datetime64("today"))).mjd
786
+ fw = known.forward(S, o.t0, mjd, a.fwd_site, cfg["vet"]["ident_backend"], allow=True) # the command asks for it
787
+ print(f"{trk}: SBDB screen ({a.clones} clones): {len(hits)} orbit(s) inside the cloud" +
788
+ "".join(f"\n {h['name']}: {h['ang_deg']:.3f} deg (cloud {h['cloud99_deg']:.3f}), dr {h['dr_au']:.2f} AU, arc {h['arc_days']} d"
789
+ for h in hits[:10]))
790
+ print(f"forward to {a.date or 'today'}: cloud 99% {fw['ext99_arcsec']:.0f}\"; known inside: " +
791
+ (", ".join(f"{n} ({d:.0f}\")" for n, d, _ in fw["known"][:10]) or "none"))
792
+ verdict = "known_candidates" if hits or fw["known"] else "none_found"
793
+ summary = dict(verdict=verdict, trk=trk, screen=hits, forward=fw, clones=a.clones)
794
+ _dump(dict(trk=trk, summary=summary), a.out, a)
795
+ return summary
796
+
797
+
798
+ def _lov_result(r):
799
+ """A search result without its Orbit object (the hits keep their state, x and v at the arc's t0)."""
800
+ return {k: v for k, v in r.items() if k != "orbit"}
801
+
802
+
803
+ def cmd_lov(a, cfg):
804
+ from astropy.time import Time
805
+
806
+ from . import lov
807
+ trk, obs = _obs(a.obs, a.trk)
808
+ arc = _arc(obs, cfg)
809
+ try:
810
+ ks = [int(x) for x in a.controls.split(",") if x.strip()]
811
+ except ValueError:
812
+ ks = [0]
813
+ if set(ks) - set(lov.CONTROLS):
814
+ raise BadInput(f"--controls: choose among {','.join(map(str, lov.CONTROLS))} (or '' for none)")
815
+ sig = cfg["orbit"]["sigma"]
816
+ R = lov.run(arc, {"nsc": lambda box, m0, m1: lov.nsc(box, m0, m1, sig)}, Time(a.start).mjd, Time(a.end).mjd,
817
+ [(o["mag"], o["band"]) for o in obs], controls=ks, site=cfg["site"], r_min=cfg["orbit"]["r_min"],
818
+ r_max=cfg["orbit"]["r_max"])
819
+ real = R["real"]
820
+ if real["status"] != "searched":
821
+ raise NoResult("no_bound_orbit", "no bound orbit fits these observations")
822
+ best = next(iter(real["results"]), None)
823
+ ctl = {str(k): dict(n_hits=c.get("n_hits"), n_strong=c.get("n_strong")) for k, c in R["controls"].items()}
824
+ verdict = ("strong" if R["clean"] else "strong_not_clean") if real["n_strong"] else "hit" if real["n_hits"] else "no_hit"
825
+ lv = real["lov"]
826
+ print(f"{trk}: LOV {lv['n_nodes']} nodes, a {lv['a_range'][0]:.0f}-{lv['a_range'][1]:.0f} AU; {real['stage_a'].get('n_cands', 0)} "
827
+ f"candidates, {real['n_hits']} hits, {real['n_strong']} strong; controls " +
828
+ (", ".join(f"k{k} {c['n_hits']}/{c['n_strong']}" for k, c in ctl.items()) or "not run"))
829
+ if best and best["hit"]:
830
+ print(f" best: {best['new_nights']} new nights {best['new_season_nights']}, rms {best['rms']:.3f}\", "
831
+ f"a {best['elements']['a']:.1f} AU e {best['elements']['e']:.3f} i {best['elements']['i']:.2f} deg")
832
+ for y, s in (R.get("loso") or {}).items():
833
+ print(f" without season {y}: " + (f"offsets {', '.join(f'{d:.2f}' for d in s['offsets'])}\" (s68 {max(s['s68']):.2f}\") "
834
+ f"{'passed' if s['passed'] else 'FAILED'}" if s["passed"] is not None else s["why"]))
835
+ print(f"verdict {verdict}")
836
+ summary = dict(verdict=verdict, trk=trk, lov=lv, H=real["H"], stage_a={k: v for k, v in real["stage_a"].items()},
837
+ n_hits=real["n_hits"], n_strong=real["n_strong"], controls=ctl, clean=R["clean"],
838
+ best=best and {k: best[k] for k in ("hit", "strong", "new_nights", "nights", "new_season_nights", "rms", "elements")},
839
+ loso=R.get("loso"), rules=lov.RULES)
840
+ V = None
841
+ if a.verify and best and best["hit"]:
842
+ V = lov.verify(arc, best["points"], _lov_cutouts, cfg["orbit"]["r_min"], cfg["orbit"]["r_max"], state=(best["x"], best["v"]))
843
+ print(f" images: {V['verified']} of {len(V['points'])} points verified, {V['failed']} failed (network or calibration: "
844
+ f"re-run), new-season nights {V['new_season_nights']} -> {'confirmed' if V['confirmed'] else 'not confirmed'}")
845
+ summary["verify"] = dict({k: V[k] for k in ("verified", "failed", "new_season_nights", "confirmed")},
846
+ points=[{k: q.get(k) for k in ("exposure", "night", "season", "status", "loo_ok", "img_ok", "error")}
847
+ for q in V["points"]])
848
+ V = dict(V, orbit=V["orbit"] and _odict(V["orbit"]))
849
+ summary["complete"] = not V["failed"] # a re-run measures the failed frames again
850
+ _dump(dict(trk=trk, orbit=_odict(real["orbit"]), real=_lov_result(real),
851
+ controls={str(k): _lov_result(c) for k, c in R["controls"].items()}, loso=R.get("loso"), verify=V, summary=summary), a.out, a)
852
+ return summary
853
+
854
+
855
+ def _lov_cutouts(p):
856
+ """Cutouts of a hit point for ``lov.verify``: its DECam CCD from the NOIRLab archive (``archives.noirlab``: net.fetch
857
+ throttling, retries and time limits; CCD lists and cuts cached), around the catalogue row and the prediction."""
858
+ from .archives import cache, noirlab
859
+ if not p["exposure"].startswith("c4d_"):
860
+ return []
861
+ A, D = np.array([p["ra"], p["pred_ra"]]), np.array([p["dec"], p["pred_dec"]])
862
+ e = dict(archive="noirlab", inst="DECam", id=p["exposure"][:17], mjd=p["mid"], exptime=0.0)
863
+ return noirlab.fetch(e, lambda m, site: (A, D), cache("cut", "x").parent)
864
+
865
+
866
+ def cmd_survey_sim(a, cfg):
867
+ """OrbitSift Archival Survey Simulator: a model population through the survey's selection (orbitsift.survey)."""
868
+ import csv
869
+ from . import survey
870
+ rows = list(csv.DictReader(open(a.model)))
871
+ if not rows:
872
+ raise BadInput(f"{a.model}: no rows")
873
+ need = ("a", "e", "inc", "node", "peri", "M", "epoch", "H")
874
+ miss = [k for k in need if k not in rows[0]]
875
+ if miss:
876
+ raise BadInput(f"{a.model}: missing columns {', '.join(miss)} (need {', '.join(need)}; optional frame helio|bary, colour_slope, amp)")
877
+ pop = {k: np.array([float(r[k]) for r in rows]) for k in need + tuple(k for k in ("colour_slope", "amp") if k in rows[0])}
878
+ pop["frame"] = rows[0].get("frame", "helio") or "helio"
879
+ sv = survey.Survey.load(a.data)
880
+ res = sv.simulate(pop, seed=a.seed)
881
+ pipes = list(res["p"])
882
+ with open(a.output, "w", newline="") as fh:
883
+ w = csv.writer(fh)
884
+ w.writerow(["index"] + [f"p_{p}" for p in pipes] + [f"found_{p}" for p in pipes] + (["p_any"] if "p_any" in res else []))
885
+ for i in range(len(rows)):
886
+ w.writerow([i] + [f"{res['p'][p][i]:.4f}" for p in pipes] + [int(res["found"][p][i]) for p in pipes] + ([f"{res['p_any'][i]:.4f}"] if "p_any" in res else []))
887
+ exp = {p: float(res["p"][p].sum()) for p in pipes}
888
+ sd = {p: float(np.sqrt((res["p"][p] * (1 - res["p"][p])).sum())) for p in pipes}
889
+ for p in pipes:
890
+ print(f"{p}: expected found {exp[p]:.1f} +- {sd[p]:.1f} of {len(rows)} (drawn {int(res['found'][p].sum())})")
891
+ return dict(verdict="done", n=len(rows), expected=exp, sd=sd, drawn={p: int(res["found"][p].sum()) for p in pipes},
892
+ expected_any=float(res["p_any"].sum()) if "p_any" in res else None, data=a.data, version=sv.man.get("version"))
893
+
894
+
895
+ def cmd_known_check(a, cfg):
896
+ from . import known
897
+ trk, obs = _obs(a.obs, a.trk)
898
+ arc = _arc(obs, cfg)
899
+ o = _fit(arc, cfg, quiet=True)
900
+ files = [known.mpc_file("Distant.txt", a.refresh)] + ([known.mpc_file("MPCORB.DAT.gz", a.refresh)] if a.mpcorb else [])
901
+ C = known.mpc_orbits(files)
902
+ sent = []
903
+ R = known.check(arc, C, o, obs_of=lambda d: sent.append(d) or known.get_obs(d, a.refresh), backend=a.backend, our_obs=obs,
904
+ rules=dict(known.CHECK, clones=a.clones))
905
+ pairs = [{k: v for k, v in p.items() if k != "k"} for p in R["pairs"]]
906
+ possible = [p["desig"] for p in pairs if "joint" in p and not p["match"]] if a.backend != "findorb" else [] # two-body cannot decide
907
+ verdict = f"known:{R['matches'][0]}" if R["matches"] else (
908
+ "undecided:" + (",".join(R["undecided"]) or "no_joint_fit") if R["status"] == "undecided" else
909
+ f"possible:{possible[0]}" if possible else "none_found")
910
+ print(f"{trk}: {R['n_orbits']} MPC orbits, {R['screened']} pairs screened, {sum(p['link']['linkable'] for p in pairs)} linkable, "
911
+ f"joint fits run {R['fits_run']}, converged {R['fits_converged']}, matches: {', '.join(R['matches']) or 'none'}")
912
+ print(f"verdict {verdict}")
913
+ cat = [dict(file=f.name, downloaded=time.strftime("%Y-%m-%d %H:%M", time.localtime(f.stat().st_mtime))) for f in files]
914
+ summary = dict(verdict=verdict, trk=trk, catalogue=cat, n_orbits=R["n_orbits"], screened=R["screened"], fits_run=R["fits_run"],
915
+ fits_converged=R["fits_converged"], undecided=R["undecided"], matches=R["matches"],
916
+ possible=possible, get_obs_sent=sent, backend=a.backend, pairs=pairs, rules=known.CHECK)
917
+ _dump(dict(trk=trk, orbit=_odict(o), summary=summary), a.out, a)
918
+ return summary
919
+
920
+
921
+ def cmd_extract(a, cfg):
922
+ from . import extract
923
+ for f in (a.image, a.mask):
924
+ if not Path(f).exists():
925
+ raise BadInput(f"{f}: no such file")
926
+ rows, meta = extract.extract(a.image, a.mask, keep_dq7=not a.mask_dq7)
927
+ meta = extract.summarize(rows, meta)
928
+ csv = str(Path(a.out).with_suffix("").with_suffix("")) + ".csv.gz" if a.out.endswith(".json") else a.out + ".csv.gz"
929
+ extract.write_csv(rows, csv)
930
+ f = lambda x, fmt: "-" if x is None else fmt.format(x)
931
+ print(f"{a.image}: {meta['n']} sources, 5-sigma depth {f(meta['depth5'], '{:.2f}')}, FWHM {f(meta['fwhm_med'], '{:.2f}')}\""
932
+ + ("" if np.isfinite(meta["zp"]) else " (no MAGZERO in the header: magnitudes are nan)") + f" -> {csv}")
933
+ summary = dict(verdict="extracted", catalogue=csv, image=a.image, mask=a.mask, **meta)
934
+ _dump(dict(summary=summary, columns=list(extract.COLUMNS)), a.out, a)
935
+ return summary
936
+
937
+
938
+ def cmd_blindcheck(a, cfg):
939
+ from . import blind
940
+ if a.compare:
941
+ if not a.notes:
942
+ raise BadInput("--compare needs --notes (the sealed notes of the blind pass)")
943
+ r = blind.compare(a.notes, a.compare, a.tol)
944
+ for t in r["tracks"][:5]:
945
+ print(f" {t['field']} {t['status']:5s} {t['utc_mean']}: mean offset {t['mean_dra']:+.2f}\" {t['mean_ddec']:+.2f}\""
946
+ f" (mean separation {t['mean_sep']:.2f}\", {t['n']} frames)")
947
+ print(f"{r['verdict']}: notes sha256 {r['notes_sha256'][:16]}... sealed {r['sealed_utc']}")
948
+ out = a.output or str(Path(a.notes).with_suffix("")) + "_compare.json"
949
+ _dump(dict(r), out)
950
+ return r
951
+ if not a.fields:
952
+ raise BadInput("blindcheck needs FIELD files or directories (or --compare EPHEM --notes NOTES)")
953
+ par = dict(vmin=a.vmin, vmax=a.vmax, step_px=a.step_px, snr=a.snr, inj_n=a.inject)
954
+ notes = blind.run(a.fields, par)
955
+ out = a.output or "blindcheck_notes.json"
956
+ h = blind.seal(notes, out)
957
+ for t in notes["tracks"]:
958
+ print(f" {t['field']} {t['utc_mean']} RA {t['ra']:.6f} Dec {t['dec']:+.6f} +-{t['sigma_ra']:.2f}\"/{t['sigma_dec']:.2f}\""
959
+ f" rate {t['rate_ra']:+.2f} {t['rate_dec']:+.2f} \"/h, {t['n_used']}/{t['n_frames']} frames, stack S/N {t['stack_snr']:.1f}")
960
+ print(f"wrote {out}, sealed: sha256 {h} (keep it; open the prediction only now)")
961
+ return dict(verdict="tracks" if notes["tracks"] else "no_tracks", notes=out, sha256=h, n_tracks=len(notes["tracks"]),
962
+ n_weak=len(notes["weak"]), fields=[dict(name=f["name"], completeness=f["completeness"]) for f in notes["fields"]])
963
+
964
+
965
+ def _mjd(date):
966
+ return float((np.datetime64(date) - np.datetime64("1858-11-17")) / np.timedelta64(1, "D"))
967
+
968
+
969
+ def _csv_rows(path):
970
+ import csv
971
+ import gzip
972
+ if not Path(path).exists():
973
+ raise BadInput(f"{path}: no such file")
974
+ with (gzip.open if str(path).endswith(".gz") else open)(path, "rt", newline="") as f:
975
+ return list(csv.DictReader(f))
976
+
977
+
978
+ def cmd_rubin(a, cfg):
979
+ from . import rubin
980
+ t = tiles.tile(*a.tile)
981
+ if (a.adql or not a.diasource) and not (a.start and a.end):
982
+ raise BadInput("--start and --end (UTC dates, YYYY-MM-DD) say which nights are wanted")
983
+ if a.adql:
984
+ q = rubin.adql(t["box"], _mjd(a.start), _mjd(a.end), a.release)
985
+ for k, v in q.items():
986
+ print(f"-- {k}, {a.release}: run it on the RSP TAP service yourself and save the answer as CSV\n{v}\n")
987
+ return dict(verdict="adql", tile=t["id"], release=a.release, queries=q, sent=False)
988
+ if a.diasource:
989
+ T, src = rubin.tile_rows(rubin.table(_csv_rows(a.diasource)), t), "rsp"
990
+ ex = rubin.ccdvisits(_csv_rows(a.detectors)) if a.detectors else rubin.exposures(T)
991
+ else:
992
+ T, src = rubin.alerts(t, a.start, a.end, a.broker), a.broker
993
+ ex = rubin.exposures(T)
994
+ rows = rubin.orphans(T, known=a.known, min_reliability=a.min_reliability)
995
+ f_rows, f_ex = rubin.write(a.outdir, t["id"], rows, ex)
996
+ nights = {int(np.floor(float(r["mjd"]) - 0.5)) for r in rows}
997
+ print(f"{t['id']} ({src}): {len(T['ra'])} DiaSources in the tile box, {len(rows)} single-night detections on {len(nights)} nights, "
998
+ f"{len(ex['name'])} detector exposures -> {f_rows}, {f_ex} (site {rubin.SITE})")
999
+ s = dict(verdict="written" if rows else "no_rows", tile=t["id"], source=src, sources=len(T["ra"]), detections=len(rows),
1000
+ nights=len(nights), exposures=len(ex["name"]), rows=str(f_rows), exposure_table=str(f_ex), site=rubin.SITE)
1001
+ _dump(dict(summary=s), a.out, a)
1002
+ return s
1003
+
1004
+
1005
+ def cmd_seeds(a, cfg):
1006
+ from . import multiyear
1007
+ for f in (a.rows, a.exposures):
1008
+ if not Path(f).exists():
1009
+ raise BadInput(f"{f}: no such file or directory")
1010
+ if any(v != int(v) for v in a.region) or a.region[0] >= a.region[1] or a.region[2] >= a.region[3]:
1011
+ raise BadInput("--region: whole degrees RA0 < RA1, DEC0 < DEC1")
1012
+ par = {}
1013
+ for kv in a.par or ():
1014
+ k, _, v = kv.partition("=")
1015
+ if k not in multiyear.dense.PAR:
1016
+ raise BadInput(f"--par {kv}: unknown seed parameter (see dense.PAR)")
1017
+ par[k] = float(v)
1018
+ site = multiyear.ctio if a.observer == "ctio" else (a.site or cfg.get("site") or "W84")
1019
+ try:
1020
+ multiyear.growth.control_seed(a.control)
1021
+ except ValueError as e:
1022
+ raise BadInput(f"--control: {e}") from None
1023
+ summ = multiyear.run(a.rows, a.exposures, tuple(int(v) for v in a.region), a.outdir, a.boxes, tuple(a.origin) if a.origin else None,
1024
+ site, a.catalogue, a.force, control=a.control, **par)
1025
+ if not summ["units"]:
1026
+ raise NoResult("no_tiles", f"no tile file of the region in {a.rows} (expected <tile>.csv.gz, e.g. 026+00.csv.gz)")
1027
+ print(f"{summ['units']} seed tables ({summ['computed']} computed, {summ['seeds']} seeds) -> {a.outdir}"
1028
+ + (f"; tile files missing: {', '.join(summ['missing_tiles'])}" if summ["missing_tiles"] else ""))
1029
+ res = dict(verdict="seeded", outdir=a.outdir, observer=a.observer, control=a.control or "real", par=par, **summ)
1030
+ _dump(res, a.out, a)
1031
+ return res
1032
+
1033
+
1034
+ def cmd_grow(a, cfg):
1035
+ from . import growth, multiyear
1036
+ for f in [*a.seeds, *a.catalogue, a.kernel]:
1037
+ if not Path(f).exists():
1038
+ raise BadInput(f"{f}: no such file or directory")
1039
+ try:
1040
+ growth.control_seed(a.control)
1041
+ pre = growth.preset(a.preset) if a.preset else None
1042
+ except ValueError as e:
1043
+ raise BadInput(str(e)) from None
1044
+ par = dict(pre["rule"]["growth"], **{k: pre["rule"]["final"][k] for k in growth.FINAL}) if pre else {}
1045
+ for kv in a.par or ():
1046
+ k, _, v = kv.partition("=")
1047
+ if k not in growth.PAR and k not in growth.FINAL:
1048
+ raise BadInput(f"--par {kv}: unknown growth parameter (see growth.PAR, growth.FINAL)")
1049
+ par[k] = float(v)
1050
+ tables = multiyear.seed_tables(*a.seeds)
1051
+ if not tables:
1052
+ raise NoResult("no_seeds", f"no seed table in {', '.join(a.seeds)} (expected tiles/*.npz, b20/*.npz ... from 'orbitsift seeds')")
1053
+ modes = {t["stat"].get("control", "real") for _, t in tables}
1054
+ if modes != {a.control or "real"}:
1055
+ raise BadInput(f"seed tables of mode {sorted(modes)} but --control {a.control or 'real'}: seed the control with 'seeds --control'")
1056
+ cat = multiyear.join_catalogues([dict(np.load(f)) for f in a.catalogue])
1057
+ t0 = time.time()
1058
+ res = growth.grow(cat, [t for _, t in tables], growth.earth_table(a.kernel), par, a.control, a.threads)
1059
+ n = len(res["cands"])
1060
+ print(f"{len(tables)} seed tables, {res['nseeds']} seeds ({res['missing']} with a row not in the catalogue), "
1061
+ f"{len(cat['key'])} catalogue rows: {res['nraw']} sets, {n} candidates after the final rule ({time.time() - t0:.0f} s)")
1062
+ res.update(verdict="grown" if n else "no_candidates", preset=pre and dict(name=pre["name"], rule_sha256=pre["rule_sha256"]),
1063
+ seeds=a.seeds, catalogue=a.catalogue, tables=len(tables))
1064
+ _dump(res, a.output or f"cand_{a.control or 'real'}.json", a)
1065
+ return res
1066
+
1067
+
1068
+ def cmd_recover(a, cfg):
1069
+ from . import growth, known, multiyear, recover
1070
+ if a.self_test:
1071
+ if not a.kernel or not Path(a.kernel).exists():
1072
+ raise BadInput("--self-test needs --kernel (a DE440s .bsp)")
1073
+ rs = recover.selftest(growth.earth_table(a.kernel, *recover.EARTH_SPAN), a.threads)
1074
+ for r in rs:
1075
+ print(f"{r['mode']}: {r['rows']} rows, {r['sets']} sets, largest set {r['largest_ours']} catalogue rows "
1076
+ f"({r['largest_true']} true), most nights {r['max_nights']}, fit4 {r['fit4']}: {'OK' if r['ok'] else 'FAILED'}")
1077
+ res = dict(verdict="self_test_ok" if all(r["ok"] for r in rs) else "not_ok", runs=rs)
1078
+ _dump(res, a.output or "recover_selftest.json", a)
1079
+ return res
1080
+ if not a.designation and not a.astrometry:
1081
+ raise BadInput("give a designation (its published rows come from MPC get-obs) or --astrometry FILE")
1082
+ rows = json.load(open(a.astrometry)) if a.astrometry else known.get_obs(a.designation)
1083
+ o = recover.published(rows)
1084
+ key = a.designation or Path(a.astrometry).stem
1085
+ if len(o["mjd"]) < 4 or len(set(np.floor(o["mjd"] - 0.5))) < 2:
1086
+ raise NoResult("not_searchable", f"{key}: {len(o['mjd'])} usable published rows; a seed needs >= 4 rows on >= 2 nights")
1087
+ if a.plan:
1088
+ t = recover.corridor_tiles(o, a.plan[0], a.plan[1], a.margin)
1089
+ print(f"{len(t)} tiles within {a.margin} deg of the nominal track, MJD {a.plan[0]:.0f}-{a.plan[1]:.0f}: "
1090
+ + " ".join(multiyear.tile_name(x) for x in t))
1091
+ res = dict(verdict="planned", key=key, tiles=[multiyear.tile_name(x) for x in t], margin=a.margin, mjd=a.plan)
1092
+ _dump(res, a.output or f"recover_plan_{key.replace(' ', '_')}.json", a)
1093
+ return res
1094
+ for f in [*(a.catalogue or ()), a.kernel]:
1095
+ if not f or not Path(f).exists():
1096
+ raise BadInput(f"{f}: no such file or directory (--catalogue and --kernel are needed)")
1097
+ try:
1098
+ growth.control_seed(a.control)
1099
+ pre = recover.preset()
1100
+ except ValueError as e:
1101
+ raise BadInput(str(e)) from None
1102
+ par = dict(pre["rule"]["growth"])
1103
+ for kv in a.par or ():
1104
+ k, _, v = kv.partition("=")
1105
+ if k not in growth.PAR:
1106
+ raise BadInput(f"--par {kv}: unknown growth parameter (see growth.PAR)")
1107
+ par[k] = float(v)
1108
+ r, dl = recover.distances(o)
1109
+ s = recover.seed(o, r, dl, key=key, H=a.H)
1110
+ cat = multiyear.join_catalogues([dict(np.load(f)) for f in a.catalogue])
1111
+ t0 = time.time()
1112
+ res = recover.search(cat, [s], growth.earth_table(a.kernel, *recover.EARTH_SPAN), par, a.control, a.threads)
1113
+ dec = recover.decide(res, pre["rule"]["decision"])
1114
+ best = dec[0] if dec else None
1115
+ verdict = {"proposal": "recovered", "hint": "hint", "ambiguous": "ambiguous"}.get(best and best["kind"], "not_recovered")
1116
+ print(f"{key}: seed {s['nrows']} rows on {s['nights']} nights over {s['arc']:.1f} d; {len(cat['key'])} catalogue rows; "
1117
+ f"{len(res['sets'])} sets ({time.time() - t0:.1f} s): " + (f"{verdict}, {best['n']} catalogue nights, dchi {best['dchi']:.3f}, "
1118
+ f"P* {best['pstar']:.2e} ({best['T']} trials), r {best['r_au']:.2f} au" if best else verdict))
1119
+ out = dict(verdict=verdict, key=key, control=a.control or "real", preset=dict(name=pre["name"], rule_sha256=pre["rule_sha256"]),
1120
+ seed={k: s[k] for k in ("nrows", "nights", "arc", "t0", "t1", "V", "g0", "stn")}, decision=dec, sets=len(res["sets"]),
1121
+ stat=res["stat"], rows=res["rows"], catalogue=a.catalogue)
1122
+ if best and not a.control:
1123
+ out["orbit"] = recover.orbit_change(o, best["det"])
1124
+ b, f = out["orbit"]["before"], out["orbit"]["after"]
1125
+ if b and f:
1126
+ print(f"internal orbit: sigma(a) {b['sigma_a']:.4g} -> {f['sigma_a']:.4g} au, arc {b['arc_days']} -> {f['arc_days']} d, rms {f['rms']}\"")
1127
+ if (res["stat"].get("capskip") or res["stat"].get("capc")) and not best:
1128
+ print("note: some nights were skipped for the size of the corridor (stat capskip / capc)")
1129
+ _dump(out, a.output or f"recover_{key.replace(' ', '_')}_{a.control or 'real'}.json", a)
1130
+ return out
1131
+
1132
+
1133
+ def cmd_export(a, cfg):
1134
+ c = cfg["ades"]
1135
+ submitter = a.submitter or c["submitter"]
1136
+ observers = [x.strip() for x in a.observers.split(",")] if a.observers else c["observers"]
1137
+ measurers = [x.strip() for x in a.measurers.split(",")] if a.measurers else (c["measurers"] or None)
1138
+ doc = json.load(open(a.input))
1139
+ tel = dict(design=c["design"], aperture=c["aperture"], detector=c["detector"])
1140
+ blocks, tracks, pre = [], {}, []
1141
+ if "links" in doc:
1142
+ sel = [int(x) for x in a.links.split(",")] if a.links else [k for k, l in enumerate(doc["links"]) if l.get("vet", {}).get("survives")]
1143
+ if not sel:
1144
+ raise NoResult("no_links_to_export", "no surviving links to export (choose some with --links)")
1145
+ cat = ades.AST_CAT["nsc"]
1146
+ by_stn = {}
1147
+ if doc.get("tables"): # link --rows: the rows are the measurements, nothing is fetched
1148
+ from .multiyear import read_rows
1149
+ byid = {r["id"]: r for r in read_rows(doc["tables"]["rows"])}
1150
+ cat, stn, rows = a.astcat or "Gaia3", doc["site"], []
1151
+ for n, k in enumerate(sel, a.first):
1152
+ trk = f"{c['trksub_prefix']}{n:04d}"
1153
+ for r in (byid[i] for i in doc["links"][k]["ids"]):
1154
+ band, col = next((b, v) for b, v in catalog.MAG_COLUMNS.items() if r.get(v))
1155
+ num = lambda key, default: float(r[key]) if r.get(key) else default
1156
+ rows.append(ades.row(trk, num("mid", float(r["mjd"])), float(r["ra"]), float(r["dec"]), max(num("raerr", 0.1), 0.05),
1157
+ max(num("decerr", 0.1), 0.05), float(r[col]), num("magerr", 0.1), (r.get("band") or band).lower(), stn, cat))
1158
+ print(f"{trk} = link {k}")
1159
+ tracks[trk] = dict(link=k)
1160
+ comment = c["comment"] or [f"Positions and magnitudes from the detection table {Path(doc['tables']['rows']).name} "
1161
+ "(docs/RUBIN.md); obsTime = mid-exposure UTC."]
1162
+ blocks.append((ades.header(submitter, observers, measurers, stn, comment=comment,
1163
+ **dict(tel, aperture={"X05": 8.4}.get(stn, tel["aperture"]))), rows))
1164
+ sel = []
1165
+ for n, k in enumerate(sel, a.first):
1166
+ l = doc["links"][k]
1167
+ trk = f"{c['trksub_prefix']}{n:04d}"
1168
+ meas = catalog.measurements(l["ids"], a.allow_ids)
1169
+ et = catalog.exptimes([m["exposure"] for m in meas])
1170
+ for m in meas:
1171
+ stn = catalog.STATIONS.get(m["exposure"][:3], doc["site"])
1172
+ mid = float(m["mjd"]) + et[m["exposure"]] / 2 / 86400 # NSC mjd = exposure start
1173
+ by_stn.setdefault(stn, []).append(ades.row(
1174
+ trk, mid, float(m["ra"]), float(m["dec"]), max(float(m["raerr"]), 0.05), max(float(m["decerr"]), 0.05),
1175
+ float(m["mag_auto"]), float(m["magerr_auto"]), m["filter"].lower(), stn, cat))
1176
+ print(f"{trk} = link {k}")
1177
+ tracks[trk] = dict(link=k)
1178
+ inst = {"W84": "DECam (CTIO Blanco 4m)", "695": "Mosaic3 (Kitt Peak Mayall 4m)", "V00": "90Prime (Kitt Peak Bok 2.3m)"}
1179
+ for stn, rows in by_stn.items():
1180
+ comment = c["comment"] or [f"Archival {inst.get(stn, '')} images. Positions and magnitudes from the NOIRLab Source "
1181
+ "Catalog DR2 (Gaia DR2 astrometric reference); obsTime = mid-exposure UTC."]
1182
+ if stn != "W84" and not c["comment"]:
1183
+ tel = dict(tel, aperture={"695": 4.0, "V00": 2.3}.get(stn, tel["aperture"]))
1184
+ blocks.append((ades.header(submitter, observers, measurers, stn, comment=comment, **tel), rows))
1185
+ elif "measurements" in doc:
1186
+ acc = [m for m in doc["measurements"] if m.get("accepted")]
1187
+ if not acc:
1188
+ raise NoResult("no_measurements_to_export", "no accepted measurements (set \"accepted\": true on the ones to export)")
1189
+ cat = ades.AST_CAT["forced"]
1190
+ tracks[doc["trk"]] = dict(forced=len(acc))
1191
+ groups = {}
1192
+ for m in acc:
1193
+ obsr = tuple(observers) if observers else tuple(sorted({ades.initials(x) for x in (m.get("observer") or "").split(",") if x.strip()}))
1194
+ groups.setdefault(obsr, []).append(m)
1195
+ for obsr, ms in groups.items():
1196
+ props = sorted({str(m.get("propid")) for m in ms})
1197
+ comment = c["comment"] or [f"Archival DECam (CTIO Blanco 4m) images, NOIRLab programme(s) {', '.join(props)}.",
1198
+ "Positions from forced PSF centroids on DECam Community Pipeline images at positions "
1199
+ "predicted from the orbit, tied to Gaia DR3 stars; obsTime = mid-exposure UTC."]
1200
+ rows = [ades.row(doc["trk"], m["mid"], m["ra"], m["dec"], max(0.10, float(np.hypot(m["sx"], 0.05))),
1201
+ max(0.10, float(np.hypot(m["sy"], 0.05))), m["mag"], float(np.hypot(m["magerr"], 0.10)),
1202
+ m["filt"], cfg["site"], cat) for m in ms]
1203
+ blocks.append((ades.header(submitter, list(obsr), measurers, cfg["site"], comment=comment, **tel), rows))
1204
+ elif "points" in doc and "second_pass" in doc: # extend: its accepted points, minus those its own checks failed
1205
+ cat, trk = ades.AST_CAT["extend"], doc["trk"]
1206
+ sp = {(s["origin"], round(s["mid"], 6)): s["ok"] for s in doc["second_pass"]}
1207
+ loo = (doc.get("summary") or {}).get("leave_one_out") or {}
1208
+ by_inst, skipped = {}, []
1209
+ for p in doc["points"]:
1210
+ why = ("second forced pass failed" if sp.get((p["origin"], round(p["mid"], 6))) is False else
1211
+ "its night failed leave-one-night-out" if (loo.get(str(p["night"])) or {}).get("passed") is False else
1212
+ f"no MPC station for instrument {p['inst']!r} (ades.ARCHIVAL)" if p["inst"] not in ades.ARCHIVAL else None)
1213
+ if why:
1214
+ skipped.append(dict(origin=p["origin"], mid=p["mid"], why=why))
1215
+ pre.append(dict(code="point_skipped", trk=trk, message=f"{trk}: {p['origin']} not exported: {why}"))
1216
+ continue
1217
+ if p.get("static") == "untested":
1218
+ pre.append(dict(code="static_untested", trk=trk, message=f"{trk}: {p['origin']}: no other night covers its "
1219
+ "position, so the static-source test did not run; look at the image"))
1220
+ stn = ades.ARCHIVAL[p["inst"]][0]
1221
+ err = max(0.10, float(np.hypot(p["sig"], 0.05)))
1222
+ by_inst.setdefault(p["inst"], []).append((p, ades.row(trk, p["mid"], p["ra"], p["dec"], err, err, p["mag"],
1223
+ p["mag"] and float(np.hypot(1.0857 / p["snr"], 0.10)), "G", stn, cat)))
1224
+ if not by_inst:
1225
+ raise NoResult("no_points_to_export", f"no extend points to export ({len(skipped)} skipped)")
1226
+ verdict = (doc.get("summary") or {}).get("verdict", "")
1227
+ if verdict != "consistent":
1228
+ pre.append(dict(code="not_consistent", trk=trk, message=f"{trk}: the extend verdict is {verdict!r}, not 'consistent'"))
1229
+ tracks[trk] = dict(extend=sum(len(v) for v in by_inst.values()), skipped=skipped)
1230
+ for inst, prs in by_inst.items(): # one block per instrument (station and aperture)
1231
+ stn, ap, name = ades.ARCHIVAL[inst]
1232
+ comment = c["comment"] or [f"Archival {name} images ({', '.join(sorted({p['archive'] for p, _ in prs}))} archive).",
1233
+ "Positions from PSF fits on the stack-detected track (orbitsift extend), tied to Gaia DR3 "
1234
+ "stars; magnitudes Gaia G; obsTime = mid-exposure UTC."]
1235
+ blocks.append((ades.header(submitter, observers, measurers, stn, comment=comment, **dict(tel, aperture=ap)),
1236
+ [r for _, r in prs]))
1237
+ else:
1238
+ raise BadInput(f"{a.input}: not a vet, forced or extend output file")
1239
+ ades.write(a.output, blocks)
1240
+ print(f"wrote {a.output}: {sum(len(r) for _, r in blocks)} observations in {len(blocks)} block(s)")
1241
+ warnings = pre + ades.lint(a.output, cat)
1242
+ for w in warnings:
1243
+ print(f"warning: {w['message']}")
1244
+ answer = None
1245
+ if a.validate:
1246
+ answer = ades.validate(a.output, a.email or c["email"], a.obj_type)
1247
+ print(answer)
1248
+ print("Review the file before submitting it yourself (see README, 'Reporting to the MPC').")
1249
+ return dict(verdict="written", output=a.output, observations=sum(len(r) for _, r in blocks), blocks=len(blocks),
1250
+ tracks=tracks, astcat=cat, warnings=warnings, validation=answer, submitted=False)
1251
+
1252
+
1253
+ def cmd_run(a, cfg):
1254
+ out = Path(a.outdir)
1255
+ tid = tiles.tile(*a.tile)["id"]
1256
+ a.links = str(out / f"{tid}_links.json")
1257
+ doc = cmd_link(a, cfg, a.links)
1258
+ return cmd_vet(a, cfg, doc, str(out / f"{tid}_vet.json"))
1259
+
1260
+
1261
+ def cmd_plugins(a, cfg, core=()):
1262
+ rep = plugins.report()
1263
+ for r in rep:
1264
+ if r["group"] == "commands" and r["name"] in core and r["status"] == "ok":
1265
+ r.update(status="conflict", reason="a core command has this name")
1266
+ if not rep:
1267
+ print("no plugins installed (entry point groups: " + ", ".join(f"orbitsift.{g}" for g in plugins.GROUPS) + ")")
1268
+ for r in rep:
1269
+ print(f"{r['group']:9s} {r['name']:20s} {r['dist'] or '?'} {r['version'] or ''} {r['status']}"
1270
+ + (f": {r['reason']}" if r["reason"] else ""))
1271
+ return dict(verdict="listed", api_version=plugins.API_VERSION, groups=list(plugins.GROUPS), plugins=rep)
1272
+
1273
+
1274
+ def cmd_export_plugin(a, cfg):
1275
+ ex = plugins.get("exporters").get(a.format)
1276
+ if ex is None:
1277
+ raise BadInput(f"no working exporter plugin '{a.format}' (see orbitsift plugins; ADES is 'export-ades')")
1278
+ doc = json.load(open(a.input))
1279
+ res = dict(ex.export(doc, a.output, cfg) or {})
1280
+ res.setdefault("verdict", "written")
1281
+ res.setdefault("output", a.output)
1282
+ res["submitted"] = False
1283
+ print(f"wrote {a.output} ({a.format})")
1284
+ return res
1285
+
1286
+
1287
+ # ---- dry runs: what a command would fetch and compute ----
1288
+
1289
+ TAP_S = (20, 200) # one Data Lab TAP tile query [s]
1290
+ TILE_MB = 2.0 # gzipped single-night objects of a tile (0.5-10 MB)
1291
+ CCD_MB = 32.0
1292
+ IDENT_SERVICE = {"jpl": "jpl_sb_ident", "skybot": "imcce_skybot"}
1293
+
1294
+
1295
+ def _plan(items, compute, seconds=(0.0, 0.0), **extra):
1296
+ todo = [i for i in items if not i["cached"]]
1297
+ lo = seconds[0] + sum(i.get("s", (0, 0))[0] for i in todo)
1298
+ hi = seconds[1] + sum(i.get("s", (0, 0))[1] for i in todo)
1299
+ for i in items:
1300
+ i.pop("s", None)
1301
+ return dict(verdict="dry_run", fetch=items, queries=sum(i.get("n", 1) or 0 for i in todo),
1302
+ download_mb=round(sum(i.get("mb", 0) for i in todo), 1), est_seconds=[round(lo), round(hi)], compute=compute, **extra)
1303
+
1304
+
1305
+ def _tap_items(box, tag, t=None, blocks=1, near=False):
1306
+ if near or (blocks > 1 and t): # near / cross-tile: every tile of the data area, exposures around it
1307
+ ts, m = (_near_core(box, t)[2], 1.6 + NEAR_MARGIN) if near else (tiles.block(t, blocks), 1.6 + blocks // 2)
1308
+ box = _near_core(box, t)[0] if near else box
1309
+ return [dict(service="datalab_tap", what=f"single-night objects {x['id']}", cached=catalog.cache_path(catalog.orphans_name(
1310
+ x["box"])).exists(), mb=TILE_MB, s=TAP_S) for x in ts] + [
1311
+ dict(service="datalab_tap", what=f"DECam exposures around {tag} +{m - 1.6:g} deg", mb=0.5, s=(5, 60),
1312
+ cached=catalog.cache_path(catalog.exposures_name(box, m)).exists())]
1313
+ return [dict(service="datalab_tap", what=f"single-night objects {tag}", cached=catalog.cache_path(catalog.orphans_name(box)).exists(),
1314
+ mb=TILE_MB, s=TAP_S),
1315
+ dict(service="datalab_tap", what=f"DECam exposures around {tag}", cached=catalog.cache_path(catalog.exposures_name(box)).exists(),
1316
+ mb=0.2, s=(5, 60))]
1317
+
1318
+
1319
+ def _vet_items(a, cfg, n_det, n_links):
1320
+ items = []
1321
+ if not a.no_static:
1322
+ items.append(dict(service="datalab_tap", what="static check: 1 query per detection of links that pass the local "
1323
+ "vetoes (upper bound)", cached=False, n=n_det, s=(0.5 * n_det, 5 * n_det)))
1324
+ if a.ident:
1325
+ jpl = cfg["vet"]["ident_backend"] == "jpl"
1326
+ items.append(dict(service=IDENT_SERVICE[cfg["vet"]["ident_backend"]], what="known-object lookup per survivor (upper bound)",
1327
+ cached=False, n=n_links, s=(10 * n_links, 600 * n_links) if jpl else (2 * n_links, 30 * n_links)))
1328
+ return items
1329
+
1330
+
1331
+ def dry_fetch(a, cfg):
1332
+ box, _, tag = _region(a)
1333
+ return _plan(_tap_items(box, tag), "none")
1334
+
1335
+
1336
+ def dry_link(a, cfg):
1337
+ box, t, tag = _region(a)
1338
+ items = [] if getattr(a, "source", None) else _tap_items(box, tag, t, a.blocks, a.near)
1339
+ return _plan(items, "linking: 1-20 s per tile", (1, 20))
1340
+
1341
+
1342
+ def dry_run(a, cfg):
1343
+ box, t, tag = _region(a)
1344
+ items = _tap_items(box, tag, t, a.blocks, a.near) + [dict(service="datalab_tap", cached=False, n=None,
1345
+ what="static check: 1 query per detection of each link that passes the local "
1346
+ "vetoes (typically 0-40 per tile)")]
1347
+ if a.ident:
1348
+ items.append(dict(service=IDENT_SERVICE[cfg["vet"]["ident_backend"]], what="known-object lookup per survivor "
1349
+ "(typically 0-2)", cached=False, n=None))
1350
+ return _plan(items, "linking + local vetoes + Kepler test: 2-30 s", (2, 30))
1351
+
1352
+
1353
+ def dry_vet(a, cfg):
1354
+ doc = json.load(open(a.links))
1355
+ n_det = sum(len(l["det"]) for l in doc["links"])
1356
+ items = _tap_items(doc["box"], (doc.get("tile") or {}).get("id") or "box", doc.get("tile"), doc.get("blocks", 1),
1357
+ doc["params"].get("near", False)) + _vet_items(a, cfg, n_det, len(doc["links"]))
1358
+ return _plan(items, f"local vetoes and Kepler test on {len(doc['links'])} links: 1-10 s", (1, 10))
1359
+
1360
+
1361
+ def dry_fit(a, cfg):
1362
+ trk, obs = _obs(a.obs, a.trk)
1363
+ return _plan([], f"orbit fit of {len(obs)} observations of {trk}" + (f" + {a.samples} samples" if a.samples else "")
1364
+ + ": 1-30 s, no network", (1, 30))
1365
+
1366
+
1367
+ def _cloud(a, cfg):
1368
+ from . import orbit
1369
+ trk, obs = _obs(a.obs, a.trk)
1370
+ arc = _arc(obs, cfg)
1371
+ o = _fit(arc, cfg, quiet=True)
1372
+ return trk, obs, arc, o, orbit.sample(arc, o, a.samples)
1373
+
1374
+
1375
+ def dry_precover(a, cfg):
1376
+ from . import precovery
1377
+ trk, obs, arc, o, S = _cloud(a, cfg)
1378
+ box = precovery.track_box(S, arc.t0, site=cfg["site"])
1379
+ name = catalog.exposures_name(box, 0.0)
1380
+ items = [dict(service="datalab_tap", what="DECam exposures along the track", cached=catalog.cache_path(name).exists(),
1381
+ mb=1.0, s=(10, 120))]
1382
+ if not items[0]["cached"]:
1383
+ items.append(dict(service="datalab_tap", what=f"up to {a.max_tiles} catalogue tiles in the orbit cloud (known after "
1384
+ "the exposure query)", cached=False, n=a.max_tiles, mb=TILE_MB * a.max_tiles,
1385
+ s=(TAP_S[0] * a.max_tiles, TAP_S[1] * a.max_tiles)))
1386
+ return _plan(items, "orbit fit and samples (done), cloud search: seconds", (1, 30), trk=trk)
1387
+ P = precovery.plan(arc, S, _mags(obs), cfg["site"], cfg["precovery"]["min_p"], ex=catalog.exposures(box, margin=0.0))
1388
+ for t, w in P["todo"][:a.max_tiles]:
1389
+ items.append(dict(service="datalab_tap", what=f"tile {t['id']} (expected detections {w:.2f})",
1390
+ cached=catalog.cache_path(catalog.orphans_name(t["box"])).exists(), mb=TILE_MB, s=TAP_S))
1391
+ return _plan(items, f"{len(P['sel'])} exposures searched, refits of the candidates: 1-60 s", (1, 60), trk=trk,
1392
+ tiles_in_cloud=len(P["todo"]), expected_detections=float(P["p"][P["sel"]].sum()))
1393
+
1394
+
1395
+ def dry_forced(a, cfg):
1396
+ from astropy.time import Time
1397
+
1398
+ from . import images
1399
+ trk, obs, arc, o, S = _cloud(a, cfg)
1400
+ f = cfg["forced"]
1401
+ start, end = Time(a.start or f["start"]).mjd, Time(_forced_end(a, cfg)).mjd
1402
+ Q = images.target_queries(S, o.t0, start, end, a.max_ext or f["max_ext"], cfg["site"])
1403
+ items = [dict(service="noirlab_archive", what=f"CCD search around {Time(m, format='mjd').iso[:10]}",
1404
+ cached=images.archive_path(ra, dec, 0.6).exists(), mb=1.0, s=(5, 120)) for m, ra, dec in Q]
1405
+ extra = dict(trk=trk, archive_searches=len(Q))
1406
+ if all(i["cached"] for i in items):
1407
+ T = images.ccd_targets(S, o.t0, start, end, a.max_ext or f["max_ext"], cfg["site"])
1408
+ ddir = Path(a.download_dir) if a.download_dir else config.cache_dir() / "ccd"
1409
+ for h in T:
1410
+ items.append(dict(service="noirlab_archive", what=f"CCD {h['archive_filename'].split('/')[-1]} hdu {h['hdu_idx']}",
1411
+ cached=images.ccd_path(h, ddir).exists(), mb=CCD_MB, s=(5, 60)))
1412
+ n_gaia = math.ceil(len(T) / 40)
1413
+ items.append(dict(service="gaia_tap", what="Gaia DR3 stars of the CCDs", cached=not T, n=n_gaia, s=(30 * n_gaia, 300 * n_gaia)))
1414
+ extra["ccds"] = len(T)
1415
+ else:
1416
+ extra["ccds"] = None # known after the archive searches
1417
+ return _plan(items, "orbit fit and samples (done), forced photometry: ~1 s per CCD", (1, 10), **extra)
1418
+
1419
+
1420
+ def dry_extend(a, cfg):
1421
+ from . import archives, extend
1422
+ trk, obs, arc, o, S = _cloud(a, cfg)
1423
+ epoch, els = extend.clone_elements(S, o.t0, a.ssois_clones)
1424
+ end = a.end or str(np.datetime64("today"))
1425
+ note = "" if a.allow_ssois else " (sends the elements: refused without --allow-ssois)"
1426
+ items = [] if a.exposures else [dict(service="cadc_ssois", what=f"SSOIS orbel search, clone {k} (elements only){note}",
1427
+ cached=archives.ssois_query(el, epoch, a.start, end)[1].exists(), s=(20, 120))
1428
+ for k, el in enumerate(els)]
1429
+ items.append(dict(service="archives", what=f"images of up to {a.max_exposures} exposures per iteration (known after the "
1430
+ f"{'local exposure tables' if a.exposures else 'SSOIS search'}; CCDs and files by ID, CADC/PS1 cutouts "
1431
+ "only with --allow-cutouts)", cached=False, n=None))
1432
+ return _plan(items, f"{a.samples} clones, stack + PSF fits: ~2 s per CCD, up to {a.max_iter} iterations", (10, 60), trk=trk)
1433
+
1434
+
1435
+ def dry_libration(a, cfg):
1436
+ n = a.clones + 1
1437
+ s = a.kyr * (0.24 + 0.027 * n) # measured on a laptop core, DOP853 rtol 1e-10
1438
+ return _plan([], f"N-body integration of {n} particles for {a.kyr:g} kyr, no network", (0.5 * s, 3 * s))
1439
+
1440
+
1441
+ def dry_seeds(a, cfg):
1442
+ return _plan([], "local tile files and exposure table only: load, reduce, seed every tile and box; no network", (5, 3600))
1443
+
1444
+
1445
+ def dry_itf(a, cfg):
1446
+ return _plan([], "parse the ITF once (minutes), then the clone cloud against every tracklet; no network", (10, 600))
1447
+
1448
+
1449
+ def dry_unused(a, cfg):
1450
+ return _plan([dict(service="datalab_tap", what="DECam exposure tables along the track (cached per tile)", cached=False, mb=0.2, s=(5, 60)),
1451
+ dict(service="noirlab_archive", what=f"up to {a.max_exposures} CCDs, cut and kept small", cached=False,
1452
+ n=a.max_exposures, mb=CCD_MB * a.max_exposures, s=(30 * a.max_exposures, 120 * a.max_exposures))],
1453
+ "forced S/N at the prediction and 32 controls per exposure", (1, 60))
1454
+
1455
+
1456
+ def dry_identify(a, cfg):
1457
+ return _plan([dict(service="jpl_sbdb", what="SBDB TNO + Centaur orbits (once, cached)", cached=False, mb=3, s=(5, 60)),
1458
+ dict(service="jpl_sb_ident", what="forward check, second pass", cached=False, s=(10, 600))],
1459
+ f"{a.clones + 1} orbits against ~9400 SBDB orbits", (5, 30))
1460
+
1461
+
1462
+ def dry_lov(a, cfg):
1463
+ from astropy.time import Time
1464
+
1465
+ from . import lov
1466
+ trk, obs = _obs(a.obs, a.trk)
1467
+ arc = _arc(obs, cfg)
1468
+ o = _fit(arc, cfg, quiet=True)
1469
+ T = lov._tiles(lov.LOV(arc, o), Time(a.start).mjd, Time(a.end).mjd, cfg["site"])
1470
+ items = []
1471
+ for t in T.values():
1472
+ items += [dict(service="datalab_tap", what=f"single-night objects {t['id']}", mb=TILE_MB, s=TAP_S,
1473
+ cached=catalog.cache_path(catalog.orphans_name(t["box"])).exists()),
1474
+ dict(service="datalab_tap", what=f"DECam exposures around {t['id']}", mb=0.2, s=(5, 60),
1475
+ cached=catalog.cache_path(catalog.exposures_name(t["box"])).exists())]
1476
+ n = len([k for k in a.controls.split(",") if k.strip()])
1477
+ if n:
1478
+ items.append(dict(service="datalab_tap", what=f"tiles of {n} control(s), 3-6 deg away (about as many per control)",
1479
+ cached=False, n=None))
1480
+ if a.verify:
1481
+ items.append(dict(service="noirlab_archive", what="CCD search and download (~32 MB) per point of the best hit, if any; "
1482
+ "Gaia DR3 and LS DR10 of each cutout", cached=False, n=None, s=(10, 120)))
1483
+ return _plan(items, f"LOV of {trk} ({len(T)} tiles), stage A/B on the real arc and {n} control(s): seconds to minutes",
1484
+ (5, 300), trk=trk, tiles=len(T))
1485
+
1486
+
1487
+ def dry_known_check(a, cfg):
1488
+ from . import config
1489
+ trk, _ = _obs(a.obs, a.trk)
1490
+ fresh = lambda n: not a.refresh and (config.cache_dir() / "known" / n).exists() and \
1491
+ time.time() - (config.cache_dir() / "known" / n).stat().st_mtime < 86400
1492
+ items = [dict(service="mpc", what="Distant.txt (bulk orbits, once a day)", cached=fresh("Distant.txt"), mb=2, s=(2, 30))]
1493
+ if a.mpcorb:
1494
+ items.append(dict(service="mpc", what="MPCORB.DAT.gz (bulk orbits, once a day)", cached=fresh("MPCORB.DAT.gz"), mb=80, s=(30, 600)))
1495
+ items.append(dict(service="mpc_get_obs", what="published astrometry by designation, one per screened pair",
1496
+ cached=False, n=None, s=(2, 60)))
1497
+ return _plan(items, f"orbit fit of {trk}, screen of every MPC orbit at its own dates, local linkage: seconds; nothing about "
1498
+ "the object is sent", (2, 30), trk=trk)
1499
+
1500
+
1501
+ def dry_rubin(a, cfg):
1502
+ from . import rubin
1503
+ t = tiles.tile(*a.tile)
1504
+ if a.adql or a.diasource:
1505
+ return _plan([], "the ADQL text, nothing is sent" if a.adql else "the saved RSP tables are converted, no network")
1506
+ hit = (config.cache_dir() / "rubin" / f"{a.broker}_{t['id']}_{a.start}_{a.end}.csv.gz").exists()
1507
+ return _plan([dict(service=a.broker, what=f"alerts within {rubin.CONE} deg of the centre of tile {t['id']}, first seen {a.start} "
1508
+ f"to {a.end}", cached=hit, mb=0.3, s=(5, 120)),
1509
+ dict(service=a.broker, what="every source of the tile's single-night objects that have several (their public "
1510
+ "ids, 100 per request; usually 1 request)", cached=hit, mb=0.01, s=(2, 60))],
1511
+ "the standard rows and the exposure table: seconds", (1, 5))
1512
+
1513
+
1514
+ def dry_extract(a, cfg):
1515
+ return _plan([], "source extraction: ~1 s per CCD, no network", (1, 120))
1516
+
1517
+
1518
+ def dry_classify(a, cfg):
1519
+ s = 0.32 * a.myr * (a.clones + 1) # measured: Pluto, 11 orbits, 2 Myr, 7 s on a laptop core
1520
+ return _plan([dict(service="naif", what="JPL DE440s kernel (once, <cache>/de440s.bsp)", cached=False, mb=32, s=(5, 60))],
1521
+ f"REBOUND run of {a.clones + 1} orbits for {a.myr:g} Myr and the class test", (0.5 * s, 5 * s))
1522
+
1523
+
1524
+ def dry_export(a, cfg):
1525
+ doc = json.load(open(a.input))
1526
+ items = []
1527
+ if "links" in doc and not doc.get("tables"):
1528
+ sel = [int(x) for x in a.links.split(",")] if a.links else [k for k, l in enumerate(doc["links"]) if l.get("vet", {}).get("survives")]
1529
+ n = sum(math.ceil(len(doc["links"][k]["ids"]) / 200) for k in sel)
1530
+ items.append(dict(service="datalab_tap", what=f"measurements and exposure times of {len(sel)} links" +
1531
+ ("" if a.allow_ids else " (names the links' NSC object ids: refused without --allow-ids)"), cached=False,
1532
+ n=2 * n, s=(5 * n, 60 * n)))
1533
+ if a.validate:
1534
+ items.append(dict(service="mpc_validator", what="validation only (nothing is submitted)", cached=False, s=(2, 60)))
1535
+ return _plan(items, f"write {a.output}", submitted=False)
1536
+
1537
+
1538
+ DRY = {"fetch": dry_fetch, "link": dry_link, "vet": dry_vet, "run": dry_run, "fit": dry_fit, "precover": dry_precover,
1539
+ "forced": dry_forced, "extend": dry_extend, "libration": dry_libration, "classify": dry_classify, "extract": dry_extract, "identify": dry_identify, "lov": dry_lov, "known-check": dry_known_check, "unused": dry_unused, "itf": dry_itf, "export-ades": dry_export,
1540
+ "seeds": dry_seeds, "rubin": dry_rubin}
1541
+
1542
+
1543
+ # ---- confirm: an independent image test of a candidate (confirm.py); exposures: local exposure tables (expindex.py) ----
1544
+ def _confirm_tracks(a):
1545
+ """-> {track: det} from an ADES PSV (V = mag - colour(band)) or a link file (--links K,...)."""
1546
+ from . import confirm as cf
1547
+ if a.links:
1548
+ doc = json.loads(Path(a.obs).read_text())
1549
+ L = {str(x.get("name", k)): x for k, x in enumerate(doc.get("links", doc) if isinstance(doc, dict) else doc)}
1550
+ want = a.links.split(",")
1551
+ miss = [k for k in want if k not in L]
1552
+ if miss:
1553
+ raise BadInput(f"{a.obs}: no link {', '.join(miss)}")
1554
+ return {k: L[k]["det"] for k in want}
1555
+ obs = ades.read(a.obs)
1556
+ if not a.all:
1557
+ trk, rows = _obs(a.obs, a.trk)
1558
+ obs = {trk: rows}
1559
+ col = cf.RULE["colour"]
1560
+ return {t: [[r["ra"], r["dec"], r["mjd"], (float(r["mag"]) - col.get(r.get("band") or "", 0.0)) if r.get("mag") not in (None, "") else None]
1561
+ for r in rows] for t, rows in obs.items()}
1562
+
1563
+
1564
+ def cmd_confirm(a, cfg, dry=False):
1565
+ from . import confirm as cf, expindex, images, known
1566
+ c = cfg["confirm"]
1567
+ if not net.contact():
1568
+ raise BadInput("confirm sends exposure ids to the archives: set [net] contact (or ORBITSIFT_CONTACT) first")
1569
+ paths = a.exposures or c["exposures"] or sorted(str(p) for p in (config.cache_dir() / "exposures").glob("*.csv.gz"))
1570
+ if not paths:
1571
+ raise BadInput("no exposure table: pass --exposures PATH or build one with 'orbitsift exposures build'")
1572
+ T = expindex.load(paths)
1573
+ keep = {"decam": "DECam", "cfht": "MegaCam", "hsc": "HSC"}
1574
+ want = [keep[x] for x in (a.archives or "decam,cfht,hsc").split(",")]
1575
+ T = {k: v[np.isin(T["inst"], want)] for k, v in T.items()}
1576
+ images.CCD_CACHE = c["ccd_cache"] or os.environ.get("ORBITSIFT_CCDCACHE") or str(config.cache_dir() / "ccdcache")
1577
+ net.settings["max_concurrent"] = max(1, min(int(a.streams or c["streams"]), int(cfg["net"]["max_concurrent"])))
1578
+ rule_over = dict(c["rule"])
1579
+ if a.max_exposures:
1580
+ rule_over["max_exposures"] = a.max_exposures
1581
+ mpc = None if dry else [known.mpc_file("Distant.txt", a.refresh)] + ([known.mpc_file("MPCORB.DAT.gz", a.refresh)] if a.mpcorb else [])
1582
+ out, rep = {}, None
1583
+ for trk, det in _confirm_tracks(a).items():
1584
+ try:
1585
+ rep = cf.run(det, T, trk, rule_over, a.twins if a.twins is not None else c["twins"], a.backend or c["backend"],
1586
+ a.registry or c["registry"] or None, mpc, dry_run=dry, bulk_ok=a.bulk_ok, bulk_ccds=c["bulk_ccds"])
1587
+ except ValueError as e:
1588
+ raise BadInput(str(e)) from None
1589
+ out[trk] = rep
1590
+ if dry:
1591
+ n = rep.get("plan", {})
1592
+ per = {}
1593
+ for x in n.get("exposures", []):
1594
+ per[x["inst"]] = per.get(x["inst"], 0) + 1
1595
+ print(f"{trk}: {len(n.get('exposures', []))} exposures planned ({', '.join(f'{k} {v}' for k, v in sorted(per.items())) or 'none'}; "
1596
+ f"{n.get('n_eligible_exp', 0)} eligible on {n.get('n_eligible_nights', 0)} nights), {n.get('search', 0)} for "
1597
+ f"search mode, {n.get('listed', 0)} listed for extend; at most {rep.get('ccds_at_most', 0)} CCDs to fetch "
1598
+ f"(HSC: SMOKA request files only); testable {n.get('testable')}")
1599
+ continue
1600
+ stem = a.output if a.output and not a.all else f"{trk}_confirm.json"
1601
+ _dump(rep, stem)
1602
+ new = [r for r in rep.get("rows_new", []) if r.get("ok")]
1603
+ if new:
1604
+ rows = [ades.row(trk[:8], r["mid"], r["ra"], r["dec"], r["sig"], r["sig"], None, None, r.get("band"), stn=r["site"],
1605
+ ast_cat="Gaia3") for r in new]
1606
+ ades.write(str(Path(stem).with_suffix(".psv")), [(["# version=2017"], rows)])
1607
+ hsc = [x for x in rep.get("plan", {}).get("exposures", []) if x["inst"] == "HSC"]
1608
+ if hsc: # HSC: request files for the user to send (nothing is sent here)
1609
+ from .archives import smoka
1610
+ st = cf.start(det, cf.RULE, T=T)
1611
+ pos = lambda mjd, site: cf.orbit.predict(st["S"][:50], st["t0"], [mjd], smoka.SITE)
1612
+ ex = [dict(id=x["exposure"], mjd=x["mid"] - x["exptime"] / 172800, exptime=x["exptime"], inst="HSC", date=x["date"],
1613
+ filt=x["band"]) for x in hsc]
1614
+ try:
1615
+ req = smoka.request(ex, lambda m, s_: tuple(v[:, 0] for v in pos(m, s_)))
1616
+ for k, txt in req.items():
1617
+ if txt:
1618
+ Path(f"{trk}_smoka_{k}.txt").write_text(txt)
1619
+ print(f"{trk}: {len(hsc)} HSC exposures -> {trk}_smoka_science.txt (send it to SMOKA yourself; nothing was sent)")
1620
+ except (ValueError, net.ServiceError) as e:
1621
+ print(f"{trk}: {len(hsc)} HSC exposures planned; no SMOKA request file ({e})")
1622
+ R = rep.get("rates", {})
1623
+ tw, kn = R.get("twins", {}), R.get("knowns", {})
1624
+ print(f"{trk}: {rep['verdict']} (tier {rep['tier']}" + (f"; failing: {', '.join(rep['failed'])}" if rep.get("failed") else "")
1625
+ + f"). {tw.get('this_run', [0, 0])[0]} of {tw.get('this_run', [0, 0])[1]} testable twins pass"
1626
+ + (f"; in validation {tw['preset'][0]} of {tw['preset'][1]} testable twins pass (95 % limit {100 * tw['upper95']:.1f} %) "
1627
+ f"and {kn['preset'][0]} of {kn['preset'][1]} testable known objects pass ({100 * kn['preset'][0] / kn['preset'][1]:.0f} %)"
1628
+ if "preset" in tw and isinstance(kn.get("preset"), list) else ""))
1629
+ if dry:
1630
+ n = sum(r.get("ccds_at_most", 0) for r in out.values())
1631
+ return dict(verdict="dry_run", tracks=out, fetch=[], queries=n, download_mb=32 * n, est_seconds=(2 * n, 30 * n),
1632
+ compute=f"{len(out)} track(s), at most {n} CCDs (about 32 MB and 2-30 s each)")
1633
+ if a.all:
1634
+ _dump(dict(tracks={k: dict(verdict=v["verdict"], tier=v["tier"]) for k, v in out.items()}), a.output or "confirm_batch.json")
1635
+ return dict(verdict="done", tracks={k: v["verdict"] for k, v in out.items()})
1636
+ return rep
1637
+
1638
+
1639
+ def cmd_exposures(a, cfg):
1640
+ from . import expindex
1641
+ if a.action == "status":
1642
+ paths = a.paths or sorted(str(p) for p in (config.cache_dir() / "exposures").glob("*.csv.gz"))
1643
+ for p in paths:
1644
+ T = expindex.read(p)
1645
+ m = T["mjd_mid"][np.isfinite(T["mjd_mid"])]
1646
+ print(f"{p}: {len(T['exposure'])} exposures, {', '.join(sorted(set(T['inst'].tolist())))}, MJD "
1647
+ f"{m.min():.0f}-{m.max():.0f}, measured depth {np.mean(T['depth_src'] == 'table'):.0%}" if len(m) else f"{p}: empty")
1648
+ return dict(verdict="done", tables=len(paths))
1649
+ if not a.archive:
1650
+ raise BadInput("exposures build needs --archive")
1651
+ return dict(verdict="done", table=str(expindex.build(a.archive, a.start, a.end, a.output)))
1652
+
1653
+
1654
+ def _confirm_parser(add, fitter):
1655
+ p = add("confirm", help="an independent image test of a candidate on exposures it was never found on, with controls",
1656
+ description="Orbit and 400 clones from the rows alone; the exposures of the local tables that hold it (decided "
1657
+ "here); forced photometry and a shift-and-stack on the unused ones with 8 local and 24 null tracks and shifted "
1658
+ "twins; the rows checked on their own images; joint refit, leave-one-opposition-out, the known-object check; a "
1659
+ "tiered verdict with the frozen thresholds of presets/confirm_v2.json. Only exposure and file ids leave the "
1660
+ "machine (strict outbound mode).")
1661
+ p.add_argument("obs", help="ADES PSV (rows at mid-exposure; NSC DR2 start times are moved to mid) or a link file with --links")
1662
+ p.add_argument("--trk", help="track id if the file holds several")
1663
+ p.add_argument("--all", action="store_true", help="every track of the PSV -> confirm_batch.json")
1664
+ p.add_argument("--links", help="link names of a link file (comma separated)")
1665
+ p.add_argument("--exposures", action="append", help="exposure table (repeatable; default [confirm] exposures, else "
1666
+ "<cache>/exposures/*.csv.gz)")
1667
+ p.add_argument("--archives", help="decam,cfht,hsc (default all three; HSC: SMOKA request files only)")
1668
+ p.add_argument("--registry", action="append", help="ADES PSV file or folder of your registered objects and candidates "
1669
+ "(repeatable; the duplicate check; without it full_bar cannot be reached)")
1670
+ p.add_argument("--twins", type=int, help="shifted twins per target (default 4)")
1671
+ p.add_argument("--max-exposures", type=int, help="unused exposures measured at most (default 12: the frozen rule)")
1672
+ p.add_argument("--streams", type=int, help="concurrent requests per host (default 1, at most [net] max_concurrent)")
1673
+ p.add_argument("--mpcorb", action="store_true", help="the known-object check also with MPCORB.DAT.gz (~80 MB)")
1674
+ p.add_argument("--refresh", action="store_true", help="download the MPC files again")
1675
+ p.add_argument("--bulk-ok", action="store_true", help="allow a plan above [confirm] bulk_ccds downloads (write to the archive first)")
1676
+ fitter(p)
1677
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_confirm.json)")
1678
+ p.set_defaults(fn=cmd_confirm)
1679
+ p = add("exposures", help="build or inspect the local exposure tables of confirm (date-range queries only)")
1680
+ p.add_argument("action", choices=("build", "status"))
1681
+ p.add_argument("paths", nargs="*", help="tables (status)")
1682
+ p.add_argument("--archive", choices=("decam-nsc", "decam", "cfht", "hsc"), help="the archive whose table to build")
1683
+ p.add_argument("--start", help="first date (YYYY-MM-DD)")
1684
+ p.add_argument("--end", help="last date (YYYY-MM-DD)")
1685
+ p.add_argument("-o", "--output", help="table path (default <cache>/exposures/<archive>.csv.gz)")
1686
+ p.set_defaults(fn=cmd_exposures)
1687
+
1688
+
1689
+ DRY["confirm"] = lambda a, cfg: cmd_confirm(a, cfg, dry=True)
1690
+
1691
+
1692
+ # ---- inputs key: an output whose stored key matches is up to date and is not recomputed ----
1693
+
1694
+ _NOKEY = {"json", "force", "dry_run", "config", "cache_dir", "output", "outdir", "download_dir", "obs", "links", "out", "key", "fn"}
1695
+
1696
+
1697
+ def _key(a, cfg):
1698
+ args = {k: v for k, v in vars(a).items() if k not in _NOKEY and not (k.endswith("backend") and v == "internal")}
1699
+ files = {k: hashlib.sha256(Path(getattr(a, k)).read_bytes()).hexdigest() for k in ("obs", "links", "diasource", "detectors")
1700
+ if getattr(a, k, None)}
1701
+ if a.cmd == "link" and getattr(a, "rows", None):
1702
+ files.update({k: hashlib.sha256(Path(f).read_bytes()).hexdigest() for k, f in (("rows", _rows_file(a)), ("exposures", a.exposures)) if f})
1703
+ if a.cmd == "forced":
1704
+ args["end"] = _forced_end(a, cfg)
1705
+ if a.cmd == "known-check": # the MPC files change every day: a result is up to date for that day
1706
+ args["day"] = str(np.datetime64("today"))
1707
+ cf = {k: v for k, v in cfg.items() if k not in ("cache_dir", "net")}
1708
+ plug = (plugins.fingerprint("vetters") if a.cmd in ("vet", "run") else [],
1709
+ plugins.fingerprint("sources") if getattr(a, "source", None) else [])
1710
+ blob = json.dumps([__version__, args, files, cf, plug], sort_keys=True, default=str)
1711
+ return hashlib.sha256(blob.encode()).hexdigest()[:20]
1712
+
1713
+
1714
+ def _out(a):
1715
+ c = a.cmd
1716
+ if c == "link":
1717
+ return a.output or f"{_region(a)[2]}_links.json"
1718
+ if c == "vet":
1719
+ return a.output or str(Path(a.links).with_name(Path(a.links).stem.replace("_links", "") + "_vet.json"))
1720
+ if c == "run":
1721
+ return str(Path(a.outdir) / f"{tiles.tile(*a.tile)['id']}_vet.json")
1722
+ if c in ("fit", "precover", "forced", "extend"):
1723
+ return a.output or f"{_obs(a.obs, a.trk)[0]}_{dict(fit='orbit', precover='precovery', forced='forced', extend='extend')[c]}.json"
1724
+ if c == "itf":
1725
+ return a.output or f"{_obs(a.obs, a.trk)[0]}_itf.json"
1726
+ if c == "unused":
1727
+ return a.output or f"{_obs(a.obs, a.trk)[0]}_unused.json"
1728
+ if c == "identify":
1729
+ return a.output or f"{_obs(a.obs, a.trk)[0]}_identify.json"
1730
+ if c == "known-check":
1731
+ return a.output or f"{_obs(a.obs, a.trk)[0]}_knowncheck.json"
1732
+ if c == "lov":
1733
+ return a.output or f"{_obs(a.obs, a.trk)[0]}_lov.json"
1734
+ if c == "extract":
1735
+ return a.output or Path(a.image).name.split(".")[0] + "_cat.json"
1736
+ if c == "seeds":
1737
+ return str(Path(a.outdir) / "seeds.json")
1738
+ if c == "rubin":
1739
+ return None if a.adql else str(Path(a.outdir) / f"{tiles.tile(*a.tile)['id']}_rubin.json")
1740
+ if c == "classify":
1741
+ return a.output or f"{_obs(a.obs, a.trk)[0]}_classes.json"
1742
+ if c == "libration":
1743
+ return a.output or f"{'elements' if a.elements else _obs(a.obs, a.trk)[0]}_libration.json"
1744
+ return None
1745
+
1746
+
1747
+ def _up_to_date(path, key):
1748
+ """The stored result of an output made from the same inputs, or None."""
1749
+ try:
1750
+ doc = json.loads(Path(path).read_text())
1751
+ except (OSError, ValueError):
1752
+ return None
1753
+ s = (doc.get("result") or doc.get("summary")) if doc.get("inputs", {}).get("key") == key else None
1754
+ return s if isinstance(s, dict) and s.get("complete", True) and "verdict" in s else None
1755
+
1756
+
1757
+ def _print_plan(p):
1758
+ for i in p["fetch"]:
1759
+ print(f" {'cached ' if i['cached'] else 'fetch '} {i['service']:16s} {i['what']}" + (" (count known after linking)" if "n" in i and i["n"] is None else f" (x{i['n']})" if i.get("n", 1) != 1 else ""))
1760
+ print(f"would make {p['queries']} queries, download ~{p['download_mb']} MB, take ~{p['est_seconds'][0]}-{p['est_seconds'][1]} s"
1761
+ f"; compute: {p['compute']}" + ("; output up to date, would skip" if p.get("would_skip") else ""))
1762
+
1763
+
1764
+ class _Parser(argparse.ArgumentParser):
1765
+ """Usage errors as a JSON document too when --json is on the command line (exit 2 either way)."""
1766
+ json_errors = False
1767
+
1768
+ def error(self, message):
1769
+ if self.json_errors:
1770
+ err = dict(kind="bad_input", message=f"{self.prog}: {message}")
1771
+ print(json.dumps(dict(schema=SCHEMA, command=None, orbitsift=__version__, ok=False, exit_code=EXIT["bad_input"],
1772
+ output=None, skipped=False, result=None, error=err)))
1773
+ super().error(message)
1774
+
1775
+
1776
+ def build_parser():
1777
+ ap = _Parser(prog="orbitsift", description="Find slow moving Solar System objects (TNOs, Neptune Trojans, "
1778
+ "distant planets) in NSC DR2 and archival DECam images.")
1779
+ ap.add_argument("--version", action="version", version=__version__)
1780
+ ap.add_argument("--config", help="TOML settings file (default: ./orbitsift.toml if present)")
1781
+ ap.add_argument("--cache-dir", help="where downloaded catalogue tiles, archive queries and CCDs are kept")
1782
+ ap.add_argument("--site", help="MPC observatory code of the images (default W84 = DECam)")
1783
+ ap.add_argument("--json", action="store_true", help="print one JSON result on stdout (human text goes to stderr)")
1784
+ common = _Parser(add_help=False)
1785
+ common.add_argument("--json", action="store_true", default=argparse.SUPPRESS,
1786
+ help="print one JSON result on stdout (human text goes to stderr)")
1787
+ common.add_argument("--dry-run", action="store_true", help="report what would be fetched and computed; do nothing")
1788
+ common.add_argument("--force", action="store_true", help="recompute even if the output is up to date")
1789
+ sub = ap.add_subparsers(dest="cmd", required=True, metavar="command")
1790
+ add = lambda name, **kw: sub.add_parser(name, parents=[common], **kw)
1791
+
1792
+ def region(p):
1793
+ g = p.add_mutually_exclusive_group(required=True)
1794
+ g.add_argument("--tile", nargs=2, type=float, metavar=("RA", "DEC"), help="the 1x1 deg tile containing RA, DEC")
1795
+ g.add_argument("--box", nargs=4, type=float, metavar=("RA0", "RA1", "DEC0", "DEC1"), help="any RA/Dec box [deg]")
1796
+ p.add_argument("--near", action="store_true", help="near mode: 8-35 AU, any direction of motion (Centaurs, Uranus "
1797
+ "Trojans, retrograde), seeds from the tile or box, data 2.5 deg around it; vet applies the near rules")
1798
+ p.add_argument("--blocks", type=int, default=1, metavar="N", help="cross-tile linking: link on the N x N tiles around "
1799
+ "--tile (N odd, e.g. 3) and keep the links centred in it; an object near 30 AU crosses a tile in a season")
1800
+
1801
+ def link_opts(p):
1802
+ p.add_argument("--mode", choices=sorted(MODES), default="tno", help="preset: tno 30-150 AU (default), mid 15-30 AU "
1803
+ "(seeds within 20 d), far 80-1500 AU (seeds within 120 d; vet keeps >= 5 nights, bound fit <= 0.3\"), "
1804
+ "multiyear 80-3000 AU in three passes with seeds within 120/250/600 d, extended over all years, "
1805
+ "dense 25-80 AU with the anchor linker for crowded tiles (exposure cap, clump mask; one tile)")
1806
+ p.add_argument("--dist", nargs=2, type=float, metavar=("MIN", "MAX"), help="distance range [AU] (default 30 150)")
1807
+ p.add_argument("--dtmax", type=float, help="max days between seed nights (default 40)")
1808
+ p.add_argument("--min-nights", type=int, help="min distinct nights in a link (default 4)")
1809
+
1810
+ def vet_opts(p):
1811
+ p.add_argument("--no-static", action="store_true", help="skip the per-detection static-source TAP queries")
1812
+ p.add_argument("--no-kepler", action="store_true", help="skip the two-body orbit test")
1813
+ p.add_argument("--ident", action="store_true", help="look up known objects (JPL sb_ident) for survivors")
1814
+
1815
+ def obs_opts(p, samples=1000):
1816
+ p.add_argument("obs", help="ADES PSV file with the observations")
1817
+ p.add_argument("--trk", help="track id (trkSub/provID/permID) if the file holds several")
1818
+ p.add_argument("--samples", type=int, default=samples, help=f"orbit uncertainty samples (default {samples})")
1819
+
1820
+ p = add("fetch", help="download and cache NSC DR2 single-night objects and exposures of a region")
1821
+ region(p)
1822
+ p.set_defaults(fn=cmd_fetch)
1823
+ p = add("link", help="link single-night objects across nights into candidate movers")
1824
+ region(p)
1825
+ link_opts(p)
1826
+ p.add_argument("--source", help="detections from a source plugin instead of NSC DR2 (see 'plugins')")
1827
+ p.add_argument("--rows", help="detections from a local table of standard rows instead of NSC DR2: a file, or a folder of "
1828
+ "<tile>.csv.gz (as 'rubin' writes; give the images' site with --site)")
1829
+ p.add_argument("--exposures", help="the exposure table of --rows (CSV), for --mode dense")
1830
+ p.add_argument("-o", "--output", help="output JSON (default <tile>_links.json)")
1831
+ p.set_defaults(fn=lambda a, cfg: cmd_link(a, cfg)["summary"])
1832
+ p = add("vet", help="apply the vetoes (missing nights, cosmic rays, trails, static, Kepler) to links")
1833
+ p.add_argument("links", help="output of 'link'")
1834
+ vet_opts(p)
1835
+ p.add_argument("-o", "--output", help="output JSON (default <tile>_vet.json)")
1836
+ p.set_defaults(fn=cmd_vet)
1837
+ fitter = lambda p, flag="--backend": p.add_argument(flag, choices=("internal", "findorb"), default="internal", help=(
1838
+ "orbit fitter: internal (default) or Find_Orb (external 'fo', see README)"))
1839
+ p = add("fit", help="fit a barycentric orbit to ADES observations")
1840
+ obs_opts(p, 0)
1841
+ p.add_argument("--backend", choices=("auto", "internal", "findorb"), default="auto", help=(
1842
+ "orbit fitter: auto (default: Find_Orb for arcs of >= [orbit] findorb_min_seasons seasons when installed, else internal with "
1843
+ "a warning), internal or "
1844
+ "Find_Orb (external 'fo', see README)"))
1845
+ p.add_argument("--unbound", action="store_true", help="parabolic and hyperbolic orbits too (comets); internal fitter")
1846
+ p.add_argument("--r-min", type=float, help="smallest barycentric distance of the grid [AU] (default [orbit] r_min, 15; ~1 is the floor)")
1847
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_orbit.json)")
1848
+ p.set_defaults(fn=cmd_fit)
1849
+ p = add("precover", help="search NSC DR2 for earlier/later detections of an object")
1850
+ obs_opts(p)
1851
+ p.add_argument("--max-tiles", type=int, default=40, help="max catalogue tiles to download (default 40)")
1852
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_precovery.json)")
1853
+ p.set_defaults(fn=cmd_precover)
1854
+ p = add("forced", help="forced PSF measurements on archival DECam CCDs at the predicted positions")
1855
+ obs_opts(p)
1856
+ p.add_argument("--max-ext", type=float, help="use dates when the 95%% position cloud is < 2 x this [arcsec] (default 13)")
1857
+ p.add_argument("--start", help="first date (default 2012-09-01)")
1858
+ p.add_argument("--end", help="last date (default today)")
1859
+ p.add_argument("--min-snr", type=float, help="S/N cut for 'accepted' (default 5)")
1860
+ fitter(p) # the refit with the accepted measurements (confirmation)
1861
+ p.add_argument("--measure", dest="measure_backend", choices=("internal", "photutils"), default="internal",
1862
+ help="forced PSF measurement: internal (default) or photutils (extra 'photutils', see README)")
1863
+ p.add_argument("--download-dir", help="where CCDs are stored (default <cache>/ccd)")
1864
+ p.add_argument("--plot", action="store_true", help="save a stamp montage (needs matplotlib)")
1865
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_forced.json)")
1866
+ p.set_defaults(fn=cmd_forced)
1867
+ p = add("extend", help="extend a short-arc orbit with images from several archives (SSOIS + shift-and-stack)",
1868
+ description="Extend a short arc with archival images: orbit clones -> CADC SSOIS 'orbel' search (only the clones' "
1869
+ "elements are sent) -> CCD cutouts from the archives -> shift-and-stack along the clones against 96 control tracks -> "
1870
+ "PSF fit per exposure and static test -> refit; repeated while the smaller cloud reaches new nights. Archives: cadc "
1871
+ "(CFHT MegaCam), noirlab (DECam; older Mosaic and 90Prime raw), eso (VST raw; VIMOS, WFI, EMMI raw), ps1 (Pan-STARRS1 "
1872
+ "warps, V <= 23.5), sdss (SDSS frames), ing (INT WFC), smoka (Subaru HSC: request mail bodies written for you, frames "
1873
+ "used once downloaded; an account is needed), listing (Gemini: listed with instructions, never downloaded). Confirmed = >= 2 new nights, refit rms <= 0.12\", consistent "
1874
+ "magnitudes, every point found again by a second forced pass at the final orbit; do the known-object check yourself.")
1875
+ obs_opts(p, 20000)
1876
+ from .archives import NAMES as archive_names
1877
+ p.add_argument("--archives", default=",".join(archive_names),
1878
+ help=f"comma-separated archives (default: all: {','.join(archive_names)})")
1879
+ p.add_argument("--start", default="2003-01-01", help="first date searched (default 2003-01-01)")
1880
+ p.add_argument("--end", help="last date searched (default today)")
1881
+ p.add_argument("--ssois-clones", type=int, default=24, help="orbit clones sent to SSOIS per iteration (default 24)")
1882
+ p.add_argument("--exposures", action="append", help="local exposure table (CSV; repeatable): exposures are selected here "
1883
+ "from predicted clone positions, nothing is sent (required unless --allow-ssois)")
1884
+ p.add_argument("--allow-ssois", action="store_true", help="send the clones' elements to SSOIS: DESIGNATED objects only")
1885
+ p.add_argument("--allow-cutouts", action="store_true", help="ask CADC/PS1 for cutouts around the clones (the box gives the "
1886
+ "position to ~2'): DESIGNATED objects only; without it leave cadc and ps1 out of --archives")
1887
+ p.add_argument("--max-ext", type=float, default=600.0, help="use exposures where the 95%% clone cloud is shorter than this [arcsec] (default 600)")
1888
+ p.add_argument("--max-exposures", type=int, default=40, help="exposures measured per iteration (default 40)")
1889
+ p.add_argument("--per-night", type=int, default=4, help="exposures per night and site per iteration (default 4)")
1890
+ p.add_argument("--max-iter", type=int, default=6, help="max iterations (default 6)")
1891
+ p.add_argument("--min-snr", type=float, default=5.0, help="S/N of an accepted point (default 5)")
1892
+ p.add_argument("--cloud", choices=("auto", "both"), default="auto", help="clones: 'auto' (ranging under 300 days, else the "
1893
+ "covariance) or 'both' (their union: either alone can miss an arc of a few nights extrapolated by years)")
1894
+ p.add_argument("--no-loo", dest="loo", action="store_false", help="skip leave-one-night-out (by default every new night "
1895
+ "is re-measured at an orbit fitted without it, against the 96 controls; output key leave_one_out). "
1896
+ "Without it the verdict cannot be 'consistent'")
1897
+ fitter(p) # the reported refit; the search loop uses the internal fitter
1898
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_extend.json)")
1899
+ p.set_defaults(fn=cmd_extend)
1900
+ p = add("libration", help="N-body test for Neptune-Trojan libration (orbit clones)")
1901
+ p.add_argument("obs", nargs="?", help="ADES PSV file (orbit is fitted, clones drawn from its uncertainty)")
1902
+ p.add_argument("--trk", help="track id if the file holds several")
1903
+ p.add_argument("--elements", nargs=6, type=float, metavar=("A", "E", "I", "NODE", "PERI", "M"),
1904
+ help="heliocentric ecliptic J2000 elements instead of observations [AU, deg]")
1905
+ p.add_argument("--epoch", type=float, help="epoch of --elements (JD TDB)")
1906
+ p.add_argument("--kyr", type=float, default=100.0, help="integration length [kyr] (default 100)")
1907
+ p.add_argument("--clones", type=int, default=20, help="clones besides the nominal orbit (default 20)")
1908
+ p.add_argument("--plot", action="store_true", help="save lambda_rel vs time (needs matplotlib)")
1909
+ p.add_argument("--backend", choices=("internal", "rebound"), default="internal",
1910
+ help="integrator: internal (DOP853, default) or REBOUND WHFast (extra 'rebound')")
1911
+ fitter(p, "--fit-backend")
1912
+ p.add_argument("-o", "--output", help="output JSON")
1913
+ p.set_defaults(fn=cmd_libration)
1914
+
1915
+ p = add("itf", help="the object's own unlinked tracklets in the MPC Isolated Tracklet File (a file you download)")
1916
+ p.add_argument("obs", help="ADES PSV file")
1917
+ p.add_argument("--itf", required=True, help="path of itf.txt.gz (MPC; about 1 GB; parsed once into an .npz next to it)")
1918
+ p.add_argument("--trk", help="track id if the file holds several")
1919
+ p.add_argument("--exclude", help="comma-separated ITF trkSubs to ignore (your own submissions are not independent)")
1920
+ p.add_argument("--samples", type=int, default=2000, help="orbit clones (default 2000)")
1921
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_itf.json)")
1922
+ p.set_defaults(fn=cmd_itf)
1923
+
1924
+ p = add("unused", help="the unused-exposure test: forced S/N at the predicted position on DECam exposures no fit used")
1925
+ p.add_argument("obs", help="ADES PSV file (every position you have: exposures they come from are excluded)")
1926
+ p.add_argument("--trk", help="track id if the file holds several")
1927
+ p.add_argument("--V", type=float, help="expected V (default: median magnitude of the observations + 0.3)")
1928
+ p.add_argument("--clones", type=int, default=400, help="orbit clones for the uncertainty (default 400)")
1929
+ p.add_argument("--start", default="2012-09-01", help="first date (default 2012-09-01)")
1930
+ p.add_argument("--end", default="2019-12-31", help="last date (default 2019-12-31: the NSC DR2 exposure table)")
1931
+ p.add_argument("--max-exposures", type=int, default=40, help="exposures measured at most (default 40; ~1 CCD download each)")
1932
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_unused.json)")
1933
+ p.set_defaults(fn=cmd_unused)
1934
+
1935
+ p = add("identify", help="known objects near the whole orbit cloud: inverse SBDB screen + forward check to a recent date")
1936
+ p.add_argument("obs", help="ADES PSV file")
1937
+ p.add_argument("--trk", help="track id if the file holds several")
1938
+ p.add_argument("--clones", type=int, default=50, help="orbit clones besides the nominal (default 50)")
1939
+ p.add_argument("--cloud", choices=("auto", "both"), default="both", help="clones: auto or both (ranging + covariance; default)")
1940
+ p.add_argument("--date", help="forward-check date (default today)")
1941
+ p.add_argument("--fwd-site", default="500", help="MPC site of the forward check (default 500, geocentre)")
1942
+ p.add_argument("--refresh", action="store_true", help="download the SBDB list again (recent discoveries)")
1943
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_identify.json)")
1944
+ p.set_defaults(fn=cmd_identify)
1945
+
1946
+ p = add("survey-sim", help="OrbitSift Archival Survey Simulator: which objects of a model population the survey would have found",
1947
+ description="Forward model of the selection of the OrbitSift Archival Survey (four characterised pipelines: NSC dense, NSC "
1948
+ "multi-year, d25 dense, d25 multi-year): positions at every archival exposure (two-body), chip geometry, the calibrated "
1949
+ "detection model, each pipeline's frozen geometric rule per unit, and the measured link probability. Reads a data directory "
1950
+ "(oass_v1/: exposures, models; no position of any undesignated object). Writes per object p_found and a draw per pipeline.")
1951
+ p.add_argument("model", help="CSV with a, e, inc, node, peri, M (deg), epoch (MJD TDB), H; optional frame (helio|bary), colour_slope, amp")
1952
+ p.add_argument("--data", required=True, help="the simulator data directory (oass_v1)")
1953
+ p.add_argument("--output", default="survey_sim.csv", help="per-object result CSV (default survey_sim.csv)")
1954
+ p.add_argument("--seed", type=int, default=1, help="random seed of the detection and link draws")
1955
+ p.set_defaults(fn=cmd_survey_sim)
1956
+
1957
+ p = add("known-check", help="designated objects that are this object: compared at THEIR observed dates, decided with their rows",
1958
+ description="Known-object check the right way round: our orbit (and clones) at each MPC object's own first/middle/last "
1959
+ "arc date against its MPC orbit there (Distant.txt; --mpcorb adds MPCORB objects with a > 5.5 AU), a local two-body "
1960
+ "linkage with 5 positions of its orbit, then its published astrometry (MPC get-obs, by designation only) in a joint "
1961
+ "fit: match = >= 90% of rows used, rms < 0.4\", every row < 1.5\". Catches designated objects with arcs of days to "
1962
+ "weeks that a cone at our epochs misses. Nothing about the object is sent anywhere. It cannot see orbits not yet "
1963
+ "published: run it again after the MPC's daily updates and before any submission.")
1964
+ p.add_argument("obs", help="ADES PSV file with the observations (best the whole arc)")
1965
+ p.add_argument("--trk", help="track id if the file holds several")
1966
+ p.add_argument("--clones", type=int, default=40, help="orbit clones for our uncertainty at their dates (default 40)")
1967
+ p.add_argument("--mpcorb", action="store_true", help="also MPCORB.DAT.gz (~80 MB) for objects with a > 5.5 AU not in Distant.txt")
1968
+ p.add_argument("--refresh", action="store_true", help="download the MPC files and published rows again")
1969
+ fitter(p) # the joint fit of the decisive test; the screen is internal
1970
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_knowncheck.json)")
1971
+ p.set_defaults(fn=cmd_known_check)
1972
+
1973
+ _confirm_parser(add, fitter)
1974
+
1975
+ p = add("lov", help="NSC DR2 detections of a short-arc object in other seasons, along its line of variations, with controls",
1976
+ description="Archive search along the line of variations: the LOV of the fit (dchi2 <= 16), its width from draws of "
1977
+ "the other five parameters, NSC DR2 single-night objects within that width and 0.8 mag of the predicted magnitude, "
1978
+ "groups refitted and grown (rms <= 0.2\", every point <= 0.6\"). Hit: >= 2 nights in one new season or >= 3 in "
1979
+ "all; strong: >= 3 over >= 2 new seasons or >= 4, magnitudes within 1.2 mag. The same for the arc rotated by "
1980
+ "+-3 and +-6 deg about the ecliptic pole (controls); leave-one-season-out on the best strong hit. A hit is a "
1981
+ "locator: measure its points on the images (lov.verify, forced) before using them.")
1982
+ p.add_argument("obs", help="ADES PSV file with the observations")
1983
+ p.add_argument("--trk", help="track id if the file holds several")
1984
+ p.add_argument("--start", default="2012-09-01", help="first date searched (default 2012-09-01)")
1985
+ p.add_argument("--end", default="2019-12-31", help="last date searched (default 2019-12-31: the end of NSC DR2)")
1986
+ p.add_argument("--controls", default="1,2,3,4", help="controls to run: 1,2,3,4 = rotations by +3,-3,+6,-6 deg "
1987
+ "(default all; '' none)")
1988
+ p.add_argument("--verify", action="store_true", help="measure the best hit's points on their DECam images (lov.verify; "
1989
+ "one NOIRLab CCD download, ~32 MB, per point)")
1990
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_lov.json)")
1991
+ p.set_defaults(fn=cmd_lov)
1992
+
1993
+ p = add("seeds", help="multi-year seeds: the dense anchor linker with DES-style windows on 1-deg tiles and 2-deg boxes "
1994
+ "of a region, from local NSC DR2 orphan tile files (docs/guide-multiyear.md)")
1995
+ p.add_argument("--rows", required=True, help="folder of orphan tile files <tile>.csv.gz (catalog.orphans columns; tile "
1996
+ "026+00 = RA 26-27, Dec 0-1, cut with a 0.15 deg margin, RA margin 0.15 / cos(dec + 0.5))")
1997
+ p.add_argument("--exposures", required=True, help="NSC DR2 exposure table, CSV(.gz): exposure, mjd, filter, exptime, ra, dec, depth95")
1998
+ p.add_argument("--region", nargs=4, type=float, required=True, metavar=("RA0", "RA1", "DEC0", "DEC1"), help="whole degrees")
1999
+ p.add_argument("--boxes", type=int, default=2, metavar="N", help="also seed N x N degree boxes, both lattice offsets (default 2; 0 = tiles only)")
2000
+ p.add_argument("--origin", nargs=2, type=int, metavar=("RA", "DEC"), help="a corner of the box lattice (default: the region's; "
2001
+ "the 2026 pilot used 0 -7)")
2002
+ p.add_argument("--observer", choices=("ctio", "site"), default="ctio", help="ctio: the survey's observer (default; reproduces its "
2003
+ "seeds); site: orbit.observer with --site (MPC parallax constants)")
2004
+ p.add_argument("--par", nargs="*", metavar="K=V", help="override seed windows (multiyear.WINDOWS / dense.PAR), e.g. dtmax=120 k=64")
2005
+ p.add_argument("--catalogue", action="store_true", help="also write the growth catalogue (loader rows + other orphan rows) as catalogue.npz")
2006
+ p.add_argument("--control", metavar="shiftN", help="seeds of a shift control: every night moved rigidly by 20-60\" per axis "
2007
+ "(random per night, seeded by N; growth.shift); use its own --outdir")
2008
+ p.add_argument("-o", "--outdir", default="seeds", help="output folder (default ./seeds)")
2009
+ p.set_defaults(fn=cmd_seeds)
2010
+
2011
+ p = add("grow", help="multi-year growth: grow the seeds of 'seeds' over all years of the catalogue, final rule, duplicate "
2012
+ "rule (docs/guide-multiyear.md); needs the native kernels")
2013
+ p.add_argument("--seeds", nargs="+", required=True, metavar="DIR", help="output folder(s) of 'seeds' (tiles/, b20/, b21/)")
2014
+ p.add_argument("--catalogue", nargs="+", required=True, metavar="NPZ", help="catalogue.npz of 'seeds --catalogue' (one per region)")
2015
+ p.add_argument("--kernel", required=True, help="JPL DE440s kernel (de440s.bsp): the Earth's position")
2016
+ p.add_argument("--preset", choices=("a2",), help="a frozen rule (a2: the 2026 survey's, presets/a2.json); without it the "
2017
+ "pilot's start values (growth.PAR)")
2018
+ p.add_argument("--control", metavar="shiftN", help="a shift control: the catalogue is shifted as the seeds were "
2019
+ "(seeds --control shiftN)")
2020
+ p.add_argument("--par", nargs="*", metavar="K=V", help="override growth parameters (growth.PAR, FINAL), e.g. maxc=3000 fchi=2")
2021
+ p.add_argument("--threads", type=int, default=4, help="threads of the kernel (default 4; results do not depend on it)")
2022
+ p.add_argument("-o", "--output", help="output JSON (default cand_<real|shiftN>.json)")
2023
+ p.set_defaults(fn=cmd_grow)
2024
+
2025
+ p = add("recover", help="seeded recovery: the published astrometry of one designated object grown over the multi-year "
2026
+ "catalogue with the frozen rule of the survey (docs/guide-recover.md); needs the native kernels")
2027
+ p.add_argument("designation", nargs="?", help="designation (its published rows come from MPC get-obs: only the designation is sent)")
2028
+ p.add_argument("--astrometry", metavar="JSON", help="published rows as a local file (get-obs ADES_DF JSON) instead of get-obs")
2029
+ p.add_argument("--catalogue", nargs="+", metavar="NPZ", help="catalogue.npz of 'seeds --catalogue' covering the corridor")
2030
+ p.add_argument("--kernel", help="JPL DE440s kernel (de440s.bsp): the Earth's position")
2031
+ p.add_argument("--control", metavar="shiftN", help="a shift control: the catalogue rows are moved (20-60\" per night), the seed is not")
2032
+ p.add_argument("--H", type=float, help="absolute magnitude, used only if no published row has a magnitude")
2033
+ p.add_argument("--par", nargs="*", metavar="K=V", help="override growth parameters of the frozen rule (results are then not the rule's)")
2034
+ p.add_argument("--plan", nargs=2, type=float, metavar=("MJD0", "MJD1"), help="only list the tiles within --margin of the nominal "
2035
+ "track between two dates (what the catalogue must cover)")
2036
+ p.add_argument("--margin", type=float, default=0.5, help="deg around the nominal track for --plan (default 0.5)")
2037
+ p.add_argument("--self-test", action="store_true", help="the survey's self-check (synthetic object, real + shift control); needs --kernel")
2038
+ p.add_argument("--threads", type=int, default=4, help="threads of the kernel (default 4; results do not depend on it)")
2039
+ p.add_argument("-o", "--output", help="output JSON (default recover_<designation>_<real|shiftN>.json)")
2040
+ p.set_defaults(fn=cmd_recover)
2041
+
2042
+ p = add("rubin", help="Rubin Observatory detections as standard tables: public alerts from a broker, or saved RSP tables")
2043
+ p.add_argument("--tile", nargs=2, type=float, required=True, metavar=("RA", "DEC"), help="the 1x1 deg tile containing RA, DEC")
2044
+ p.add_argument("--start", help="first UTC date (YYYY-MM-DD) of the diaObjects' first detection")
2045
+ p.add_argument("--end", help="last UTC date")
2046
+ p.add_argument("--broker", default="fink", help="alert broker (default fink: public REST service, no account)")
2047
+ p.add_argument("--adql", action="store_true", help="only print the two ADQL queries for the Rubin Science Platform (you run "
2048
+ "them with your own data rights; nothing is sent)")
2049
+ p.add_argument("--release", default="dp2", choices=("dp1", "dp2"), help="RSP release of --adql (default dp2)")
2050
+ p.add_argument("--diasource", metavar="CSV", help="convert a saved RSP DiaSource table instead of asking a broker (schema "
2051
+ "level: not tested on real RSP data)")
2052
+ p.add_argument("--detectors", metavar="CSV", help="with --diasource: the saved CcdVisit (DP1) / VisitDetector (DP2) table; "
2053
+ "without it the exposure table is rebuilt from the detections")
2054
+ p.add_argument("--known", action="store_true", help="keep detections Rubin tied to a known object (ssObjectId)")
2055
+ p.add_argument("--min-reliability", type=float, default=0.0, help="drop detections below this real/bogus score (default 0: no cut)")
2056
+ p.add_argument("-o", "--outdir", default="rubin", help="output folder (default ./rubin): <tile>.csv.gz, exposures.csv")
2057
+ p.set_defaults(fn=cmd_rubin)
2058
+ p = add("extract", help="single-epoch source catalogue of a DECam Community Pipeline exposure (image + data-quality mask)")
2059
+ p.add_argument("image", help="CP image (*_ooi_*.fits.fz), all CCDs or some")
2060
+ p.add_argument("mask", help="its data-quality file (*_ood_*.fits.fz, same CCDs)")
2061
+ p.add_argument("--mask-dq7", action="store_true", help="also mask DQ code 7 (CP 'diff detect'); kept by default because it "
2062
+ "sits on moving objects in repeat sequences (docs/guide-catalogue.md)")
2063
+ p.add_argument("-o", "--output", help="output JSON (default <image>_cat.json; the rows go to <same name>.csv.gz)")
2064
+ p.set_defaults(fn=cmd_extract)
2065
+
2066
+ p = add("blindcheck", help="blind search for moving sources on registered FITS frames, notes sealed with their sha256 "
2067
+ "before a prediction is opened; then --compare with an ephemeris")
2068
+ p.add_argument("fields", nargs="*", metavar="FIELD", help="FITS cube with a time table, or a directory of registered frames")
2069
+ p.add_argument("--vmin", type=float, default=1.0, help="slowest rate searched [\"/h] (default 1)")
2070
+ p.add_argument("--vmax", type=float, default=50.0, help="fastest rate of the shift-and-stack [\"/h] (default 50; the "
2071
+ "linking of single-frame detections goes to 150)")
2072
+ p.add_argument("--step-px", type=float, default=2.0, help="rate grid step: total displacement over the sequence [px] (default 2)")
2073
+ p.add_argument("--snr", type=float, default=5.0, help="stack detection threshold [sigma] (default 5)")
2074
+ p.add_argument("--inject", type=int, default=10, help="synthetic movers per level and field for the completeness (0: none)")
2075
+ p.add_argument("--compare", metavar="EPHEM", help="second pass: CSV with ra, dec and mjd or utc (e.g. satfit --ephem)")
2076
+ p.add_argument("--notes", help="with --compare: the sealed notes of the first pass")
2077
+ p.add_argument("--tol", type=float, default=2.0, help="with --compare: a track within this mean separation [\"] matches")
2078
+ p.add_argument("-o", "--output", help="notes JSON (default blindcheck_notes.json; <notes>.sha256 beside it) or, with "
2079
+ "--compare, the comparison (default <notes>_compare.json)")
2080
+ p.set_defaults(fn=cmd_blindcheck)
2081
+ p = add("classify", help="dynamical class (resonant, Centaur, scattering, detached, classical) from a long REBOUND run")
2082
+ p.add_argument("obs", help="ADES PSV file (orbit and covariance are fitted; --fit-backend findorb as in the survey)")
2083
+ p.add_argument("--trk", help="track id if the file holds several")
2084
+ p.add_argument("--myr", type=float, default=10.0, help="integration length [Myr] (default 10)")
2085
+ p.add_argument("--clones", type=int, default=50, help="covariance clones besides the nominal orbit (default 50)")
2086
+ p.add_argument("--infl", type=float, default=1.0, help="covariance inflation in sigma (3: the check for arcs under 3 yr)")
2087
+ fitter(p, "--fit-backend")
2088
+ p.add_argument("-o", "--output", help="output JSON (default <trk>_classes.json)")
2089
+ p.set_defaults(fn=cmd_classify)
2090
+ p = add("export-ades", help="write vetted links, accepted forced measurements or extend points as ADES PSV (never submits)")
2091
+ p.add_argument("input", help="output of 'vet', 'forced' or 'extend'")
2092
+ p.add_argument("-o", "--output", required=True, help="PSV file to write")
2093
+ p.add_argument("--links", help="comma-separated link numbers to export (default: all survivors)")
2094
+ p.add_argument("--first", type=int, default=1, help="number of the first trkSub (default 1)")
2095
+ p.add_argument("--submitter", help="submitter name, e.g. 'J. Smith' (default from config)")
2096
+ p.add_argument("--observers", help="comma-separated observer names (default: config, or the FITS OBSERVER keyword)")
2097
+ p.add_argument("--measurers", help="comma-separated measurer names (default: the submitter)")
2098
+ p.add_argument("--validate", action="store_true", help="check the file with the MPC validator (nothing is submitted)")
2099
+ p.add_argument("--email", help="e-mail address the MPC validator requires (default from config)")
2100
+ p.add_argument("--obj-type", default="TNO", help="object type for the validator (default TNO)")
2101
+ p.add_argument("--astcat", help="links of a local table (link --rows): the astCat of their positions (default Gaia3)")
2102
+ p.add_argument("--allow-ids", action="store_true", help="links: ask NSC DR2 for the measurements of the link's object ids "
2103
+ "(the ids name the detections): DESIGNATED objects only")
2104
+ p.set_defaults(fn=cmd_export)
2105
+ p = add("run", help="fetch + link + vet one tile")
2106
+ p.add_argument("--tile", nargs=2, type=float, required=True, metavar=("RA", "DEC"), help="the 1x1 deg tile containing RA, DEC")
2107
+ p.add_argument("--box", default=None, help=argparse.SUPPRESS)
2108
+ p.add_argument("--blocks", type=int, default=1, metavar="N", help="cross-tile linking on the N x N tiles around --tile (see link)")
2109
+ p.add_argument("--near", action="store_true", help="near mode, 8-35 AU (see link)")
2110
+ link_opts(p)
2111
+ vet_opts(p)
2112
+ p.add_argument("--outdir", default=".", help="output directory (default .)")
2113
+ p.set_defaults(fn=cmd_run)
2114
+ p = add("plugins", help="list installed plugins and whether they load")
2115
+ core = set(sub.choices)
2116
+ p.set_defaults(fn=lambda a, cfg: cmd_plugins(a, cfg, core))
2117
+ if plugins.get("exporters"):
2118
+ p = add("export", help="write a vet or forced output with an exporter plugin")
2119
+ p.add_argument("input", help="output of 'vet' or 'forced'")
2120
+ p.add_argument("-o", "--output", required=True, help="file to write")
2121
+ p.add_argument("--format", required=True, choices=sorted(plugins.get("exporters")), help="exporter plugin")
2122
+ p.set_defaults(fn=cmd_export_plugin)
2123
+ core.add("export")
2124
+ for name, cmd in plugins.get("commands").items():
2125
+ if name in core:
2126
+ continue
2127
+ p = add(name, help=getattr(cmd, "help", None) or f"plugin command ({name})")
2128
+ cmd.add_arguments(p)
2129
+ p.set_defaults(fn=lambda a, cfg, cmd=cmd: dict(cmd.run(a, cfg) or {}))
2130
+ return ap
2131
+
2132
+
2133
+ def _execute(a):
2134
+ """Run the parsed command -> (result dict, output path, skipped)."""
2135
+ if getattr(a, "plot", False):
2136
+ import importlib.util
2137
+ if importlib.util.find_spec("matplotlib") is None:
2138
+ raise BadInput("--plot needs matplotlib: pip install 'orbitsift[plots]'")
2139
+ try:
2140
+ cfg = config.load(a.config)
2141
+ except (ValueError, OSError) as e:
2142
+ raise BadInput(f"config: {e}") from None
2143
+ if a.cache_dir:
2144
+ cfg["cache_dir"] = a.cache_dir
2145
+ if a.site:
2146
+ cfg["site"] = a.site
2147
+ config.apply(cfg)
2148
+ a.out = _out(a)
2149
+ a.key = _key(a, cfg) if a.out else None
2150
+ old = _up_to_date(a.out, a.key) if a.out and not a.force else None
2151
+ if a.dry_run:
2152
+ if a.cmd not in DRY:
2153
+ return dict(verdict="dry_run", compute="unknown for this command", fetch=[]), a.out, False
2154
+ res = DRY[a.cmd](a, cfg)
2155
+ res["would_skip"] = old is not None
2156
+ _print_plan(res)
2157
+ return res, a.out, False
2158
+ if old is not None:
2159
+ print(f"{a.out} is up to date (same inputs and version); --force recomputes")
2160
+ return old, a.out, True
2161
+ res = a.fn(a, cfg)
2162
+ return (res if isinstance(res, dict) and "verdict" in res else dict(verdict="done", **(res or {}))), a.out, False
2163
+
2164
+
2165
+ def main(argv=None):
2166
+ _Parser.json_errors = "--json" in (sys.argv[1:] if argv is None else argv)
2167
+ ap = build_parser()
2168
+ a = ap.parse_args(argv)
2169
+ if a.cmd == "libration" and not a.obs and not (a.elements and a.epoch):
2170
+ ap.error("libration needs an ADES file or --elements with --epoch")
2171
+ stdout = sys.stdout
2172
+ env = dict(schema=SCHEMA, command=a.cmd, orbitsift=__version__)
2173
+ res, out, skipped, err = None, None, False, None
2174
+ try:
2175
+ with contextlib.redirect_stdout(sys.stderr) if a.json else contextlib.nullcontext():
2176
+ res, out, skipped = _execute(a)
2177
+ v = str(res.get("verdict", ""))
2178
+ code = EXIT["no_result"] if v.startswith(("no_", "not_", "undecided")) else EXIT["ok"]
2179
+ except NoResult as e:
2180
+ res, code = dict(verdict=e.verdict, message=str(e)), EXIT["no_result"]
2181
+ print(e, file=sys.stderr)
2182
+ except KeyboardInterrupt:
2183
+ code, err = EXIT["interrupted"], dict(kind="interrupted", message="interrupted")
2184
+ except (BadInput, ValueError, FileNotFoundError, IsADirectoryError, PermissionError, net.OutboundBlocked) as e:
2185
+ code, err = EXIT["bad_input"], dict(kind="bad_input", message=str(e))
2186
+ print(err["message"], file=sys.stderr)
2187
+ except NET_ERRORS as e:
2188
+ code, err = EXIT["network"], dict(kind="network", message=f"{type(e).__name__}: {e}")
2189
+ print(f"network/service error: {err['message']} (cached results are kept; re-run to resume)", file=sys.stderr)
2190
+ except Exception as e:
2191
+ traceback.print_exc()
2192
+ code, err = EXIT["internal"], dict(kind="internal", message=f"{type(e).__name__}: {e}")
2193
+ if a.json:
2194
+ env.update(ok=code == 0, exit_code=code, output=out, skipped=skipped, result=res, error=err)
2195
+ print(json.dumps(_clean(env)), file=stdout)
2196
+ return code
2197
+
2198
+
2199
+ if __name__ == "__main__":
2200
+ sys.exit(main())