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
@@ -0,0 +1,164 @@
1
+ """Optional MCP server: the main OrbitSift commands as tools, JSON in and out.
2
+
3
+ pip install "orbitsift[mcp]"
4
+ orbitsift-mcp # stdio transport; register it in your MCP client
5
+
6
+ Each tool runs ``orbitsift <command> ... --json`` in a subprocess (so a long job or a crash never takes
7
+ the server down, and the results are exactly the CLI's, see docs/cli.md) and returns its JSON document.
8
+ Files are read and written relative to the server's working directory. Nothing is ever submitted to
9
+ the MPC: ``export_ades`` only writes a file for a human to review and submit.
10
+ """
11
+ import json
12
+ import os
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ SRC = str(Path(__file__).resolve().parent.parent)
18
+
19
+
20
+ FLAGS = {"--tile", "--outdir", "--dist", "--ident", "--no-static", "--force", "--trk", "--samples", "--max-tiles", "--start",
21
+ "--end", "--kyr", "--clones", "--myr", "-o", "--submitter", "--observers", "--links", "--controls", "--verify", "--mpcorb",
22
+ "--allow-ids"}
23
+
24
+
25
+ def _cli(*args, dry_run=False):
26
+ argv = [str(x) for x in args if x is not None] + ["--json"] + (["--dry-run"] if dry_run else [])
27
+ bad = [x for x in argv if x.startswith("-") and x not in FLAGS | {"--json", "--dry-run"} and not _number(x)]
28
+ if bad: # a value from the client must not become an option
29
+ return dict(schema="orbitsift/1", ok=False, exit_code=2,
30
+ error=dict(kind="bad_input", message=f"argument values may not start with '-': {bad}"))
31
+ env = dict(os.environ, PYTHONPATH=os.pathsep.join(filter(None, [SRC, os.environ.get("PYTHONPATH")])))
32
+ p = subprocess.run([sys.executable, "-m", "orbitsift.cli", *argv], capture_output=True, text=True, env=env)
33
+ try:
34
+ return json.loads(p.stdout)
35
+ except ValueError: # argparse errors (exit 2) print usage only
36
+ return dict(schema="orbitsift/1", ok=False, exit_code=p.returncode,
37
+ error=dict(kind="bad_input" if p.returncode == 2 else "internal", message=p.stderr.strip()[-2000:]))
38
+
39
+
40
+ def _number(x):
41
+ try:
42
+ float(x)
43
+ return True
44
+ except ValueError:
45
+ return False
46
+
47
+
48
+ def _flag(on, name):
49
+ return name if on else None
50
+
51
+
52
+ def survey_tile(ra: float, dec: float, outdir: str = ".", ident: bool = False, static: bool = True,
53
+ dist_min: float = 30.0, dist_max: float = 150.0, dry_run: bool = False, force: bool = False) -> dict:
54
+ """Fetch, link and vet the 1x1 deg NSC DR2 tile containing (ra, dec) [deg]. Each link gets a verdict:
55
+ survives, known:<designation>, vetoed:<reasons> or unchecked:<why>. Re-runs with the same inputs are
56
+ skipped; dry_run reports the queries, MB and time first. Writes <tile>_links.json, <tile>_vet.json."""
57
+ return _cli("run", "--tile", ra, dec, "--outdir", outdir, "--dist", dist_min, dist_max, _flag(ident, "--ident"),
58
+ _flag(not static, "--no-static"), _flag(force, "--force"), dry_run=dry_run)
59
+
60
+
61
+ def fit_orbit(obs_psv: str, trk: str | None = None, samples: int = 0) -> dict:
62
+ """Barycentric orbit of the observations in an ADES PSV file (elements, rms, short-arc warning; with
63
+ samples > 0 the 5/50/95% ranges of a, e, i)."""
64
+ return _cli("fit", obs_psv, *(["--trk", trk] if trk else []), "--samples", samples)
65
+
66
+
67
+ def precover(obs_psv: str, trk: str | None = None, max_tiles: int = 40, dry_run: bool = False) -> dict:
68
+ """Search NSC DR2 for other nights of the object. Each candidate has a verdict consistent /
69
+ not_consistent:<rules> (>= 2 new nights, rms <= 0.12", magnitudes consistent)."""
70
+ return _cli("precover", obs_psv, *(["--trk", trk] if trk else []), "--max-tiles", max_tiles, dry_run=dry_run)
71
+
72
+
73
+ def forced_photometry(obs_psv: str, trk: str | None = None, start: str | None = None, end: str | None = None,
74
+ dry_run: bool = False) -> dict:
75
+ """Forced PSF measurements on public archival DECam CCDs at the predicted positions (downloads one CCD
76
+ per exposure, ~32 MB each: use dry_run first). Verdict consistent / not_consistent:<rules>."""
77
+ return _cli("forced", obs_psv, *(["--trk", trk] if trk else []), *(["--start", start] if start else []),
78
+ *(["--end", end] if end else []), dry_run=dry_run)
79
+
80
+
81
+ def libration(obs_psv: str, trk: str | None = None, kyr: float = 100.0, clones: int = 20) -> dict:
82
+ """N-body Neptune-Trojan test of the orbit clones; verdict = the most common class (L4, L5, escaped, other)."""
83
+ return _cli("libration", obs_psv, *(["--trk", trk] if trk else []), "--kyr", kyr, "--clones", clones)
84
+
85
+
86
+ def dynamical_class(obs_psv: str, trk: str | None = None, myr: float = 10.0, clones: int = 50) -> dict:
87
+ """Dynamical class (resonant p:q, Centaur, scattering, detached, classical) of the orbit clones over a long REBOUND
88
+ run (extra 'rebound'); verdict = the majority class, secure when >= 80% of the orbits agree. Minutes per object."""
89
+ return _cli("classify", obs_psv, *(["--trk", trk] if trk else []), "--myr", myr, "--clones", clones)
90
+
91
+
92
+ def known_check(obs_psv: str, trk: str | None = None, clones: int = 40, mpcorb: bool = False, dry_run: bool = False) -> dict:
93
+ """Designated objects compared at THEIR observed dates (catches one-opposition objects a cone at our dates misses):
94
+ MPC bulk orbits (Distant.txt; mpcorb adds MPCORB.DAT.gz, ~80 MB), a local linkage, then a joint fit with their
95
+ published rows. Verdict known:<designation>, possible:<designation> or none_found. Nothing about the object is sent;
96
+ re-run after the MPC's daily updates."""
97
+ return _cli("known-check", obs_psv, *(["--trk", trk] if trk else []), "--clones", clones, _flag(mpcorb, "--mpcorb"),
98
+ dry_run=dry_run)
99
+
100
+
101
+ def lov_search(obs_psv: str, trk: str | None = None, start: str = "2012-09-01", end: str = "2019-12-31",
102
+ controls: str = "1,2,3,4", verify: bool = False, dry_run: bool = False) -> dict:
103
+ """Other seasons of a short-arc object in NSC DR2, along its line of variations, with rotated controls ("1,2,3,4",
104
+ "" for none). Verdict strong / strong_not_clean / hit / no_hit; a hit is a locator. verify measures the best hit's
105
+ points on their DECam CCDs (~32 MB download each: use dry_run first); a point whose download failed is 'failed'."""
106
+ return _cli("lov", obs_psv, *(["--trk", trk] if trk else []), "--start", start, "--end", end, "--controls", controls,
107
+ _flag(verify, "--verify"), dry_run=dry_run)
108
+
109
+
110
+ def export_ades(input_json: str, output_psv: str, submitter: str, observers: str, links: str | None = None,
111
+ allow_ids: bool = False) -> dict:
112
+ """Write the surviving links of a vet output, the accepted measurements of a forced output, or the new
113
+ points of an extend output (one block per instrument and station) as an ADES PSV file, with warnings
114
+ (singleton nights, astCat, skipped extend points). It never submits: a human reviews and
115
+ submits the file. Links need allow_ids: their NSC object ids are sent to Data Lab (designated objects; for an
116
+ undesignated candidate ask the user first)."""
117
+ return _cli("export-ades", input_json, "-o", output_psv, "--submitter", submitter, "--observers", observers,
118
+ *(["--links", links] if links else []), _flag(allow_ids, "--allow-ids"))
119
+
120
+
121
+ def list_plugins() -> dict:
122
+ """Installed OrbitSift plugins (sources, vetters, commands, exporters) and whether they load."""
123
+ return _cli("plugins")
124
+
125
+
126
+ TOOLS = (survey_tile, fit_orbit, precover, forced_photometry, libration, dynamical_class, known_check, lov_search, export_ades,
127
+ list_plugins)
128
+
129
+
130
+ INSTRUCTIONS = (
131
+ "Find TNOs, Neptune Trojans and Centaurs in public archival data. Use these tools rather than the orbitsift CLI; "
132
+ "the rules below are complete, so there is no need to look for AGENTS.md (it is in the OrbitSift repository, not "
133
+ "in your working directory). 1) Never submit anything to the MPC: export_ades only writes a file for a human. "
134
+ "2) Never call a candidate an object, a discovery or new without: >= 2 new nights fitted with the arc at rms "
135
+ "<= 0.12\" with a bound orbit, consistent magnitudes, and a known_check that finds nothing (known:<name> or "
136
+ "possible:<name> means look at that object). 3) A 'survives' link is a candidate, not an object. 4) Do not "
137
+ "publish positions or orbits of unreported candidates; report counts and classes. Use dry_run before anything "
138
+ "that downloads CCDs or many tiles. export_ades with allow_ids sends NSC object ids to Data Lab: fine for a "
139
+ "designated object, ask the user first for an undesignated candidate.")
140
+
141
+
142
+ def build():
143
+ try:
144
+ from mcp.server.mcpserver import MCPServer as Server # mcp >= 2
145
+ except ImportError:
146
+ from mcp.server.fastmcp import FastMCP as Server # mcp 1.x
147
+ server = Server("orbitsift", instructions=INSTRUCTIONS)
148
+ for f in TOOLS:
149
+ server.tool()(f)
150
+ return server
151
+
152
+
153
+ def main():
154
+ try:
155
+ server = build()
156
+ except ImportError:
157
+ print("orbitsift-mcp needs the MCP SDK: pip install 'orbitsift[mcp]'", file=sys.stderr)
158
+ return 2
159
+ server.run()
160
+ return 0
161
+
162
+
163
+ if __name__ == "__main__":
164
+ sys.exit(main())
orbitsift/multiyear.py ADDED
@@ -0,0 +1,409 @@
1
+ """Multi-year seeds: the seed stage of the survey's DES-style sparse linker on NSC DR2 (2026 pilot, PREREG A1/A2).
2
+
3
+ The dense anchor linker (``dense``) is run with DES-style windows instead of the production ones: three nights within
4
+ 120 days (``dtmax``) among the 64 nearest covering nights (``k``), kept from 3 nights on. Each kept link is a *seed*: a
5
+ few rows and a distance and radial rate (gamma, gamma-dot). The growth stage (not here) extends seeds over all years.
6
+
7
+ Steps, each one function, all on local files (nothing here touches the network). The growth stage is ``growth``.
8
+
9
+ 1. ``load_tile``: one tile's orphan rows (the ``catalog.orphans`` CSV: id, ra, dec, mjd, ... gaia, ls) and the NSC DR2
10
+ exposure table -> loader rows. Each row is given its exposure (``dense.exposure_of``) and a magnitude error from the
11
+ exposure depth; then the survey's cuts (flags <= 1, no band magnitude brighter than 20, 0.7 <= fwhm <= 3.0, flags < 4,
12
+ no Gaia or Legacy Survey counterpart). ``cut=False`` keeps every row (the growth catalogue's second level).
13
+ 2. ``reduce``: the exposure cap and clump mask of ``dense`` (per tile, before any pairing).
14
+ 3. ``key64``: one 64-bit key per row (rule F2): NSC ids "a_b" -> (a << 32) | b; any other id -> 63 bits of
15
+ blake2b(exposure | RA | Dec) with the top bit set, so a detection has the same key in every tile file that holds it.
16
+ 4. ``merge``: the rows of several reduced tiles as one region (a 2-degree box), each key once.
17
+ 5. ``seeds``: exposures of the rows (``exposures``) -> ``dense.prep`` -> ``dense.link`` with ``WINDOWS`` -> a seed
18
+ table (row keys per seed, gamma, gamma-dot, nights). Above ``DEEP_ROWS`` rows a tile is seeded with the production
19
+ windows (amendment A1) and a box is not seeded at all.
20
+ 6. ``catalogue``: the rows of many tiles as one table, each key once, sorted by key, with per-row sigma, exposure index
21
+ and level (0 = loader row, 1 = other orphan row of a non-deep tile).
22
+
23
+ Tiles here are the survey's: 1 x 1 degree cells, files cut with a 0.15 deg margin (RA margin 0.15 / cos(dec0 + 0.5)).
24
+ Boxes: n x n tiles from a lower-left corner tile, on a lattice of stride n with an offset (``box_corners``).
25
+ """
26
+ import csv
27
+ import gzip
28
+ import hashlib
29
+ import json
30
+ import math
31
+ import os
32
+ import warnings
33
+
34
+ import numpy as np
35
+
36
+ from . import dense, growth
37
+
38
+ MAGS = ("gmag", "rmag", "imag", "zmag", "ymag", "vrmag")
39
+ VCOL = np.array([-0.27, 0.17, 0.28, 0.31, 0.31, 0.1]) # V - band, MAGS order (catalog.VCOL)
40
+ FILT_VCOL = dict(zip(("g", "r", "i", "z", "Y", "VR"), VCOL.tolist())) # by exposure filter; any other filter: 0
41
+ WINDOWS = dict(gmin=1 / 80, gmax=1 / 25, dtmax=120.0, k=64, nmin=3, nminu=3) # DES-style seed windows (PREREG section 5)
42
+ DEEP_ROWS = 100000 # A1: a denser tile is seeded with PRODUCTION; a denser box is skipped
43
+ PRODUCTION = dict(gmin=1 / 80, gmax=1 / 25) # the dense defaults: dtmax 40, k 8, nmin 4, nminu 6
44
+ SHIFT = (20.0, 60.0) # arcsec per axis of the shift controls (not used for real seeds)
45
+
46
+
47
+ # ---------------------------------------------------------------- tiles and boxes
48
+ def tile_id(ra0, dec0):
49
+ """Integer tile id ra0 * 1000 + dec0 + 100 (the survey's) of the cell with lower-left corner (ra0, dec0)."""
50
+ return (int(ra0) % 360) * 1000 + int(dec0) + 100
51
+
52
+
53
+ def tile_corner(tid):
54
+ return tid // 1000, tid % 1000 - 100
55
+
56
+
57
+ def tile_name(tid):
58
+ """File stem of a tile: '026+00'."""
59
+ a, d = tile_corner(tid)
60
+ return f"{a:03d}{d:+03d}"
61
+
62
+
63
+ def tile_box(tid):
64
+ """The survey's query box of a tile [ra0, ra1, dec0, dec1] (margin 0.15 deg; RA margin at the cell's mid Dec)."""
65
+ a, d = tile_corner(tid)
66
+ pr = round(0.15 / max(math.cos(math.radians(d + 0.5)), 0.05), 3)
67
+ return [round(a - pr, 3), round(a + 1 + pr, 3), round(d - 0.15, 2), round(d + 1.15, 2)]
68
+
69
+
70
+ def tiles_of(ra0, ra1, dec0, dec1):
71
+ """Tile ids of a region of whole degrees, RA-major (the catalogue's order)."""
72
+ return [tile_id(a, d) for a in range(int(ra0), int(ra1)) for d in range(int(dec0), int(dec1))]
73
+
74
+
75
+ def box_corners(ra0, ra1, dec0, dec1, n=2, off=0, origin=None):
76
+ """Lower-left tiles of the n x n boxes of a region: a lattice of stride n through origin (default: the region's corner),
77
+ moved by off in both axes; corners inside the region (boxes may overhang it). The 2026 pilot's lattice: origin (0, -7)."""
78
+ oa, od = (ra0, dec0) if origin is None else origin
79
+ a0, d0 = int(ra0) + (int(oa) + off - int(ra0)) % n, int(dec0) + (int(od) + off - int(dec0)) % n
80
+ return [tile_id(a, d) for a in range(a0, int(ra1), n) for d in range(d0, int(dec1), n)]
81
+
82
+
83
+ def box_tiles(corner, n):
84
+ a, d = tile_corner(corner)
85
+ return [tile_id(a + i, d + j) for i in range(n) for j in range(n)]
86
+
87
+
88
+ def centre(tid, n=1):
89
+ """Tangent point of a tile (n = 1) or of the n x n box whose corner it is."""
90
+ a, d = tile_corner(tid)
91
+ return a + 0.5 * n, d + 0.5 * n
92
+
93
+
94
+ # ---------------------------------------------------------------- exposures
95
+ def read_exposures(path):
96
+ """NSC DR2 exposure table (CSV, optionally gzipped; columns exposure, mjd = start, filter, exptime [s], ra, dec,
97
+ depth95) -> dict of arrays in file order, plus ``mid`` = mjd + exptime / 2 (the time the linker uses)."""
98
+ op = gzip.open if str(path).endswith(".gz") else open
99
+ with op(path, "rt") as f:
100
+ rows = list(csv.DictReader(f))
101
+ g = lambda k: np.array([float(r[k]) if r[k] not in ("", None) else np.nan for r in rows])
102
+ ex = dict(name=np.array([r["exposure"] for r in rows]), mjd=g("mjd"), exptime=g("exptime"), ra=g("ra"), dec=g("dec"),
103
+ depth=g("depth95"), filt=np.array([r["filter"] for r in rows]))
104
+ ex["mid"] = ex["mjd"] + ex["exptime"] / 2 / 86400
105
+ if rows and "radius" in rows[0]: # deg: tables of single detectors (``rubin.write``)
106
+ ex["radius"] = g("radius")
107
+ return ex
108
+
109
+
110
+ def exposures(d, ex):
111
+ """Per exposure of loader rows d (d['expname']): mid, ra, dec, depth (V limit) as the linker wants them. From the
112
+ exposure table when it has the exposure (depth = depth95 + V - band; missing depth: median V of its rows if >= 20),
113
+ else from the rows. Still missing: the median depth of the region (23 if none). Exposures in d['expbad'] cover
114
+ nothing (depth -99)."""
115
+ pos = {n: i for i, n in enumerate(ex["name"])}
116
+ ne = len(d["expname"])
117
+ o = dict(mid=np.full(ne, np.nan), ra=np.full(ne, np.nan), dec=np.full(ne, np.nan), depth=np.full(ne, np.nan))
118
+ order = np.argsort(d["expi"], kind="stable")
119
+ cut = np.searchsorted(d["expi"][order], np.arange(ne + 1))
120
+ for e, nm in enumerate(d["expname"]):
121
+ i = pos.get(str(nm))
122
+ r = order[cut[e]:cut[e + 1]]
123
+ vmed = np.nanmedian(d["V"][r]) if len(r) >= 20 and np.isfinite(d["V"][r]).any() else np.nan
124
+ if i is not None:
125
+ o["mid"][e], o["ra"][e], o["dec"][e] = ex["mid"][i], ex["ra"][i], ex["dec"][i]
126
+ dp = ex["depth"][i]
127
+ o["depth"][e] = dp + FILT_VCOL.get(str(ex["filt"][i]), 0.0) if np.isfinite(dp) else vmed
128
+ elif len(r):
129
+ o["mid"][e], o["ra"][e], o["dec"][e], o["depth"][e] = d["mjd"][r].min(), d["ra"][r].mean(), d["dec"][r].mean(), vmed
130
+ bad = ~np.isfinite(o["depth"])
131
+ o["depth"][bad] = np.nanmedian(o["depth"]) if (~bad).any() else 23.0
132
+ if "expbad" in d:
133
+ o["depth"][d["expbad"]] = -99.0
134
+ return o
135
+
136
+
137
+ # ---------------------------------------------------------------- loader
138
+ def read_rows(path):
139
+ """An orphan-tile CSV (``catalog.orphans`` columns) -> list of dicts (strings)."""
140
+ with gzip.open(path, "rt") as f:
141
+ return [r for r in csv.DictReader(f)]
142
+
143
+
144
+ def load_tile(rows, ex, cut=True):
145
+ """Orphan rows of one tile file + the exposure table -> loader dict (numpy arrays per row: ra, dec, mjd, V, night,
146
+ fwhm, magerr, ndet, flags, band, row; id; expname = sorted names of the exposures of all rows with one, expi;
147
+ nraw = rows with an exposure). Rows without an exposure are dropped first. magerr = min(0.217 x 10^(0.4 (m -
148
+ depth95)), 0.5) with m the brightest band magnitude (depth95 if none, 23 if no depth), rounded to 4 decimals."""
149
+ fl = lambda s: float(s) if s else np.nan
150
+ mjd = np.array([float(r["mjd"]) for r in rows])
151
+ ndet = np.array([fl(r["ndet"]) for r in rows])
152
+ ei = dense.exposure_of(mjd, np.where(np.isfinite(ndet), np.trunc(ndet), 1.0), ex["mjd"], ex["exptime"]) if len(rows) \
153
+ else np.zeros(0, int)
154
+ has = np.flatnonzero(ei >= 0)
155
+ rows = [rows[k] for k in has]
156
+ ei = ei[has]
157
+ m = np.array([[float(r[k]) if r[k] and float(r[k]) < 50 else np.nan for k in MAGS] for r in rows]).reshape(-1, len(MAGS))
158
+ num = lambda k: np.array([fl(r[k]) for r in rows])
159
+ ra, dec, mjd, fwhm, flags, ndet, dmjd = (num(k) for k in ("ra", "dec", "mjd", "fwhm", "flags", "ndet", "deltamjd"))
160
+ gaia = np.array([1.0 if r["gaia"] else 0.0 for r in rows])
161
+ ls = np.array([1.0 if r["ls"] else 0.0 for r in rows])
162
+ with np.errstate(all="ignore"), warnings.catch_warnings():
163
+ warnings.simplefilter("ignore")
164
+ mband = np.nanmin(m, axis=1) if len(m) else np.zeros(0)
165
+ V = np.nanmin(m + VCOL, axis=1) if len(m) else np.zeros(0)
166
+ band = np.where(np.isfinite(mband), np.nanargmin(np.where(np.isfinite(m), m, 1e9), axis=1), -1) if len(m) \
167
+ else np.zeros(0, int)
168
+ dp = np.where(np.isfinite(ex["depth"][ei]), ex["depth"][ei], 23.0)
169
+ me = np.minimum(0.217 * 10 ** (0.4 * (np.where(np.isfinite(mband), mband, dp) - dp)), 0.5)
170
+ magerr = np.array([float(f"{x:.4f}") for x in me]) # the survey's tile files hold it as text, 4 decimals
171
+ fz = np.where(np.isfinite(flags), flags, 0.0)
172
+ keep = np.ones(len(rows), bool)
173
+ if cut:
174
+ with np.errstate(invalid="ignore"):
175
+ keep = (fz <= 1) & ~(mband < 20) & (fwhm >= 0.7) & (fwhm <= 3.0) & (flags < 4) & (gaia == 0) & (ls == 0)
176
+ names = np.array(sorted(set(ex["name"][ei].tolist())))
177
+ expi = np.searchsorted(names, ex["name"][ei]).astype(np.int64)
178
+ d = dict(ra=ra, dec=dec, mjd=mjd, V=V, night=np.floor(mjd - 0.5).astype(np.int64), fwhm=fwhm, magerr=magerr, ndet=ndet,
179
+ dmjd=dmjd, flags=fz, band=band.astype(np.int64), row=np.arange(len(rows)), expi=expi)
180
+ d = {k: v[keep] for k, v in d.items()}
181
+ d["id"] = np.array([r["id"] for r in rows])[keep] if len(rows) else np.zeros(0, str)
182
+ d["expname"], d["nraw"] = names, np.array([len(rows)])
183
+ return d
184
+
185
+
186
+ ROWCOLS = ("ra", "dec", "mjd", "V", "night", "fwhm", "magerr", "ndet", "dmjd", "flags", "band", "row", "expi", "id", "key")
187
+
188
+
189
+ def subset(d, m):
190
+ return {k: (v[m] if k in ROWCOLS else v) for k, v in d.items()}
191
+
192
+
193
+ def reduce(d, expmax=dense.EXPMAX, clump_factor=dense.CLUMP):
194
+ """The exposure cap, then the clump mask (``dense.expcap``, ``dense.clump``) -> new loader dict with 'expbad'."""
195
+ bad = dense.expcap(d["expi"], len(d["expname"]), expmax)
196
+ d = subset(d, ~bad[d["expi"]])
197
+ d["expbad"] = bad
198
+ m, _ = dense.clump(d["expi"], d["ra"], d["dec"], len(d["expname"]), clump_factor)
199
+ return subset(d, ~m)
200
+
201
+
202
+ # ---------------------------------------------------------------- row keys
203
+ def key1(s):
204
+ """Key of an NSC id 'a_b' ((a << 32) | b), or None for any other id."""
205
+ q = str(s).split("_")
206
+ return (int(q[0]) << 32) | int(q[1]) if len(q) == 2 and q[0].isdigit() and q[1].isdigit() else None
207
+
208
+
209
+ def key64(d):
210
+ """F2 row keys of loader dict d (id, expname, expi, ra, dec) -> uint64 array. NSC ids keep their value; any other id
211
+ (e.g. '<exposure>_<row number in the file>', not unique between files) is replaced by 63 bits of
212
+ blake2b(exposure name | RA | Dec as float64 little-endian) with the top bit set."""
213
+ en = [str(n).encode() + b"|" for n in d["expname"]]
214
+ pos = np.ascontiguousarray(np.column_stack([d["ra"], d["dec"]]), "<f8").tobytes()
215
+ out = np.empty(len(d["ra"]), np.uint64)
216
+ for i, (s, e) in enumerate(zip(d["id"], d["expi"])):
217
+ k = key1(s)
218
+ out[i] = k if k is not None else int.from_bytes(hashlib.blake2b(en[e] + pos[16 * i:16 * i + 16], digest_size=8).digest(),
219
+ "little") | (1 << 63)
220
+ return out
221
+
222
+
223
+ # ---------------------------------------------------------------- regions
224
+ def merge(parts):
225
+ """Reduced loader dicts of several tiles -> one: rows concatenated in the given order, each key once (first copy),
226
+ in that order; exposures renamed into the union of names; an exposure capped in any tile is capped in the region."""
227
+ parts = [p for p in parts if p is not None and len(p["ra"])]
228
+ if not parts:
229
+ return None
230
+ names = np.unique(np.concatenate([p["expname"] for p in parts]))
231
+ cols = [k for k in ROWCOLS if k in parts[0] and k != "expi"]
232
+ d = {k: np.concatenate([p[k] for p in parts]) for k in cols}
233
+ d["expi"] = np.concatenate([np.searchsorted(names, p["expname"][p["expi"]]) for p in parts]).astype(np.int64)
234
+ bad = np.zeros(len(names), bool)
235
+ for p in parts:
236
+ bad[np.searchsorted(names, p["expname"][p["expbad"]])] = True
237
+ ix = np.sort(np.unique(d["key"], return_index=True)[1])
238
+ d = {k: v[ix] for k, v in d.items()}
239
+ d.update(expname=names, expbad=bad, nraw=np.array([0]))
240
+ return d
241
+
242
+
243
+ # ---------------------------------------------------------------- observer
244
+ CTIO = (math.radians(-30.1652), math.radians(-70.8150), 6378.137 / 1.495978707e8 * 0.9984) # lat, lon, radius [AU]
245
+ _GEO = {}
246
+
247
+
248
+ def ctio(mjd):
249
+ """The survey's observer (the one the 2026 seeds were made with): astropy's geocentre at the UTC MJD rounded to 1e-6 d,
250
+ plus CTIO rotated by GMST only. It differs from ``orbit.observer(mjd, 'W84')`` (MPC parallax constants) by a few
251
+ km; that is enough to flip borderline links: on the public fixture 17 of 64 seed tables differ with 'W84' (and gamma
252
+ of the other 47 by up to 1e-3 relative); with this one all 64 are the survey's (gamma to 1e-10)."""
253
+ mjd = np.asarray(mjd, float)
254
+ key = np.round(mjd, 6)
255
+ miss = np.setdiff1d(key, list(_GEO))
256
+ if len(miss):
257
+ from astropy.coordinates import get_body_barycentric
258
+ from astropy.time import Time
259
+ _GEO.update(zip(miss.tolist(), get_body_barycentric("earth", Time(miss, format="mjd", scale="utc")).xyz.to("au").value.T))
260
+ lat, lon, re = CTIO
261
+ lst = np.radians((280.46061837 + 360.98564736629 * (mjd - 51544.5)) % 360) + lon
262
+ geo = np.array([_GEO[k] for k in key.tolist()]).reshape(*key.shape, 3)
263
+ return geo + re * np.stack([np.cos(lat) * np.cos(lst), np.cos(lat) * np.sin(lst), np.full_like(lst, np.sin(lat))], -1)
264
+
265
+
266
+ # ---------------------------------------------------------------- seeds
267
+ def seeds(d, ex, ctr, box=False, site=ctio, native=None, control=None, **par):
268
+ """Seed table of a reduced tile (box=False) or merged box: dict(off (row offsets), key (row keys, uint64), g, gd,
269
+ nights, stat). A tile above DEEP_ROWS rows is seeded with PRODUCTION; a box above it is not seeded
270
+ (stat skipped=1). control 'shiftN': the rows are first moved by ``growth.shift`` (SHIFT; exposures from the real rows)."""
271
+ deep = len(d["ra"]) > DEEP_ROWS
272
+ empty = dict(off=np.zeros(1, np.int64), key=np.zeros(0, np.uint64), g=np.zeros(0), gd=np.zeros(0), nights=np.zeros(0, np.int64))
273
+ if box and deep:
274
+ return dict(empty, stat=dict(skipped=1, rows=len(d["ra"]), control=control or "real"))
275
+ e = exposures(d, ex)
276
+ n = growth.control_seed(control)
277
+ if n is not None:
278
+ d = growth.shift(d, n, *SHIFT)
279
+ rows = dict(ra=d["ra"], dec=d["dec"], mjd=d["mjd"], V=d["V"], night=d["night"], ndet=d["ndet"],
280
+ sig=dense.sigma(d["fwhm"], d["magerr"]), expi=d["expi"])
281
+ P = dense.prep(rows, e, ctr[0], ctr[1], site)
282
+ links, st = dense.link(P, native=native, **(PRODUCTION if deep else dict(WINDOWS, **par)))
283
+ ks = [d["key"][P["src"][lk["m"]]] for lk in links]
284
+ return dict(off=np.concatenate([[0], np.cumsum([len(k) for k in ks])]).astype(np.int64),
285
+ key=np.concatenate(ks).astype(np.uint64) if ks else np.zeros(0, np.uint64),
286
+ g=np.array([lk["p"][4] for lk in links], float), gd=np.array([lk["p"][5] for lk in links], float),
287
+ nights=np.array([lk["nights"] for lk in links], np.int64), stat=dict(st, rows=len(d["ra"]), deep=int(deep),
288
+ control=control or "real"))
289
+
290
+
291
+ def save_seeds(s, path):
292
+ tmp = f"{path}.{os.getpid()}.tmp.npz"
293
+ np.savez(tmp, off=s["off"], key=s["key"], g=s["g"], gd=s["gd"], nights=s["nights"], stat=json.dumps(s["stat"]))
294
+ os.replace(tmp, path)
295
+
296
+
297
+ def load_seeds(path):
298
+ with np.load(path) as z:
299
+ out = {k: z[k] for k in z.files if k != "stat"}
300
+ out["stat"] = json.loads(str(z["stat"]))
301
+ if "id64" in out: # the survey's own files
302
+ out["key"] = out.pop("id64")
303
+ return out
304
+
305
+
306
+ def _tid(stem):
307
+ """'003-06' (tile_name) or '3094' (the survey's file names) -> tile id."""
308
+ return int(stem) if stem.isdigit() else tile_id(int(stem[:3]), int(stem[3:]))
309
+
310
+
311
+ def seed_tables(*outdirs):
312
+ """Seed tables of ``run`` folders (tiles/, b20/, b21/; e.g. one per region) in the survey's reading order: tiles first,
313
+ then the box sets in name order; within a set by str(tile id) (the survey's file names were tile ids).
314
+ -> list of ('set/name', table)."""
315
+ from pathlib import Path
316
+ fs = [(p.name, f) for d in outdirs for p in Path(d).iterdir() if p.is_dir() and (p.name == "tiles" or p.name.startswith("b"))
317
+ for f in p.glob("*.npz")]
318
+ fs.sort(key=lambda x: (x[0] != "tiles", x[0], str(_tid(x[1].stem))))
319
+ return [(f"{s}/{f.stem}", load_seeds(f)) for s, f in fs]
320
+
321
+
322
+ # ---------------------------------------------------------------- catalogue
323
+ def catalogue(loader, raw=None, deep=()):
324
+ """Growth catalogue of a region. loader: reduced loader dicts in tile order (level 0); raw: unreduced, uncut loader
325
+ dicts of the same tiles (level 1, ``cut=False``) or None; deep: tile indices whose raw rows are left out. Each key
326
+ once (first copy in that order), sorted by key -> dict(key, ra, dec, mjd, V (f4), sig (f4), exp, lvl, night, expname)."""
327
+ parts, names = [], {}
328
+ for lvl, ds in ((0, loader), (1, raw or ())):
329
+ for n, a in enumerate(ds):
330
+ if a is None or (lvl and n in deep):
331
+ continue
332
+ ok = np.isfinite(a["V"]) & np.isfinite(a["ra"])
333
+ lut = np.array([names.setdefault(str(x), len(names)) for x in a["expname"]], np.int32)
334
+ fw, me = (a["fwhm"], a["magerr"]) if lvl == 0 else (a["fwhm"].astype("f4"), a["magerr"].astype("f4"))
335
+ parts.append(dict(key=a["key"][ok], ra=a["ra"][ok], dec=a["dec"][ok], mjd=a["mjd"][ok], V=a["V"][ok].astype("f4"),
336
+ sig=dense.sigma(fw[ok], me[ok]).astype("f4"), exp=lut[a["expi"][ok]] if len(lut) else np.zeros(int(ok.sum()), np.int32),
337
+ lvl=np.full(int(ok.sum()), lvl, np.int32)))
338
+ c = {k: np.concatenate([p[k] for p in parts]) for k in parts[0]}
339
+ _, ix = np.unique(c["key"], return_index=True)
340
+ c = {k: v[ix] for k, v in c.items()}
341
+ c["night"] = np.floor(c["mjd"] - 0.5).astype(np.int32)
342
+ c["expname"] = np.array(list(names))
343
+ return c
344
+
345
+
346
+ def join_catalogues(cats):
347
+ """Several ``catalogue`` dicts (e.g. one per region) -> one: rows in the given order, each key once (first copy), sorted by
348
+ key; exposure indices renamed into the union of names (first appearance)."""
349
+ names, parts = {}, []
350
+ for c in cats:
351
+ lut = np.array([names.setdefault(str(x), len(names)) for x in c["expname"]], np.int32)
352
+ parts.append(dict({k: np.asarray(c[k]) for k in ("key", "ra", "dec", "mjd", "V", "sig", "lvl")}, exp=lut[np.asarray(c["exp"])]))
353
+ c = {k: np.concatenate([p[k] for p in parts]) for k in parts[0]}
354
+ _, ix = np.unique(c["key"], return_index=True)
355
+ c = {k: v[ix] for k, v in c.items()}
356
+ c["night"] = np.floor(c["mjd"] - 0.5).astype(np.int32)
357
+ c["expname"] = np.array(list(names))
358
+ return c
359
+
360
+
361
+ # ---------------------------------------------------------------- a region, end to end
362
+ def run(rows_dir, exposures_path, region, outdir, boxes=2, origin=None, site=ctio, cat=False, force=False, native=None, log=print,
363
+ control=None, **par):
364
+ """Seed tables of every tile of region (ra0, ra1, dec0, dec1; whole degrees) and of every n x n box (n = boxes, both
365
+ lattice offsets, lattice through origin: ``box_corners``) that lies inside it, from rows_dir/<tile_name>.csv.gz and the
366
+ exposure table. control 'shiftN': the seeds of that shift control (the catalogue is always the real one).
367
+ -> outdir/tiles/<tile>.npz, outdir/b<n><off>/<corner tile>.npz, and with cat outdir/catalogue.npz (levels 0 and 1).
368
+ An existing table is kept unless force. Returns a summary (units, seeds, rows, missing tile files)."""
369
+ from pathlib import Path
370
+ ex = read_exposures(exposures_path)
371
+ out = Path(outdir)
372
+ ts = tiles_of(*region)
373
+ files = {t: Path(rows_dir) / f"{tile_name(t)}.csv.gz" for t in ts}
374
+ missing = [tile_name(t) for t in ts if not files[t].exists()]
375
+ units = [(t, 1, "tiles") for t in ts if files[t].exists()]
376
+ if boxes > 1:
377
+ units += [(c, boxes, f"b{boxes}{o}") for o in range(2) for c in box_corners(*region, boxes, o, origin)
378
+ if all(files.get(x) and files[x].exists() for x in box_tiles(c, boxes))]
379
+ todo = [u for u in units if force or not (out / u[2] / f"{tile_name(u[0])}.npz").exists()]
380
+ need = sorted({x for t, n, _ in todo for x in box_tiles(t, n)} | (set(files) if cat else set()))
381
+ loaded, raw = {}, {} # ponytail: every needed tile in RAM at once; stream box by box for regions of hundreds of tiles
382
+ for t in need:
383
+ if files[t].exists():
384
+ rows = read_rows(files[t])
385
+ d = load_tile(rows, ex)
386
+ d["key"] = key64(d)
387
+ loaded[t] = reduce(d)
388
+ if cat:
389
+ r = load_tile(rows, ex, cut=False)
390
+ r["key"] = key64(r)
391
+ raw[t] = r
392
+ summ = dict(units=len(units), computed=len(todo), seeds=0, missing_tiles=missing, region=list(region), boxes=boxes)
393
+ for t, n, kind in todo:
394
+ d = loaded[t] if n == 1 else merge([loaded[x] for x in box_tiles(t, n)])
395
+ if d is None:
396
+ continue
397
+ s = seeds(d, ex, centre(t, n), box=n > 1, site=site, native=native, control=control, **par)
398
+ (out / kind).mkdir(parents=True, exist_ok=True)
399
+ save_seeds(s, out / kind / f"{tile_name(t)}.npz")
400
+ summ["seeds"] += len(s["g"])
401
+ log(f"{kind}/{tile_name(t)}: {s['stat'].get('rows')} rows, {len(s['g'])} seeds")
402
+ if cat:
403
+ L = [loaded.get(t) for t in ts]
404
+ c = catalogue(L, [raw.get(t) for t in ts], {i for i, a in enumerate(L) if a is not None and len(a["ra"]) > DEEP_ROWS})
405
+ out.mkdir(parents=True, exist_ok=True)
406
+ np.savez(out / "catalogue.npz", **c)
407
+ summ["catalogue_rows"] = len(c["key"])
408
+ log(f"catalogue: {len(c['key'])} rows ({int(c['lvl'].sum())} of level 1) -> {out / 'catalogue.npz'}")
409
+ return summ