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,369 @@
1
+ """SMOKA (Subaru HSC and Suprime-Cam raw frames). Downloading needs a free account and a request by mail whose subject is
2
+ the account password, so it is never done here: ``request`` writes the mail bodies (frame ids + dates only; SMOKA id from
3
+ the argument or $SMOKA_ID, never a password) for the user to send. Once the files are in the SMOKA folder
4
+ ($ORBITSIFT_SMOKA_DIR, default <cache>/smoka; FRAMEID.fits or .fits.gz, calibrations included), ``fetch`` reduces the CCDs
5
+ where the clones fall: per amplifier overscan (row median of the serial overscan, 31-row smoothed) and gain, then for HSC the
6
+ median of the BIAS and normalised median of the DOMEFLAT/SKYFLAT frames of the same DET-ID (and filter) found in the
7
+ folder; the amplifiers' data sections are joined (no overscan columns), the rough header WCS is refined on Gaia
8
+ (``gaia_refine``: scale, rotation, 1-2' offset) and ``extend.Frame`` ties the cut to Gaia.
9
+
10
+ The HSC CCDs to request are chosen from one public header of the shot (SMOKA info page, by frame id + date: no
11
+ coordinates are sent) and the focal-plane layout in hsc_geom.json, rotated to that header's CD matrix."""
12
+ import datetime
13
+ import gzip
14
+ import html
15
+ import json
16
+ import os
17
+ import re
18
+ import urllib.parse
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+
23
+ from .. import config, net
24
+ from . import PAD, box, cache, cached_json, stale, write_cut
25
+
26
+ INSTRUMENTS = ("Subaru/HSC", "Subaru/SuprimeCam")
27
+ SITE = "T09" # Subaru Telescope (568 is the generic Maunakea code)
28
+ PIX = 0.168
29
+ SMOKA = "https://smoka.nao.ac.jp/"
30
+ GEOM = json.loads(Path(__file__).with_name("hsc_geom.json").read_text())
31
+
32
+
33
+ def folder():
34
+ return Path(os.environ.get("ORBITSIFT_SMOKA_DIR") or config.cache_dir() / "smoka")
35
+
36
+
37
+ def local(fid):
38
+ """The local file of a frame id, or None."""
39
+ for ext in (".fits", ".fits.gz", ".fits.fz"):
40
+ p = folder() / (fid + ext)
41
+ if p.exists():
42
+ return p
43
+ return None
44
+
45
+
46
+ def utdate(mjd):
47
+ return str(datetime.date(1858, 11, 17) + datetime.timedelta(days=int(np.floor(mjd))))
48
+
49
+
50
+ def frames(exp, slots=None):
51
+ """Frame ids of an exposure: HSC slots '000'..'155' (visit + first digit, CCD 2 digits); Suprime-Cam the 10 CCDs."""
52
+ if exp["inst"] == "HSC":
53
+ e = int(exp["id"][4:10])
54
+ return [f"HSCA{e + int(k[0]):06d}{k[1:]}" for k in (slots or sorted(GEOM))]
55
+ return ["SUPA" + exp["id"][4:-1] + str(c) for c in range(10)] # FRAMEID is SUPA..., the exposure id SUPE... (SMOKA drops SUPE requests)
56
+
57
+
58
+ def exposures(rows, V=None):
59
+ out = {}
60
+ for r in rows:
61
+ ti = r["Telescope/Instrument"]
62
+ if ti in INSTRUMENTS and float(r["Exptime"]) >= 30:
63
+ inst = ti.split("/")[1]
64
+ x = out.setdefault(r["Image"], dict(archive="smoka", id=r["Image"], mjd=float(r["MJD"]), exptime=float(r["Exptime"]),
65
+ filt=r["Filter"], inst=inst, site=SITE, date=utdate(float(r["MJD"]))))
66
+ if not any(local(f) for f in frames(x)):
67
+ x["listed"] = ("SMOKA (free account): orbitsift.archives.smoka.request(...) writes the mail body; once the frames "
68
+ "are in the SMOKA folder, extend reduces them")
69
+ return list(out.values())
70
+
71
+
72
+ def header(fid, date):
73
+ """Public original header of a SMOKA frame (info page, by frame id + date), cached -> dict or {}."""
74
+ def get():
75
+ t = net.fetch(f"{SMOKA}info.jsp?{urllib.parse.urlencode(dict(frameid=fid, date_obs=date, i=0))}", timeout=120).decode(errors="replace")
76
+ m = re.search(r"Original FITS Header.*?<pre[^>]*>(.*?)</pre>", t, re.S)
77
+ h = {}
78
+ for line in (html.unescape(re.sub(r"<[^>]+>", "", m.group(1))).splitlines() if m else []):
79
+ if len(line) > 9 and line[8] == "=":
80
+ v = line[10:].split(" /")[0].strip()
81
+ try:
82
+ v = float(v)
83
+ except ValueError:
84
+ v = v.strip("'").strip()
85
+ h[line[:8].strip()] = v
86
+ return h
87
+ return cached_json(cache("smoka", "hdr", f"{fid}_{date}.json"), get)
88
+
89
+
90
+ def slots(exp, pos, margin=30.0):
91
+ """HSC CCD slots holding a clone (within margin" + 2.5% of the boresight distance, for the header's missing distortion),
92
+ from the shot's header WCS and the focal-plane layout. None if no header could be read."""
93
+ for k0 in ("000", "100", "012", "112", "020", "120"):
94
+ h = header(frames(exp, [k0])[0], exp["date"])
95
+ if h.get("CD1_1") is not None and int(h.get("DET-ID", -1)) == GEOM[k0]["det"]:
96
+ break
97
+ else:
98
+ return None
99
+ ra, dec = pos(exp["mjd"] + exp["exptime"] / 2 / 86400, SITE)
100
+ cd = np.array([[h["CD1_1"], h["CD1_2"]], [h["CD2_1"], h["CD2_2"]]]) @ np.linalg.inv(np.array(GEOM[k0]["cd"]))
101
+ a, d, a0, d0 = (np.radians(np.asarray(v, float)) for v in (ra, dec, h["CRVAL1"], h["CRVAL2"]))
102
+ c = np.sin(d) * np.sin(d0) + np.cos(d) * np.cos(d0) * np.cos(a - a0)
103
+ std = np.degrees(np.vstack([np.cos(d) * np.sin(a - a0) / c, (np.sin(d) * np.cos(d0) - np.cos(d) * np.sin(d0) * np.cos(a - a0)) / c]))
104
+ r = float(np.degrees(np.arccos(np.clip(c.max(), -1, 1)))) * 3600
105
+ m = (margin + 0.025 * r) / PIX
106
+ out = []
107
+ for k, g in GEOM.items():
108
+ x, y = np.linalg.solve(cd @ np.array(g["cd"]), std) + np.array(g["crpix"])[:, None]
109
+ if ((x > 0.5 - m) & (x < g["nax"][0] + 0.5 + m) & (y > 0.5 - m) & (y < g["nax"][1] + 0.5 + m)).any():
110
+ out.append(k)
111
+ return sorted(out)
112
+
113
+
114
+ def search(date, typ, band=""):
115
+ """SMOKA HSC catalogue by date and type only -> rows [FRAMEID, DATE_OBS, DATA_TYPE, FILTER, EXPTIME, ..., EXP_ID]."""
116
+ body = (f"action=Search&instruments=HSC&obs_cat=Science+Observation&data_typ={typ}&obs_mod=IMAG&frameorshot=Frame&asciitable=Ascii"
117
+ f"&coordsys=Equatorial&equinox=J2000&RadOrRec=radius&radius=10.0&frameid=&date_obs={date}&resolver=NONE&calib_typ=ALL"
118
+ f"&fieldofview=off&diff=5000&from=0&orderby=FRAMEID&output_equinox=J2000&bandwidth_type=FILTER&prop_id=&dataset=&band={band}"
119
+ "&dispcol=FRAMEID&dispcol=DATE_OBS&dispcol=DATA_TYPE&dispcol=FILTER&dispcol=EXPTIME&dispcol=RA2000&dispcol=DEC2000"
120
+ "&dispcol=UT_START&dispcol=EXP_ID")
121
+ t = net.fetch(SMOKA + "HSCsearch", body.encode(), timeout=300).decode(errors="replace")
122
+ m = re.findall(r"<pre>(.*?)</pre>", t, re.S)
123
+ return [x.split() for x in html.unescape(re.sub(r"<[^>]+>", "", m[-1])).strip().splitlines()[1:] if x.startswith("HSCA")] if m else []
124
+
125
+
126
+ def calibrations(date, band, used, n=3):
127
+ """HSC calibration frame ids (n BIAS + n DOMEFLAT of ``band``, whole exposures nearest ``date`` within 30 d, only the slots
128
+ in ``used``) -> [(frame id, date)]."""
129
+ d0 = datetime.date.fromisoformat(date)
130
+ out = []
131
+ for typ, b in (("BIAS", ""), ("DOMEFLAT", band)):
132
+ for win in (0, 7, 15, 30):
133
+ rows = search(f"{d0 - datetime.timedelta(win)}..{d0 + datetime.timedelta(win)}", "FLAT" if typ == "DOMEFLAT" else typ, b)
134
+ ex = {}
135
+ for r in rows:
136
+ if r[2] == typ:
137
+ ex.setdefault(r[8], []).append(r)
138
+ ex = {e: v for e, v in ex.items() if len(v) >= 100}
139
+ if len(ex) >= n:
140
+ break
141
+ for e in sorted(ex, key=lambda e: abs((datetime.date.fromisoformat(ex[e][0][1]) - d0).days))[:n]:
142
+ base = min(int(r[0][4:10]) for r in ex[e])
143
+ have = {f"{int(r[0][4:10]) - base}{r[0][10:]}": r for r in ex[e]}
144
+ out += [(have[k][0], have[k][1]) for k in sorted(used) if k in have]
145
+ return out
146
+
147
+
148
+ def request(exps, pos, smokaid=None, purpose="Research(solar system)", calib=True):
149
+ """Mail bodies for SMOKA (to be sent by the user, subject = password): {"science": text, "calibration": text or ""}.
150
+ HSC: only the CCDs holding the clones (all 112 when the shot's header is not public); Suprime-Cam: the 10 CCDs."""
151
+ smokaid = smokaid or os.environ.get("SMOKA_ID")
152
+ if not smokaid:
153
+ raise ValueError("SMOKA id: pass smokaid= or set $SMOKA_ID")
154
+ head = [f"SMOKAID {smokaid}", f"PURPOSE {purpose}", "COMPRESS GZIP"]
155
+ sci, cal, used = ["# Science frames"], [], {}
156
+ for x in sorted(exps, key=lambda x: x["mjd"]):
157
+ s = slots(x, pos) if x["inst"] == "HSC" else None
158
+ if x["inst"] == "HSC" and s == []:
159
+ continue
160
+ sci += [f"{f} {x['date']}" for f in frames(x, s)]
161
+ if x["inst"] == "HSC":
162
+ used.setdefault((x["date"][:7], x["filt"]), (x["date"], set()))[1].update(s or GEOM)
163
+ if calib:
164
+ for (_, band), (date, sl) in sorted(used.items()):
165
+ c = calibrations(date, band, sl)
166
+ if c:
167
+ cal += [f"# Calibration frames (BIAS + DOMEFLAT {band}, nearest {date})"] + [f"{f} {d}" for f, d in c]
168
+ return dict(science="\n".join(head + sci) + "\n", calibration="\n".join(head + cal) + "\n" if cal else "")
169
+
170
+
171
+ # ---------------------------------------------------------------- reduction of the local frames
172
+ def _open(p):
173
+ from astropy.io import fits
174
+ with (gzip.open(p) if str(p).endswith(".gz") else open(p, "rb")) as f:
175
+ with fits.open(f) as F:
176
+ e = next(x for x in F if x.data is not None)
177
+ h = e.header.copy()
178
+ for k in ("CUNIT1", "CUNIT2"): # raw HSC/Suprime-Cam write 'degree' variants that wcslib rejects
179
+ if str(h.get(k, "")).strip().lower().startswith("deg"): h[k] = "deg"
180
+ return h, e.data.astype(np.float32)
181
+
182
+
183
+ def _amps(h):
184
+ """(data slices, serial overscan columns, gain) per amplifier: HSC T_ keys, Suprime-Cam S_ keys."""
185
+ for p in ("T_", "S_"):
186
+ if f"{p}EFMN11" in h:
187
+ out = []
188
+ for a in range(1, 5):
189
+ if f"{p}EFMN{a}1" not in h:
190
+ continue
191
+ sl = lambda kind, ax: slice(int(h[f"{p}{kind}MN{a}{ax}"]) - 1, int(h[f"{p}{kind}MX{a}{ax}"]))
192
+ out.append(((sl("EF", 2), sl("EF", 1)), sl("OS", 1), float(h.get(f"{p}GAIN{a}", 1.0))))
193
+ return out
194
+ return None
195
+
196
+
197
+ def raw_ccd(p):
198
+ """Overscan-subtracted, gain-corrected CCD -> (image [e-], header, saturated). The data sections of the amplifiers are
199
+ joined side by side (the raw grid has 16-32 overscan/prescan columns between them: on the sky the CCD is contiguous,
200
+ so a raw-grid cut has 3-5" jumps no WCS can describe); the header CRPIX moves with the first amplifier's origin."""
201
+ from scipy.ndimage import median_filter
202
+ h, raw = _open(p)
203
+ amps = sorted(_amps(h) or [], key=lambda a: a[0][1].start)
204
+ if not amps:
205
+ return np.full(raw.shape, np.nan, np.float32), h, np.zeros(raw.shape, bool)
206
+ parts = []
207
+ for (y, x), ox, gain in amps:
208
+ lev = median_filter(np.median(raw[y, ox.start + 2:ox.stop - 2], axis=1), size=31, mode="nearest")
209
+ parts.append(((raw[y, x] - lev[:, None]) * gain, raw[y, x] >= 65000))
210
+ (y0, x0), _, _ = amps[0]
211
+ if "CRPIX1" in h:
212
+ h["CRPIX1"], h["CRPIX2"] = float(h["CRPIX1"]) - x0.start, float(h["CRPIX2"]) - y0.start
213
+ return np.hstack([a for a, _ in parts]).astype(np.float32), h, np.hstack([s for _, s in parts])
214
+
215
+
216
+ def gaia_refine(img, h, mid, b):
217
+ """Raw HSC headers are a rough focal-plane model ('WCS-ORIG = Rough estimation', no distortion): off axis the true scale
218
+ is up to ~10% smaller and the CCD 1-2' away (measured 7.5% and 66" on a 2015 outer CCD). Scan scale 0.90-1.01 and
219
+ rotation +-3 deg about the centre of the region b (x0, y0, x1, y1: the clones' box with room for the offset; the scale
220
+ changes across a whole CCD), offset histogram +-300" in 4" bins (brightest peaks vs Gaia G < 20.5), then a linear fit
221
+ of the matched stars, and with >= 12 of them a quadratic one written as TAN-SIP (the off-axis distortion leaves ~0.1"
222
+ after an affine fit over a cut). The header unchanged when fewer than 8 stars agree."""
223
+ from scipy import ndimage
224
+ from scipy.spatial import cKDTree
225
+ from astropy.wcs import WCS
226
+ from .. import extend
227
+ ny, nx = img.shape
228
+ d = np.nan_to_num(img - np.nanmedian(img))
229
+ d = d - ndimage.median_filter(d[::8, ::8], 9).repeat(8, 0).repeat(8, 1)[:ny, :nx]
230
+ sig = 1.4826 * np.median(np.abs(d - np.median(d)))
231
+ sm = ndimage.gaussian_filter(d, 2)
232
+ sm[ndimage.binary_dilation(~np.isfinite(img), iterations=40)] = 0 # saturated stars: halo, spikes and trails
233
+ sm[:30], sm[-30:], sm[:, :30], sm[:, -30:] = 0, 0, 0, 0
234
+ keep = np.zeros(sm.shape, bool)
235
+ keep[b[1]:b[3], b[0]:b[2]] = True
236
+ sm[~keep] = 0
237
+ yy, xx = np.nonzero((sm == ndimage.maximum_filter(sm, 11)) & (sm > 5 * sig))
238
+ if len(yy) < 10:
239
+ return h
240
+ cx, cy, bw, bh = (b[0] + b[2]) / 2, (b[1] + b[3]) / 2, b[2] - b[0], b[3] - b[1]
241
+ cell = np.minimum(((yy - b[1]) * 3 // bh) * 3 + (xx - b[0]) * 3 // bw, 8) # brightest 25 per ninth of the region
242
+ o = np.concatenate([np.flatnonzero(cell == k)[np.argsort(-sm[yy, xx][cell == k])[:25]] for k in range(9)])
243
+ Y, X = np.mgrid[-3:4, -3:4]
244
+ st = [np.clip(d[y - 3:y + 4, x - 3:x + 4], 0, None) for y, x in zip(yy[o], xx[o])] # first moments: sub-pixel centroids
245
+ px = np.c_[[x + (X * t).sum() / t.sum() for x, t in zip(xx[o], st)], [y + (Y * t).sum() / t.sum() for y, t in zip(yy[o], st)]] - [cx, cy]
246
+ w = WCS(h, naxis=2)
247
+ a0, d0 = (float(v) for v in w.all_pix2world(cx, cy, 0))
248
+ ra, de = w.all_pix2world(px[:, 0] + cx, px[:, 1] + cy, 0)
249
+ std = lambda a, b: _std(a, b, a0, d0) * 3600 # arcsec (xi, eta) about the CCD centre
250
+ en = std(ra, de).T
251
+ gra, gde, g = extend._gaia(round(a0, 4), round(d0, 4), round(np.hypot(bw, bh) / 2 * PIX / 3600 + 0.1, 2), mid)
252
+ ge = std(gra, gde).T
253
+ best = (0,)
254
+ for s in np.arange(0.90, 1.0101, 0.005):
255
+ for th in np.radians(np.arange(-3, 3.01, 0.25)):
256
+ R = s * np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]])
257
+ dd = (ge[None] - (en @ R.T)[:, None]).reshape(-1, 2)
258
+ H, xe, ye = np.histogram2d(dd[:, 0], dd[:, 1], bins=150, range=[[-300, 300], [-300, 300]])
259
+ i, j = np.unravel_index(H.argmax(), H.shape)
260
+ if H[i, j] > best[0]:
261
+ best = (H[i, j], R, np.array([xe[i] + 2, ye[j] + 2]))
262
+ if best[0] < 9:
263
+ return h
264
+ pe, T, A = en @ best[1].T + best[2], cKDTree(ge), np.c_[np.ones(len(px)), px]
265
+ for rad in (6.0, 3.0, 2.0, 1.5):
266
+ dist, idx = T.query(pe, distance_upper_bound=rad)
267
+ m = np.isfinite(dist)
268
+ if m.sum() < 8:
269
+ return h
270
+ c = np.linalg.lstsq(A[m], ge[idx[m]], rcond=None)[0] # (3, 2): [1, x, y] -> (xi, eta) ["]
271
+ pe = A @ c
272
+ # tangent point at the region centre (constant term ~0, CRPIX ~ the centre), then the quadratic terms
273
+ t = WCS(naxis=2)
274
+ t.wcs.ctype, t.wcs.crval, t.wcs.crpix, t.wcs.cd = ["RA---TAN", "DEC--TAN"], [a0, d0], [1, 1], np.eye(2) / 3600
275
+ a0, d0 = (float(v) for v in t.all_pix2world(c[0, 0], c[0, 1], 0))
276
+ ge = _std(gra, gde, a0, d0).T * 3600
277
+ T, Q = cKDTree(ge), A
278
+ if m.sum() >= 12:
279
+ Q = np.c_[A, px[:, :1] ** 2 / 1e6, px[:, :1] * px[:, 1:] / 1e6, px[:, 1:] ** 2 / 1e6]
280
+ dist, idx = T.query(A @ np.linalg.lstsq(A[m], ge[idx[m]], rcond=None)[0], distance_upper_bound=1.5)
281
+ m = np.isfinite(dist)
282
+ for rad in (1.0, 0.7):
283
+ dist, idx2 = T.query(Q @ np.linalg.lstsq(Q[m], ge[idx[m]], rcond=None)[0], distance_upper_bound=rad)
284
+ if np.isfinite(dist).sum() < 8:
285
+ break
286
+ m, idx = np.isfinite(dist), idx2
287
+ c = np.linalg.lstsq(Q[m], ge[idx[m]], rcond=None)[0]
288
+ C = c[1:3].T # ["/px], rows (xi, eta)
289
+ h = h.copy()
290
+ for k in [k for k in h if k.startswith(("PC", "CDELT", "PV", "A_", "B_", "AP_", "BP_"))]:
291
+ del h[k]
292
+ crpix = np.linalg.solve(C, -c[0]) + [cx, cy]
293
+ sip = "-SIP" if len(c) > 3 else ""
294
+ h["CTYPE1"], h["CTYPE2"], h["CRVAL1"], h["CRVAL2"] = "RA---TAN" + sip, "DEC--TAN" + sip, a0, d0
295
+ h["CRPIX1"], h["CRPIX2"] = float(crpix[0] + 1), float(crpix[1] + 1)
296
+ h["CD1_1"], h["CD1_2"], h["CD2_1"], h["CD2_2"] = (float(v) / 3600 for v in C.ravel())
297
+ if sip: # pixel-space quadratic terms about CRPIX (~ the centre)
298
+ h["A_ORDER"] = h["B_ORDER"] = 2
299
+ for (i, j), (qa, qb) in zip(((2, 0), (1, 1), (0, 2)), np.linalg.solve(C, c[3:].T).T / 1e6):
300
+ h[f"A_{i}_{j}"], h[f"B_{i}_{j}"] = float(qa), float(qb)
301
+ h["WCS-ORIG"], h["WCSNMAT"] = "Gaia DR3 (orbitsift smoka.gaia_refine)", int(m.sum())
302
+ return h
303
+
304
+
305
+ def _std(a, d, a0, d0):
306
+ """Gnomonic standard coordinates [deg] of (a, d) about (a0, d0)."""
307
+ a, d, a0, d0 = (np.radians(np.asarray(v, float)) for v in (a, d, a0, d0))
308
+ c = np.sin(d) * np.sin(d0) + np.cos(d) * np.cos(d0) * np.cos(a - a0)
309
+ return np.degrees(np.vstack([np.cos(d) * np.sin(a - a0) / c, (np.sin(d) * np.cos(d0) - np.cos(d) * np.sin(d0) * np.cos(a - a0)) / c]))
310
+
311
+
312
+ def masters(h):
313
+ """Median BIAS and normalised median flat of the local calibration frames with this DET-ID (flats: same filter), nearest
314
+ in time, 3 each; cached per (DET-ID, the frames used). -> (bias, flat), None when missing."""
315
+ det, filt, mjd = int(h.get("DET-ID", -1)), h.get("FILTER01"), float(h.get("MJD", 0))
316
+ idx = cached_json(cache("smoka", "calib_index.json"), lambda: {})
317
+ for p in folder().glob("*.fits*"): # headers of the calibration frames, read once
318
+ if p.name not in idx:
319
+ try:
320
+ hh = _open(p)[0]
321
+ idx[p.name] = dict(typ=hh.get("DATA-TYP"), det=int(hh.get("DET-ID", -1)), filt=hh.get("FILTER01"), mjd=float(hh.get("MJD", 0)))
322
+ except Exception: # noqa: BLE001 unreadable file: skipped
323
+ idx[p.name] = dict(typ=None)
324
+ cache("smoka", "calib_index.json").write_text(json.dumps(idx))
325
+ near = lambda c: sorted(c, key=lambda n: abs(idx[n]["mjd"] - mjd))[:3]
326
+ bias = near([n for n, x in idx.items() if x.get("typ") == "BIAS" and x["det"] == det])
327
+ flat = near([n for n, x in idx.items() if x.get("typ") in ("DOMEFLAT", "SKYFLAT") and x["det"] == det and x["filt"] == filt])
328
+ B = np.median([raw_ccd(folder() / n)[0] for n in bias], axis=0) if bias else None
329
+ F = None
330
+ if flat:
331
+ fl = []
332
+ for n in flat:
333
+ a = raw_ccd(folder() / n)[0] - (B if B is not None else 0)
334
+ fl.append(a / np.nanmedian(a))
335
+ F = np.nanmedian(fl, axis=0)
336
+ F[(F < 0.5) | (F > 1.5)] = np.nan
337
+ return B, F
338
+
339
+
340
+ def fetch(exp, pos, outdir):
341
+ from astropy.wcs import WCS
342
+ ra, dec = pos(exp["mjd"] + exp["exptime"] / 2 / 86400, SITE)
343
+ paths = []
344
+ for fid in frames(exp):
345
+ p = local(fid)
346
+ if p is None:
347
+ continue
348
+ path = outdir / f"smoka_{fid}.fits.fz"
349
+ if stale(path, ra, dec, PAD / PIX):
350
+ img, h, sat = raw_ccd(p)
351
+ w = WCS(h, naxis=2)
352
+ if not w.has_celestial:
353
+ continue
354
+ mid = (float(h["MJD-STR"]) + float(h["MJD-END"])) / 2 if "MJD-END" in h else float(h.get("MJD", exp["mjd"])) + exp["exptime"] / 2 / 86400
355
+ b = box(w, img.shape[1], img.shape[0], *pos(mid, SITE), (PAD + 300) / PIX) # rough header: 1-2' off
356
+ if b is None:
357
+ continue
358
+ if exp["inst"] == "HSC":
359
+ B, F = masters(h)
360
+ img = (img - (B if B is not None else 0)) / (F if F is not None else 1)
361
+ img[sat] = np.nan
362
+ h = gaia_refine(img, h, mid, b)
363
+ b = box(WCS(h, naxis=2), img.shape[1], img.shape[0], *pos(mid, SITE), PAD / PIX)
364
+ if b is None:
365
+ continue
366
+ write_cut(path, img[b[1]:b[3], b[0]:b[2]], h, mid, float(h.get("EXPTIME", exp["exptime"])), str(h.get("FILTER01", exp["filt"])),
367
+ SITE, exp["inst"], fid, b[0], b[1], saturate=1e30)
368
+ paths.append(path)
369
+ return paths