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/external.py ADDED
@@ -0,0 +1,204 @@
1
+ """Optional published backends: Find_Orb (B. Gray, Project Pluto) for orbit fits and REBOUND (Rein & Liu
2
+ 2012; WHFast, Rein & Tamayo 2015) for the N-body integration of the libration test.
3
+
4
+ Both are GPL and neither is part of OrbitSift: Find_Orb is run as a separate program (``fo``, found through
5
+ $ORBITSIFT_FINDORB or PATH), REBOUND is imported only when asked for (extra ``rebound``). The internal
6
+ fitter and integrator stay the defaults.
7
+ """
8
+ import json
9
+ import os
10
+ import re
11
+ import shutil
12
+ import subprocess
13
+ import tempfile
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+
18
+ from . import ades, orbit
19
+
20
+ FINDORB_URL = "https://www.projectpluto.com/find_orb.htm"
21
+ NAMES = {"a": "a", "e": "e", "i": "i", "node": "asc_node", "peri": "arg_per", "M": "M"} # ours: Find_Orb's total.json
22
+
23
+
24
+ def findorb_exe():
25
+ """Path of Find_Orb's ``fo``: $ORBITSIFT_FINDORB, else ``fo`` on PATH."""
26
+ p = os.environ.get("ORBITSIFT_FINDORB") or shutil.which("fo")
27
+ if not p or not Path(p).is_file():
28
+ raise FileNotFoundError(f"Find_Orb 'fo' not found: build it ({FINDORB_URL}) and set ORBITSIFT_FINDORB=/path/to/fo "
29
+ "or put fo on PATH")
30
+ return p
31
+
32
+
33
+ def findorb_fit(obs, sigma=0.15, site="W84", epoch=None, timeout=600, seed=None):
34
+ """Fit observations (dicts as ``ades.read``: mjd, ra, dec, rmsRA, rmsDec, stn, astCat) with Find_Orb.
35
+
36
+ Weights: each row's rmsRA/rmsDec, else ``sigma`` ["]. Everything else is Find_Orb's own settings (its
37
+ environ.dat: JPL ephemeris, perturbers, 3-sigma outlier rejection); a fit without a JPL DE ephemeris is
38
+ refused. (Settings are not passed on fo's command line: fo writes them back into environ.dat.)
39
+ ``epoch`` (JD) is where its own elements are shown. -> (orbit.Orbit at Find_Orb's fit epoch, with the
40
+ residuals of every row, rejected ones included, as the internal fit; info dict), or None if fo finds no
41
+ orbit. ``seed``: Find_Orb's own start (info["findorb"]["seed"] of an earlier fit: epoch and its covar.json state
42
+ vector), passed as fo -v."""
43
+ fo = findorb_exe()
44
+ obs = sorted(obs, key=lambda o: o["mjd"])
45
+ with tempfile.TemporaryDirectory(prefix="orbitsift-fo-") as d:
46
+ rows = [ades.row("fit", o["mjd"], o["ra"], o["dec"], o.get("rmsRA") or sigma, o.get("rmsDec") or sigma, None, None,
47
+ None, stn=o.get("stn") or site, ast_cat=o.get("astCat") or "UNK") for o in obs]
48
+ Path(d, "obs.psv").write_text("# version=2017\n" + ades.column_line() + "\n" + "\n".join(rows) + "\n")
49
+ env = os.environ.get("ORBITSIFT_FINDORB_ENV") # a Find_Orb settings file for this run (fo -D)
50
+ p = subprocess.run([fo, "obs.psv", "-O", d] + ([f"-tE{epoch:.6f}"] if epoch else []) + (["-D", env] if env else [])
51
+ + ([f"-v{seed[0]:.6f}," + ",".join(f"{q:.12f}" for q in seed[1:])] if seed else []), cwd=d, stdin=subprocess.DEVNULL,
52
+ capture_output=True, text=True, timeout=timeout)
53
+ if p.returncode:
54
+ raise RuntimeError(f"fo exited with {p.returncode}: {(p.stdout + p.stderr)[-500:]}")
55
+ try:
56
+ cv = json.loads(Path(d, "covar.json").read_text())
57
+ tot = next(iter(json.loads(Path(d, "total.json").read_text())["objects"].values()))
58
+ txt = Path(d, "elements.txt").read_text()
59
+ except FileNotFoundError:
60
+ return None
61
+ pert = re.search(r"^# Perturbers: (\S+) .*;\s*(.*)$", txt, re.M)
62
+ if not pert or "not using" in pert[2]:
63
+ raise FileNotFoundError("Find_Orb ran without a JPL DE ephemeris: set JPL_FILENAME (and LINUX_JPL_FILENAME) in "
64
+ f"~/.find_orb/environ.dat to a DE440 file ({FINDORB_URL}#de_eph)")
65
+ R = sorted(tot["observations"]["residuals"], key=lambda r: r["JD"])
66
+ if len(R) != len(obs):
67
+ raise RuntimeError(f"fo returned {len(R)} residuals for {len(obs)} observations")
68
+ t0 = float(cv["epoch"]) # TT; TDB differs by < 2 ms
69
+ s = orbit.convert(np.array(cv["state_vect"]), t0, orbit.EQUATORIAL, orbit.BARYCENTRIC, orbit.ECLIPTIC, orbit.HELIOCENTRIC)
70
+ E = np.kron(np.eye(2), orbit.ECL.T) # ecliptic -> equatorial axes, positions and velocities
71
+ res = -np.array([[r["dRA"], r["dDec"]] for r in R]) # computed - observed, as Arc.residuals
72
+ sig = np.array([[r["sigma_1"], r["sigma_2"]] for r in R])
73
+ used = np.array([bool(r["incl"]) for r in R])
74
+ el = tot["elements"]
75
+ o = orbit.Orbit(s[:3], s[3:], t0, E @ np.array(cv["covar"]) @ E.T, float(((res[used] / sig[used]) ** 2).sum()), len(obs),
76
+ float(np.sqrt(np.mean(res ** 2))), float(np.ptp([q["mjd"] for q in obs])), res)
77
+ info = dict(backend="findorb", findorb=dict(
78
+ version=tot["Find_Orb_version_iso"][:10], ephemeris=pert[2].strip(), perturbers=pert[1], n_used=int(used.sum()),
79
+ n_rejected=int((~used).sum()), rejected=np.flatnonzero(~used).tolist(), seed=[float(cv["epoch"])] + list(cv["state_vect"]), rms_used_arcsec=el.get("rms_residual"),
80
+ weighted_rms=el.get("weighted_rms_residual"), elements_helio=dict(
81
+ epoch_jd_tt=el["epoch"], **{k: el.get(f) for k, f in NAMES.items()}, sigma={k: el.get(f + " sigma") for k, f in NAMES.items()})))
82
+ return o, info
83
+
84
+
85
+ def rebound_integrate(t0, states, years, dt_out=20.0, steps_per_jupiter=25):
86
+ """``dynamics.integrate`` with REBOUND's WHFast (corrector 11) instead of DOP853: the same bodies, masses,
87
+ initial planet states and output (dict t [yr], x, v (n_out, 5 + n, 3) ecliptic barycentric). The step is
88
+ about P_Jupiter / ``steps_per_jupiter`` and divides ``dt_out``, so samples fall on steps."""
89
+ try:
90
+ import rebound
91
+ except ImportError:
92
+ raise ValueError("REBOUND is not installed: pip install 'orbitsift[rebound]'") from None
93
+ from .dynamics import GMP, planets
94
+ states = np.atleast_2d(states)
95
+ n = len(states)
96
+ Xp, Wp = planets(t0)
97
+ sim = rebound.Simulation()
98
+ sim.G = 1.0 # masses are GM [AU^3/d^2], time in days
99
+ for m, x, v in zip(GMP, Xp, Wp):
100
+ sim.add(m=m, x=x[0], y=x[1], z=x[2], vx=v[0], vy=v[1], vz=v[2])
101
+ for x, v in zip(states[:, :3] @ orbit.ECL.T, states[:, 3:] @ orbit.ECL.T):
102
+ sim.add(x=x[0], y=x[1], z=x[2], vx=v[0], vy=v[1], vz=v[2])
103
+ sim.N_active, sim.testparticle_type = 5, 0
104
+ step = dt_out * 365.25
105
+ sim.integrator = "whfast"
106
+ sim.dt = step / np.ceil(step / (4332.59 / steps_per_jupiter))
107
+ ri = getattr(sim, "ri_whfast", None) or sim.integrator # REBOUND 4 / 5
108
+ ri.safe_mode, ri.corrector = 0, 11
109
+ te = np.arange(0, years * 365.25 + 1e-6, step)
110
+ X, V = np.empty((len(te), 5 + n, 3)), np.empty((len(te), 5 + n, 3))
111
+ for k, t in enumerate(te):
112
+ sim.integrate(t - sim.dt / 2, exact_finish_time=0) # the step that lands on t
113
+ sim.serialize_particle_data(xyz=X[k], vxvyvz=V[k])
114
+ return dict(t=te / 365.25, x=X, v=V, rebound=rebound.__version__)
115
+
116
+
117
+ DE440S = "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de440s.bsp"
118
+
119
+
120
+ def rebound_classes_run(epoch, state, cov, years=1e7, nclones=50, seed=20261103, infl=1.0, step_yr=250.0, kernel=None):
121
+ """Long REBOUND run for dynamical classes: the nominal orbit and ``nclones`` clones drawn from ``cov`` (x infl^2),
122
+ heliocentric ecliptic J2000 state [AU, AU/d] at ``epoch`` (JD TDB; Find_Orb's covariance frame). Sun with Mercury..Mars
123
+ lumped at their centre of mass, Jupiter..Neptune system barycentres, DE440 GMs and states (``kernel``: a de440s.bsp
124
+ path, default downloaded once into <cache>/de440s.bsp through ``net.fetch``). MERCURIUS (WHFast, IAS15 within 3 Hill radii), step P_Jup/25
125
+ (P_Jup/50 if the nominal q < 25 AU); barycentric elements every ``step_yr``; particles beyond 2000 AU or inside 4 AU
126
+ are removed. -> dict(a, e, i, lam, pom (n_out, n), lamN (n_out,), t_rm (n,) [yr, nan = kept], step_yr, dt_days, q0, dE)
127
+ for ``dynamics.classify``."""
128
+ try:
129
+ import rebound
130
+ except ImportError:
131
+ raise ValueError("REBOUND is not installed: pip install 'orbitsift[rebound]'") from None
132
+ from jplephem.spk import SPK
133
+ if kernel is None: # through net.fetch: contact header and request log
134
+ from . import config, net
135
+ kernel = config.cache_dir() / "de440s.bsp"
136
+ if not kernel.exists():
137
+ net.save(kernel, net.fetch(DE440S, timeout=1800))
138
+ kernel = str(kernel)
139
+ C = (np.asarray(cov, float) + np.asarray(cov, float).T) / 2
140
+ w, V = np.linalg.eigh(C)
141
+ C = V @ np.diag(np.clip(w, 0, None)) @ V.T * infl ** 2
142
+ x0 = np.asarray(state, float)
143
+ clones = np.vstack([x0, np.random.default_rng(seed).multivariate_normal(x0, C, nclones)])
144
+ au, eps = 149597870.7, np.radians(84381.448 / 3600)
145
+ R = np.array([[1, 0, 0], [0, np.cos(eps), np.sin(eps)], [0, -np.sin(eps), np.cos(eps)]])
146
+ GM = {10: 2.9591220828411951e-04, 1: 4.9125001948893182e-11, 2: 7.2434523326441187e-10, 3: 8.9970113929473456e-10,
147
+ 4: 9.5495488297258119e-11, 5: 2.8253458252257917e-07, 6: 8.4597059933762903e-08, 7: 1.2920265649682399e-08,
148
+ 8: 1.5243573478851939e-08} # DE440 [AU^3/d^2]: Sun, Mercury..Mars, Jupiter..Neptune systems
149
+ k = SPK.open(kernel)
150
+ try:
151
+ def st(b):
152
+ p, v = k[0, b].compute_and_differentiate(epoch)
153
+ return np.concatenate([R @ p, R @ v]) / au
154
+ S = {b: st(b) for b in GM}
155
+ finally:
156
+ k.close()
157
+ inner = [10, 1, 2, 3, 4]
158
+ m0 = sum(GM[b] for b in inner)
159
+ s0 = sum(GM[b] * S[b] for b in inner) / m0
160
+ sim = rebound.Simulation()
161
+ sim.G = 1.0
162
+ sim.add(m=m0, x=s0[0], y=s0[1], z=s0[2], vx=s0[3], vy=s0[4], vz=s0[5])
163
+ for b in (5, 6, 7, 8):
164
+ s = S[b]
165
+ sim.add(m=GM[b], x=s[0], y=s[1], z=s[2], vx=s[3], vy=s[4], vz=s[5])
166
+ sim.N_active, sim.testparticle_type = 5, 0
167
+ for x in clones:
168
+ s = x + S[10]
169
+ sim.add(x=s[0], y=s[1], z=s[2], vx=s[3], vy=s[4], vz=s[5])
170
+ sim.move_to_com()
171
+ o5 = sim.particles[5].orbit(primary=sim.particles[0])
172
+ q0 = o5.a * (1 - o5.e)
173
+ sim.integrator = "mercurius"
174
+ sim.dt = 4332.59 / (50.0 if q0 < 25 else 25.0)
175
+ sim.integrator.r_crit_hill = 3
176
+ alive = list(range(len(clones))) # alive[k] = clone index of sim.particles[5 + k]
177
+ E0 = sim.energy()
178
+ step = step_yr * 365.25
179
+ nout, n = int(years * 365.25 / step) + 1, len(clones)
180
+ A = {q: np.full((nout, n), np.nan, np.float32) for q in ("a", "e", "i", "lam", "pom")}
181
+ lamN = np.full(nout, np.nan, np.float32)
182
+ t_rm = np.full(n, np.nan)
183
+ for j in range(nout):
184
+ sim.integrate(j * step, exact_finish_time=0)
185
+ bc = sim.com()
186
+ lamN[j] = sim.particles[4].orbit(primary=bc).l
187
+ gone = []
188
+ for kk, i in enumerate(alive):
189
+ p = sim.particles[5 + kk]
190
+ h = p - sim.particles[0]
191
+ r = (h.x ** 2 + h.y ** 2 + h.z ** 2) ** .5
192
+ if r > 2000 or r < 4:
193
+ gone.append(kk)
194
+ t_rm[i] = sim.t / 365.25
195
+ continue
196
+ o = p.orbit(primary=bc)
197
+ A["a"][j, i], A["e"][j, i], A["i"][j, i], A["lam"][j, i], A["pom"][j, i] = o.a, o.e, np.degrees(o.inc), o.l, o.pomega
198
+ for kk in sorted(gone, reverse=True):
199
+ sim.remove(5 + kk)
200
+ del alive[kk]
201
+ if sim.N <= 5:
202
+ break
203
+ return dict(A, lamN=lamN, t_rm=t_rm, step_yr=step_yr, dt_days=sim.dt, q0=q0, dE=abs((sim.energy() - E0) / E0),
204
+ rebound=rebound.__version__)
orbitsift/extract.py ADDED
@@ -0,0 +1,148 @@
1
+ """Single-epoch source catalogue from DECam Community Pipeline images (``orbitsift extract``).
2
+
3
+ For exposures that the NSC DR2 does not cover (DECam after 2019, or programmes it left out): each CCD of a calibrated
4
+ image (``ooi``) is masked with its data-quality file (``ood``), the background and noise are taken on a 128-px mesh,
5
+ sources are 5-sigma peaks of the image smoothed with a sigma = 1.6 px Gaussian that are local maxima over 5x5 px and
6
+ at least 2 px from a masked pixel; positions are the first moments in 5x5 px (through the CP WCS), magnitudes are 4-px
7
+ aperture sums on the CP zero point (MAGZERO), widths come from the second moments in 9x9 px.
8
+
9
+ DQ code 7 ("diff detect": a transient the CP found by differencing the exposure against the others of the same field,
10
+ which is exactly what a moving object is) is kept by default (``keep_dq7``); rows next to such a pixel are tagged
11
+ ``dq7``. Measured on 3,830 DECam exposures of 2020-2026 (2,988 random ones and 842 of one field) against 894 predictions
12
+ of known movers (survey, 14 Nov 2026): 136 mover detections exist only with code 7 kept, against 492 without it (21.7%
13
+ of all; 0.0 in the controls). The flag sits on movers in same-night same-band repeat sequences: by repeats within 1.1 deg,
14
+ 0 of 306 detections at 0, 0 of 101 at 1-3, 4 at 4-9, 132 of 183 at 10 or more; down to the detection limit (35% of the
15
+ movers detected at S/N 5-8 there). It also appears without repeats in 2016-17 CP versions (on 63-74% of the CCD masks of
16
+ one field). An extraction that masks every non-zero code loses those detections; masking code 7 (``keep_dq7=False``,
17
+ ``extract --mask-dq7``) is for comparisons with catalogues built that way.
18
+
19
+ Rows are not cut: artefacts (``fwhm`` well below the exposure's ``fwhm_med``, ``nbad`` > 0) are for the user to drop.
20
+ First moments lock to the pixel grid (scatter ~0.05" per axis on bright stars); exposures without MAGZERO give
21
+ magnitudes of nan.
22
+ """
23
+ import gzip
24
+
25
+ import numpy as np
26
+
27
+ PIX = 0.263 # DECam pixel ["]
28
+ COLUMNS = ("ra", "dec", "mag", "magerr", "fwhm", "nbad", "ccd", "dq7")
29
+ _DIAMOND = [(a, b) for a in range(-2, 3) for b in range(-2 + abs(a), 3 - abs(a))]
30
+
31
+
32
+ def mesh_up(a, ny, nx, mesh):
33
+ """Mesh values (one per ``mesh`` x ``mesh`` block, the last block of a row or column may be partial) -> full ny x nx
34
+ map, bilinear between the true block centres and constant outside the outer centres. (scipy.ndimage.zoom, used up to
35
+ Nov 2026, put mesh 0 on pixel 0 and the last mesh on the last pixel: on a 4094 x 2046 DECam CCD with a 128 px mesh
36
+ the map was displaced by up to 189 px towards the high-x / high-y edges.)"""
37
+ def c(n, k):
38
+ s = np.arange(k) * mesh
39
+ return (s + np.minimum(s + mesh, n) - 1) / 2
40
+ t = np.array([np.interp(np.arange(nx), c(nx, a.shape[1]), r) for r in a])
41
+ return np.array([np.interp(np.arange(ny), c(ny, a.shape[0]), col) for col in t.T]).T
42
+
43
+
44
+ def background_map(img, bad, mesh=128):
45
+ """Background and noise maps of an image: median and robust sigma on a ``mesh`` px grid, bilinear (``mesh_up``)."""
46
+ ny, nx = img.shape
47
+ g = np.where(bad, np.nan, img)
48
+ by, bx = -(-ny // mesh), -(-nx // mesh) # ceil: the partial last block row / column is sampled too
49
+ gp = np.full((by * mesh, bx * mesh), np.nan, np.float32)
50
+ gp[:ny, :nx] = g
51
+ blk = gp.reshape(by, mesh, bx, mesh).transpose(0, 2, 1, 3).reshape(by, bx, -1)
52
+ med = np.nanmedian(blk, -1)
53
+ rms = 1.4826 * np.nanmedian(np.abs(blk - med[..., None]), -1)
54
+ med, rms = (np.where(np.isfinite(a), a, np.nanmedian(a)) for a in (med, rms))
55
+ return mesh_up(med, ny, nx, mesh), mesh_up(rms, ny, nx, mesh)
56
+
57
+
58
+ def detect(img, bad, nsig=5.0, mesh=128, r_ap=4.0):
59
+ """Sources of one CCD -> x, y (0-based px), aperture flux, its error, masked pixels in the aperture, FWHM [px]."""
60
+ from scipy import ndimage as nd
61
+ ny, nx = img.shape
62
+ back, noise = background_map(img, bad, mesh)
63
+ sub = np.where(bad, 0.0, img - back).astype(np.float32)
64
+ sm = nd.gaussian_filter(sub, 1.6)
65
+ smn = noise / (2 * np.sqrt(np.pi) * 1.6)
66
+ c = sm > nsig * smn
67
+ c[:6] = False
68
+ c[ny - 6:] = False
69
+ c[:, :6] = False
70
+ c[:, nx - 6:] = False
71
+ y, x = np.nonzero(c)
72
+ for dy, dx in [(0, 1), (0, -1), (1, 0), (-1, 0)] + [(a, b) for a in range(-2, 3) for b in range(-2, 3) if abs(a) + abs(b) > 1]:
73
+ k = sm[y, x] >= sm[y + dy, x + dx] # a local maximum over 5x5 px
74
+ y, x = y[k], x[k]
75
+ for dy, dx in _DIAMOND: # no masked pixel within 2 px
76
+ k = ~bad[y + dy, x + dx]
77
+ y, x = y[k], x[k]
78
+ oy, ox = np.mgrid[-2:3, -2:3]
79
+ w = np.clip(sub[y[:, None, None] + oy, x[:, None, None] + ox], 0, None)
80
+ ws = w.sum((1, 2)) + 1e-9
81
+ mx, my = (w * ox).sum((1, 2)) / ws, (w * oy).sum((1, 2)) / ws
82
+ qy, qx = np.mgrid[-4:5, -4:5]
83
+ w9 = np.clip(sub[y[:, None, None] + qy, x[:, None, None] + qx], 0, None)
84
+ w9s = w9.sum((1, 2)) + 1e-9
85
+ m9x, m9y = (w9 * qx).sum((1, 2)) / w9s, (w9 * qy).sum((1, 2)) / w9s
86
+ s2 = ((w9 * (qx - m9x[:, None, None]) ** 2).sum((1, 2)) + (w9 * (qy - m9y[:, None, None]) ** 2).sum((1, 2))) / (2 * w9s)
87
+ fwhm_px = 2.3548 * np.sqrt(np.clip(s2, 0, None))
88
+ R = int(np.ceil(r_ap))
89
+ ay, ax = np.mgrid[-R:R + 1, -R:R + 1]
90
+ m = ay ** 2 + ax ** 2 <= r_ap ** 2
91
+ ay, ax = ay[m], ax[m]
92
+ flux = sub[y[:, None] + ay, x[:, None] + ax].sum(1)
93
+ nbad = bad[y[:, None] + ay, x[:, None] + ax].sum(1)
94
+ return x + mx, y + my, flux, noise[y, x] * np.sqrt(m.sum()), nbad, fwhm_px
95
+
96
+
97
+ def extract(ooi, ood, log=print, keep_dq7=True):
98
+ """Catalogue of one CP exposure (or of the CCDs a file holds): ``ooi`` image and ``ood`` data-quality file, same HDUs.
99
+ Pixels with a non-zero DQ code are masked, except code 7 while ``keep_dq7`` (see the module notes).
100
+ -> (array (n, 8) with COLUMNS; fwhm in arcsec, dq7 0/1), dict(mjd (mid-exposure), zp, filt, exptime, expnum, dq7_kept))."""
101
+ import warnings
102
+
103
+ from astropy.io import fits
104
+ from astropy.wcs import WCS
105
+ warnings.simplefilter("ignore")
106
+ rows = []
107
+ with fits.open(ooi, memmap=False) as F, fits.open(ood, memmap=False) as Q:
108
+ h0 = F[0].header
109
+ zp = h0.get("MAGZERO", np.nan)
110
+ mjd = h0["MJD-OBS"] + h0["EXPTIME"] / 2 / 86400
111
+ for k, hdu in enumerate(F[1:], 1):
112
+ try: # a CCD that cannot be decompressed loses that CCD only
113
+ if hdu.data is None:
114
+ continue
115
+ img = hdu.data.astype(np.float32)
116
+ q = Q[k].data
117
+ bad = ~np.isfinite(img) | ((q > 0) & ((q != 7) | (not keep_dq7)))
118
+ x, y, fl, fe, nb, fw = detect(np.where(bad, 0, img), bad)
119
+ ix, iy = np.rint(x).astype(int), np.rint(y).astype(int)
120
+ t7 = np.zeros(len(x), bool)
121
+ for a, b in _DIAMOND:
122
+ t7 |= q[np.clip(iy + a, 0, q.shape[0] - 1), np.clip(ix + b, 0, q.shape[1] - 1)] == 7
123
+ except Exception as e:
124
+ log(f"{ooi}: CCD {k} skipped: {e!r}")
125
+ continue
126
+ ok = fl > 0
127
+ ra, dec = WCS(hdu.header).all_pix2world(x[ok], y[ok], 0)
128
+ rows.append(np.c_[ra, dec, zp - 2.5 * np.log10(fl[ok]), 1.0857 * fe[ok] / fl[ok], fw[ok] * PIX, nb[ok],
129
+ np.full(ok.sum(), hdu.header.get("CCDNUM", k)), t7[ok]])
130
+ a = np.concatenate(rows) if rows else np.zeros((0, len(COLUMNS)))
131
+ return a, dict(mjd=float(mjd), zp=float(zp), filt=str(h0.get("FILTER", "?")).split()[0], exptime=float(h0["EXPTIME"]),
132
+ expnum=h0.get("EXPNUM"), dq7_kept=bool(keep_dq7))
133
+
134
+
135
+ def summarize(a, meta):
136
+ """Adds n, depth5 (median magnitude at magerr 0.18-0.24, i.e. S/N ~5) and fwhm_med (median width at magerr < 0.05)."""
137
+ sel, br = (a[:, 3] > 0.18) & (a[:, 3] < 0.24) & np.isfinite(a[:, 2]), a[:, 3] < 0.05
138
+ meta.update(n=int(len(a)), depth5=float(np.median(a[sel, 2])) if sel.sum() > 20 else None,
139
+ fwhm_med=float(np.median(a[br, 4])) if br.sum() > 20 else None)
140
+ return meta
141
+
142
+
143
+ def write_csv(a, path):
144
+ """Rows as gzipped CSV (ra, dec to 1e-6 deg, mag and magerr to 1e-3, fwhm to 0.01")."""
145
+ with gzip.open(path, "wt") as f:
146
+ f.write(",".join(COLUMNS) + "\n")
147
+ for r in a:
148
+ f.write(f"{r[0]:.6f},{r[1]:.6f},{r[2]:.3f},{r[3]:.3f},{r[4]:.2f},{int(r[5])},{int(r[6])},{int(r[7])}\n")
orbitsift/growth.py ADDED
@@ -0,0 +1,224 @@
1
+ """Multi-year growth: the second stage of the survey's DES-style linker (2026 pilot, frozen rule A2; see docs/guide-multiyear.md).
2
+
3
+ Each seed (a few rows and a start gamma, gamma-dot from ``multiyear.seeds``) is grown over all years of a catalogue
4
+ (``multiyear.catalogue``): fit of the seed rows; rows of the other nights inside the seed's error ellipse, each fitted with
5
+ the seed; rows of other seasons that agree on (gamma, gamma-dot) grouped and fitted together; then attachment of every other
6
+ night with the joint orbit, outlier rejection and the final rule (nights, ARCCUT, chi2/nu, bound orbit in the distance box).
7
+ The work is the compiled kernel ``orbitsift_native.grow`` (native/src/grow.rs: the survey's growth binary, portable build);
8
+ there is no Python fallback.
9
+
10
+ Steps, each one function, arrays in and out (nothing here reads or writes files or touches the network):
11
+
12
+ 1. ``earth_table``: the geocentre on a 0.125-day TDB grid from a JPL DE440s kernel (as the survey made it).
13
+ 2. ``run``: one growth pass -> candidate sets (before the final cuts) and counters. ``growlib.run`` of the survey.
14
+ 3. ``grow``: seed tables + catalogue -> candidates after the frozen cuts and the duplicate rule (``pl.py grow``), with
15
+ ``control='shiftN'`` the survey's shift controls (``shift``: every night moved rigidly by 20-60" per axis).
16
+ 4. ``preset('a2')``: the frozen parameters, from presets/a2.json, checked against the sha256 recorded in it.
17
+ """
18
+ import hashlib
19
+ import json
20
+ from math import exp, fsum
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+
25
+ from ._native import lib
26
+
27
+ AS = np.pi / 180 / 3600
28
+ TDB = 69.184 / 86400 # TT - UTC [d] over 2012-2019 (the survey's constant; TDB - TT is below 2 ms)
29
+ # GM of the Sun and the planet systems [au^3 / d^2] (DE440); their exact sum is the survey's mu
30
+ GM = (2.9591220828411956e-04, 4.9125001948893182e-11, 7.2434523326441187e-10, 8.9970113929473466e-10, 9.5495488297258119e-11,
31
+ 2.8253458252257917e-07, 8.4597059933762903e-08, 1.2920265649682399e-08, 1.5243573478851939e-08, 2.1750964648933581e-12)
32
+ # parameters in the order the kernel reads them (growlib.PAR of the survey: the pilot's start values; A2 overrides some)
33
+ PAR = dict(gmin=1 / 80, gmax=1 / 25, # distance box [1/au], as the seed stage
34
+ kgate=4.0, rcap=1800.0, # seed error ellipse: sigmas; largest semi-axis searched [arcsec]
35
+ pad=1.0, # arcsec added in quadrature to the gate of the seed stage (linear motion inside a night)
36
+ dmag=1.0, # |V - median V of the seed / of the members|
37
+ nrms4=2.0, # sqrt(chi2 / 2N) of seed + one row
38
+ kclu=4.0, minfar=2, # same (gamma, gamma-dot) within kclu sigmas; far nights needed before the joint fit
39
+ fardt=150.0, # days from the middle of the seed: a row beyond this is "another season"
40
+ katt=3.5, attfloor=0.5, # attachment with the joint orbit: sigmas, floor [arcsec]
41
+ rcapatt=120.0, # arcsec: nights whose prediction is worse than this are not searched with the joint orbit
42
+ npass=3, krej=3.5, # attachment passes; outlier rejection [sigmas]
43
+ nfinal=7, chi2max=4.0, arccut=183.0, # final rule (DES Y6): distinct nights, chi2 / nu, shortest arc after removing one night [d]
44
+ cell=0.02, maxc=20000, # grid cell [deg]; candidate rows per seed (cap, counted in capc)
45
+ nthreads=0, fitonly=0, mu=0.0, bmargin=1.05, # nthreads: not read (see run's threads); mu 0 = sum of GM
46
+ sgmax=1e9, minarc=0.0, # seed filter: sigma(gamma) / gamma of the seed fit, seed arc [d]
47
+ maxmem=0, # grouping: at most this many partners of a centre go to the joint fit (nearest in gamma, gamma-dot); 0 = all
48
+ rcapmin=0.0) # a seed with more than maxc rows in its gate is searched again with rcap halved, down to this [arcsec]; 0 = off
49
+ FINAL = dict(fchi=4.0, pfa=1.0, rawgate=0) # applied by grow: chi2/nu limit, P_chance limit, every row in the seed gate
50
+ STATS = ("rows", "nights", "seeds", "fit3", "reach", "capskip", "tested", "fit4", "quads", "capc", "centres", "joint", "scans",
51
+ "finals", "out", "ns_gate", "ns_fit4", "ns_clu", "ns_joint", "shrunk", "memcut", "ns_load")
52
+ PRESETS = Path(__file__).parent / "presets"
53
+
54
+
55
+ def _need():
56
+ if lib is None or not hasattr(lib, "grow"):
57
+ raise RuntimeError("the growth stage needs the compiled kernels: pip install ./native (orbitsift-native with grow)")
58
+
59
+
60
+ # ---------------------------------------------------------------- preset
61
+ def rule_sha(rule):
62
+ return hashlib.sha256(json.dumps(rule, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
63
+
64
+
65
+ def preset(name):
66
+ """A frozen parameter set from presets/<name>.json -> its dict; its 'rule' must hash to the recorded 'rule_sha256'."""
67
+ f = PRESETS / f"{str(name).lower()}.json"
68
+ if not f.exists():
69
+ raise ValueError(f"unknown preset {name!r} (have: {', '.join(sorted(p.stem for p in PRESETS.glob('*.json')))})")
70
+ p = json.loads(f.read_text())
71
+ if rule_sha(p["rule"]) != p["rule_sha256"]:
72
+ raise ValueError(f"{f}: the rule does not match its recorded sha256 (edited?)")
73
+ return p
74
+
75
+
76
+ # ---------------------------------------------------------------- earth
77
+ def earth_table(kernel, t0=56000.0, t1=58950.0, step=0.125):
78
+ """Geocentre (barycentric equatorial au, au/d) on the TDB grid arange(t0, t1, step) from a JPL kernel (DE440s .bsp) ->
79
+ dict(t, P, V, GM). The survey's table (deslink_pilot truth.py) is this one with the defaults."""
80
+ from jplephem.spk import SPK
81
+ au = 149597870.7
82
+ t = np.arange(t0, t1, step)
83
+ k = SPK.open(str(kernel))
84
+ try:
85
+ p, v = k[0, 3].compute_and_differentiate(t + 2400000.5)
86
+ p2, v2 = k[3, 399].compute_and_differentiate(t + 2400000.5)
87
+ finally:
88
+ k.close()
89
+ return dict(t=t, P=((p + p2) / au).T, V=((v + v2) / au).T, GM=fsum(GM)) # = the survey's sum() (compensated since Python 3.12)
90
+
91
+
92
+ # ---------------------------------------------------------------- one pass
93
+ def _r(x, f):
94
+ return float(format(x, f)) # the precision of the survey binary's text output, so its cuts see the same numbers
95
+
96
+
97
+ def run(cat, seeds, earth, par=None, threads=4):
98
+ """One growth pass. cat = dict(ra, dec [deg], mjd [UTC], sig [arcsec], V, night [int labels], exp [int], lvl (0 = loader
99
+ row; optional)); seeds = list of (row indices, gamma0, gammadot0); earth = earth_table(). -> (candidate sets, counters).
100
+ A set: seed (index), rows (catalogue indices), q, tref, z, chi2, nights, arccut, rms [arcsec], fpr (expected chance
101
+ attachments), chi2nu."""
102
+ _need()
103
+ p = dict(PAR, **(par or {}))
104
+ p["mu"] = p["mu"] or earth["GM"]
105
+ _, night = np.unique(cat["night"], return_inverse=True)
106
+ so = np.concatenate([[0], np.cumsum([len(s[0]) for s in seeds])]).astype("<u8")
107
+ f8 = lambda a: np.ascontiguousarray(a, "<f8")
108
+ i4 = lambda a: np.ascontiguousarray(a, "<i4")
109
+ T, P, V = earth["t"], earth["P"], earth["V"]
110
+ rows = [f8(cat["ra"]), f8(cat["dec"]), f8(np.asarray(cat["mjd"]) + TDB), f8(np.asarray(cat["sig"]) * AS), f8(cat["V"])]
111
+ irows = [i4(night), i4(cat["exp"]), i4(cat.get("lvl", np.zeros(len(night))))]
112
+ srow = i4(np.concatenate([np.asarray(s[0]) for s in seeds] or [np.zeros(0)]))
113
+ out, st = lib.grow(rows, irows, len(np.unique(night)), so, srow, f8([s[1] for s in seeds]), f8([s[2] for s in seeds]),
114
+ [float(p[k]) for k in PAR], float(T[0]), float(T[1] - T[0]), f8(P).ravel(), f8(V).ravel(), int(threads))
115
+ res = []
116
+ for s, r, q, tref, z, chi, n, arc, rms, fpr in out:
117
+ c = dict(seed=s, rows=[int(v) for v in r], q=[_r(v, ".17e") for v in q], tref=_r(tref, ".9f"), z=[_r(v, ".15e") for v in z],
118
+ chi2=_r(chi, ".6e"), nights=n, arccut=_r(arc, ".4f"), rms=_r(rms, ".5f"), fpr=_r(fpr, ".6e"))
119
+ c["chi2nu"] = c["chi2"] / (2 * len(c["rows"]) - 6)
120
+ res.append(c)
121
+ return res, dict(zip(STATS, st))
122
+
123
+
124
+ def dedup(cands):
125
+ """The duplicate rule: best first (more nights, then lower chi2 / nu); a candidate sharing >= 2 rows with a kept one is dropped."""
126
+ keep, owner = [], {}
127
+ for c in sorted(cands, key=lambda c: (-c["nights"], c["chi2nu"], c["rows"])):
128
+ cnt = {}
129
+ for i in c["rows"]:
130
+ for k in owner.get(i, ()):
131
+ cnt[k] = cnt.get(k, 0) + 1
132
+ if any(v >= 2 for v in cnt.values()):
133
+ continue
134
+ for i in c["rows"]:
135
+ owner.setdefault(i, []).append(len(keep))
136
+ keep.append(c)
137
+ return keep
138
+
139
+
140
+ def shift(cat, seed, lo=20.0, hi=60.0):
141
+ """Control: every night moved rigidly by lo-hi arcsec per axis (random sign and size per night and seed; the same shift
142
+ for a night wherever it is applied, so seeds and catalogue of a control agree). Returns a new dict."""
143
+ c = dict(cat, ra=np.array(cat["ra"], float), dec=np.array(cat["dec"], float))
144
+ for nt in np.unique(c["night"]):
145
+ g = np.random.default_rng([seed, int(nt)])
146
+ s = g.choice([-1, 1], 2) * g.uniform(lo, hi, 2)
147
+ m = c["night"] == nt
148
+ c["ra"][m] = (c["ra"][m] + s[0] / 3600 / np.maximum(np.cos(np.radians(c["dec"][m])), .05)) % 360
149
+ c["dec"][m] += s[1] / 3600
150
+ return c
151
+
152
+
153
+ def control_seed(control):
154
+ """'shift1' -> 1; None / 'real' -> None."""
155
+ if control in (None, "", "real"):
156
+ return None
157
+ if not (str(control).startswith("shift") and str(control)[5:].isdigit()):
158
+ raise ValueError(f"control {control!r}: expected shiftN (N a positive integer)")
159
+ return int(str(control)[5:])
160
+
161
+
162
+ def pchance(c, nfree):
163
+ """P(Poisson(fpr) >= nights - nfree): chance that the nights beyond the nfree that define the orbit (seed nights + minfar)
164
+ are all chance attachments."""
165
+ k = c["nights"] - nfree
166
+ mu = c["fpr"]
167
+ t = s = exp(-mu)
168
+ if k <= 0:
169
+ return 1.0
170
+ for j in range(1, k):
171
+ t *= mu / j
172
+ s += t
173
+ return max(0.0, 1.0 - s)
174
+
175
+
176
+ # ---------------------------------------------------------------- seeds + catalogue -> candidates
177
+ def unique_seeds(tables):
178
+ """Seed tables (dicts off, key, g, gd; in the order to read them) -> [(sorted row keys, g, gd)], a row set once (first)."""
179
+ u = {}
180
+ for z in tables:
181
+ k, off, g, gd = z["key"], z["off"], z["g"], z["gd"]
182
+ for i in range(len(g)):
183
+ r = tuple(sorted(k[off[i]:off[i + 1]].tolist()))
184
+ u.setdefault(r, (r, float(g[i]), float(gd[i])))
185
+ return list(u.values())
186
+
187
+
188
+ def grow(cat, tables, earth, par=None, control=None, threads=4):
189
+ """The growth of a region (``pl.py grow`` of the survey). cat: ``multiyear.catalogue`` (sorted by key); tables: seed
190
+ tables of the same mode, in the survey's order (``multiyear.seed_tables``); par: growth parameters plus fchi, pfa,
191
+ rawgate (FINAL); control: None or 'shiftN' (the catalogue is shifted here; the seeds must be that control's).
192
+ -> dict(cands (after the final cuts and the duplicate rule, each with ids, det, gamma, pch), sets (every set before the
193
+ cuts: n, chi, fpr, pch, rms), stat, nseeds, missing (seeds with a row not in the catalogue), nraw)."""
194
+ par = dict(par or {})
195
+ fin = {k: par.pop(k, v) for k, v in FINAL.items()}
196
+ S = unique_seeds(tables)
197
+ n = control_seed(control)
198
+ if n is not None:
199
+ cat = shift(cat, n)
200
+ order = np.argsort(cat["key"])
201
+ ids = cat["key"][order]
202
+ seeds, miss = [], 0
203
+ for rows, g, gd in S:
204
+ r = np.array(rows, np.uint64)
205
+ j = np.minimum(np.searchsorted(ids, r), len(ids) - 1)
206
+ if (ids[j] != r).any():
207
+ miss += 1
208
+ continue
209
+ seeds.append((order[j], g, gd))
210
+ if fin["rawgate"] and "lvl" in cat:
211
+ cat = dict(cat, lvl=np.zeros_like(cat["lvl"]))
212
+ out, st = run(cat, seeds, earth, par, threads)
213
+ mf = int(dict(PAR, **par)["minfar"])
214
+ for o in out:
215
+ o["pch"] = pchance(o, len(np.unique(cat["night"][seeds[o["seed"]][0]])) + mf)
216
+ sets = [dict(n=o["nights"], chi=o["chi2nu"], fpr=o["fpr"], pch=o["pch"], rms=o["rms"]) for o in out]
217
+ keep = dedup([o for o in out if o["chi2nu"] <= fin["fchi"] and o["pch"] <= fin["pfa"]])
218
+ for o in keep:
219
+ r = np.array(o["rows"])
220
+ o["ids"] = [int(v) for v in cat["key"][r]]
221
+ o["det"] = [[float(cat["ra"][i]), float(cat["dec"][i]), float(cat["mjd"][i]), float(cat["V"][i])] for i in r]
222
+ o["gamma"] = o["q"][4]
223
+ return dict(cands=keep, sets=sets, stat=st, nseeds=len(seeds), missing=miss, nraw=len(out), control=control or "real",
224
+ par=dict(par, **fin))