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,70 @@
1
+ """ING archive at CASU (INT/WFC). Search and headers are public and anonymous (the SSOIS image id is the archive's record
2
+ number); the download goes through a request with an e-mail address and the data link arrives by mail, so it is only
3
+ prepared here (``request``), never submitted. Exposures are listed, with the request to make."""
4
+ import html
5
+ import re
6
+ import urllib.parse
7
+
8
+ from .. import net
9
+ from . import cache, cached_json
10
+
11
+ INSTRUMENTS = ("INT/WFC",)
12
+ SITE = "950"
13
+ ARCH = "http://casu.ast.cam.ac.uk/casuadc/ingarch/"
14
+ COLS = ("run", "coords", "object", "filter", "exptime", "ut", "night", "airmass", "obstype", "instrument")
15
+
16
+
17
+ def exposures(rows, V=None):
18
+ out = {}
19
+ for r in rows:
20
+ if r["Telescope/Instrument"] in INSTRUMENTS and float(r["Exptime"]) >= 30:
21
+ out.setdefault(r["Image"], dict(archive="ing", id=r["Image"], mjd=float(r["MJD"]), exptime=float(r["Exptime"]),
22
+ filt=r["Filter"], inst="INT/WFC", site=SITE, run=int(r["Image"][8:16]), night=r["Image"][:8],
23
+ listed="ING archive (CASU): orbitsift.archives.ing.request(...) prepares the request; "
24
+ "submitting it needs an e-mail address, the data link comes by mail"))
25
+ return list(out.values())
26
+
27
+
28
+ def search(night, run):
29
+ """ING archive rows of one run on one night (YYYYMMDD) -> [dict(recno, run, coords, object, filter, exptime, ...)]."""
30
+ def get():
31
+ q = dict(objname="", coordinates="", radius="", nightobs=night, telescope="", instrument="", waveband="", pattref="", runno=run)
32
+ t = net.fetch(ARCH + "displayResults", urllib.parse.urlencode(q).encode(), timeout=300).decode(errors="replace")
33
+ out = []
34
+ for tr in re.findall(r"<tr[^>]*>(.*?)</tr>", t, re.S):
35
+ m = re.search(r"displayHeader\?recno=(\d+)", tr)
36
+ cells = [html.unescape(re.sub(r"<[^>]+>", "", c)).strip() for c in re.findall(r"<td[^>]*>(.*?)</td>", tr, re.S)]
37
+ if m and len(cells) >= len(COLS) + 1:
38
+ out.append(dict(recno=m.group(1), **dict(zip(COLS, cells[-len(COLS):]))))
39
+ return out
40
+ return cached_json(cache("ing", f"{night}_{run}.json"), get)
41
+
42
+
43
+ def header(recno):
44
+ """Primary header of a record (public header page) -> dict of keyword: value (strings and floats)."""
45
+ def get():
46
+ t = html.unescape(re.sub(r"<[^>]+>", "", net.fetch(f"{ARCH}displayHeader?recno={recno}", timeout=300).decode(errors="replace")))
47
+ h = {}
48
+ for line in t.splitlines():
49
+ if len(line) > 9 and line[8] == "=" and line[:8].strip() not in h: # first HDU first
50
+ v = line[10:].split(" /")[0].strip()
51
+ try:
52
+ v = float(v)
53
+ except ValueError:
54
+ v = v.strip("'").strip()
55
+ h[line[:8].strip()] = v
56
+ return h
57
+ return cached_json(cache("ing", f"hdr_{recno}.json"), get)
58
+
59
+
60
+ def request(exps):
61
+ """The data request to submit by hand: POST ``url`` with ``data`` (the record numbers), then the page asks for an
62
+ e-mail address and the data link arrives by mail. Nothing is sent from here."""
63
+ rec = sorted({x["id"] for x in exps})
64
+ return dict(url=ARCH + "request", data=urllib.parse.urlencode([("recno", r) for r in rec]), recno=rec,
65
+ note="POST the record numbers to the request page (or tick them in the archive's results page), "
66
+ "then give an e-mail address; CASU mails the download link.")
67
+
68
+
69
+ def fetch(exp, pos, outdir):
70
+ return []
@@ -0,0 +1,22 @@
1
+ """Archives that are not downloaded here (an account is needed, or no anonymous cutout service is wired up):
2
+ their exposures are only listed, with where to get them. No login is ever attempted."""
3
+ INSTRUCTIONS = {
4
+ "Gemini/GMOS": "Gemini Observatory Archive (https://archive.gemini.edu/): search by file name; public after the proprietary period",
5
+ "Gemini-N/GMOS": "Gemini Observatory Archive (https://archive.gemini.edu/): search by file name",
6
+ "Gemini-S/GMOS": "Gemini Observatory Archive (https://archive.gemini.edu/): search by file name",
7
+ }
8
+ INSTRUMENTS = tuple(INSTRUCTIONS)
9
+
10
+
11
+ def exposures(rows, V=None):
12
+ out = {}
13
+ for r in rows:
14
+ ti = r["Telescope/Instrument"]
15
+ if ti in INSTRUCTIONS and float(r["Exptime"]) >= 30:
16
+ out.setdefault(r["Image"], dict(archive="listing", id=r["Image"], mjd=float(r["MJD"]), exptime=float(r["Exptime"]),
17
+ filt=r["Filter"], inst=ti, site=None, listed=INSTRUCTIONS[ti]))
18
+ return list(out.values())
19
+
20
+
21
+ def fetch(exp, pos, outdir):
22
+ return []
@@ -0,0 +1,302 @@
1
+ """NOIRLab Astro Data Archive: DECam Community Pipeline CCDs (instcal), public ones only; the CCD is downloaded,
2
+ cut and deleted (the archive has no cutout service). Also the older NOIRLab imagers (KPNO 90prime, Mosaic-1.1/3, CTIO
3
+ Mosaic-2): their SSOIS rows carry the md5 of a raw or processed file; the instcal file of the same exposure (same
4
+ DATE-OBS) is used when public, otherwise the raw one, overscan-subtracted and trimmed (no flat)."""
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import tempfile
9
+
10
+ import numpy as np
11
+
12
+ from .. import config, images, net, orbit
13
+ from . import PAD, box, cache, cached_json, section, stale, write_cut
14
+
15
+ # SSOIS name -> (NOIRLab instrument, MPC site, short name)
16
+ OTHER = {"KPNO-2.3m/90prime": ("90prime", "695", "90prime"), "KPNO-4m/Mosaic1.1": ("mosaic_1_1", "695", "Mosaic1.1"),
17
+ "KPNO-4m/Mosaic3": ("mosaic3", "695", "Mosaic3"), "CTIO-4m/Mosaic2": ("mosaic_2", "807", "Mosaic2")}
18
+ INSTRUMENTS = ("CTIO-4m/DECam",) + tuple(OTHER)
19
+ SITE = "W84"
20
+ # Read caches made before 15 Nov 2026 too (CCD lists per exposure, cuts named by exposure), with their defect: only to
21
+ # replay a fixture recorded that way (benchmarks/validate.py with an old extend bundle). Never for new measurements.
22
+ LEGACY = False
23
+
24
+
25
+ def exposures(rows, V=None):
26
+ out = {}
27
+ for r in rows:
28
+ img = r["Image"].split()[0]
29
+ if r["Telescope/Instrument"] in INSTRUMENTS and img.startswith("c4d_") and float(r["Exptime"]) >= 30:
30
+ out.setdefault(img[:17], dict(archive="noirlab", id=img[:17], mjd=float(r["MJD"]), exptime=float(r["Exptime"]),
31
+ filt=r["Filter"], inst="DECam", site=SITE))
32
+ elif r["Telescope/Instrument"] in OTHER and float(r["Exptime"]) >= 30 and len(r["Image"].split()) == 2:
33
+ noao, site, short = OTHER[r["Telescope/Instrument"]]
34
+ x = out.setdefault((short, round(float(r["MJD"]), 5)), dict(archive="noirlab", id=img.split(".")[0], mjd=float(r["MJD"]),
35
+ exptime=float(r["Exptime"]), filt=r["Filter"], inst=short,
36
+ noao=noao, site=site, md5=[]))
37
+ if r["Image"].split()[1] not in x["md5"]: # raw, instcal and resampled rows of one exposure
38
+ x["md5"].append(r["Image"].split()[1])
39
+ return list(out.values())
40
+
41
+
42
+ def _find(search):
43
+ body = dict(outfields=["md5sum", "archive_filename", "release_date", "proc_type", "prod_type", "dateobs_min", "caldat", "instrument"],
44
+ search=search)
45
+ return json.loads(net.fetch(f"{images.ARCHIVE}/api/adv_search/find/?limit=5000&format=json", data=json.dumps(body).encode(),
46
+ headers={"Content-Type": "application/json"}, timeout=900))[1:]
47
+
48
+
49
+ def product(exp):
50
+ """The file to cut for a non-DECam exposure (cached): the public instcal image with the DATE-OBS of the SSOIS file
51
+ (Legacy Surveys 'ls9' reprocessing first, then the newest name), else the public raw image -> dict or None."""
52
+ def find():
53
+ recs = [x for m in exp["md5"] for x in _find([["md5sum", m]])]
54
+ today = str(np.datetime64("today"))
55
+ if not recs:
56
+ return None
57
+ t, night = recs[0]["dateobs_min"][:19], recs[0]["caldat"]
58
+ same = [x for x in _find([["instrument", exp["noao"]], ["caldat", night, night], ["prod_type", "image"]])
59
+ if (x["dateobs_min"] or "")[:19] == t and str(x.get("release_date") or "9999")[:10] <= today]
60
+ for proc in ("instcal", "raw"):
61
+ c = [x for x in same if x["proc_type"] == proc]
62
+ if c:
63
+ x = max(c, key=lambda x: ("ls9" in x["archive_filename"], x["archive_filename"]))
64
+ return dict(md5sum=x["md5sum"], archive_filename=x["archive_filename"], raw=proc == "raw")
65
+ return None
66
+ return cached_json(cache("noirlab", f"{exp['inst']}_{exp['id']}.json"), find)
67
+
68
+
69
+ def _headers(md5):
70
+ return cached_json(cache("noirlab", "hdr", md5 + ".json.gz"),
71
+ lambda: json.loads(net.fetch(f"{images.ARCHIVE}/api/header/{md5}/?format=json", timeout=300)))
72
+
73
+
74
+ def _fetch_other(exp, pos, outdir):
75
+ import warnings
76
+ from astropy.io import fits
77
+ from astropy.time import Time
78
+ from astropy.wcs import WCS, FITSFixedWarning
79
+ from . import raw_amp, tan_header
80
+ p = product(exp)
81
+ if p is None:
82
+ return []
83
+ H = _headers(p["md5sum"])
84
+ h0 = H[0]
85
+ mid = (float(h0["MJD-OBS"]) if h0.get("MJD-OBS") else Time(h0["DATE-OBS"], scale="utc").mjd) + float(h0["EXPTIME"]) / 2 / 86400
86
+ ra, dec = pos(mid, exp["site"])
87
+ paths = []
88
+ for k, e in enumerate(H[1:], 1):
89
+ if "CRVAL1" not in e or "NAXIS1" not in e:
90
+ continue
91
+ h = tan_header(fits.Header({q: v for q, v in e.items() if isinstance(v, (int, float, str)) and len(q) <= 8
92
+ and q not in ("COMMENT", "HISTORY", "")}))
93
+ nx, ny = int(e.get("ZNAXIS1", e["NAXIS1"])), int(e.get("ZNAXIS2", e["NAXIS2"]))
94
+ x0 = y0 = 0
95
+ if p["raw"]:
96
+ ds = section(h["DATASEC"])
97
+ x0, y0, nx, ny = ds[1].start, ds[0].start, ds[1].stop - ds[1].start, ds[0].stop - ds[0].start
98
+ hw = h.copy()
99
+ hw["CRPIX1"], hw["CRPIX2"] = float(h["CRPIX1"]) - x0, float(h["CRPIX2"]) - y0
100
+ with warnings.catch_warnings():
101
+ warnings.simplefilter("ignore", FITSFixedWarning)
102
+ w = WCS(hw, naxis=2)
103
+ pix = float(np.sqrt(abs(np.linalg.det(w.pixel_scale_matrix))) * 3600)
104
+ b = box(w, nx, ny, ra, dec, PAD / pix)
105
+ if b is None:
106
+ continue
107
+ path = outdir / poskey(ra, dec) / f"{exp['inst']}_{exp['id']}_{k}.fits.fz"
108
+ if stale(path, ra, dec, PAD / pix):
109
+ with tempfile.TemporaryDirectory(dir=config.cache_dir()) as tmp:
110
+ with fits.open(images.retrieve(dict(p, hdu_idx=k - 1), tmp)) as f:
111
+ d = f[-1].data
112
+ sat = float(e.get("SATURATE") or h0.get("SATURATE") or 60000)
113
+ if p["raw"]:
114
+ d, _, lev = raw_amp(d, h)
115
+ sat = min(sat, 65535) - lev
116
+ write_cut(path, d[b[1]:b[3], b[0]:b[2]], hw, mid, h0["EXPTIME"], str(h0.get("FILTER", "")).split()[0], exp["site"],
117
+ exp["inst"], p["archive_filename"].split("/")[-1] + f"[{k}]", b[0], b[1], saturate=sat)
118
+ paths.append(path)
119
+ return paths
120
+
121
+
122
+ def poskey(ra, dec):
123
+ """Cache key of a set of positions (rounded to 1e-5 deg): CCD lists and cuts are made for these positions only."""
124
+ a = np.round(np.c_[np.atleast_1d(ra) % 360, np.atleast_1d(dec)].astype(float), 5) + 0.0 # (+ 0.0: no -0.0)
125
+ return hashlib.sha1(a.tobytes()).hexdigest()[:16]
126
+
127
+
128
+ def ccds(exp, ra, dec):
129
+ """Public instcal HDUs of the exposure that hold any of the positions (one per CCD, reprocessed ls9 version first).
130
+ Cached under the exposure AND the positions: the list holds only the CCDs that hold these positions, so another
131
+ object on the same exposure (or a moved cloud) never reuses it. Keyed by exposure alone, the first object measured
132
+ on an exposure fixed the CCDs of every later one: those then measured nothing ('no CCD' or off the cut) although a
133
+ CCD held them (found in the survey on 15 Nov 2026: ~1,900 frames). Empty lists are not cached."""
134
+ def hold(x):
135
+ dx = ((ra - x["ra_center"] + 180) % 360 - 180) * np.cos(np.radians(dec))
136
+ return bool(((np.abs(dx) < images.CCD_HALF[0]) & (np.abs(dec - x["dec_center"]) < images.CCD_HALF[1])).any())
137
+
138
+ def find():
139
+ a0, d0 = orbit.centre_ra(ra, np.median), float(np.median(dec))
140
+ r = float(np.max(images._sep(ra, dec, a0, d0)))
141
+ recs = images.archive_hdus(round(a0, 1), round(d0, 1), math.ceil((r + 0.25) * 10) / 10) # rounded: one search per field
142
+ today = str(np.datetime64("today"))
143
+ best = {}
144
+ for x in recs:
145
+ name = x["archive_filename"].split("/")[-1]
146
+ if not name.startswith(exp["id"]) or x.get("ra_center") is None or x.get("file_release_date", "9999")[:10] > today:
147
+ continue
148
+ if not hold(x):
149
+ continue
150
+ k, rank = x["hdu_idx"], ("ls9" in name, name)
151
+ if k not in best or rank > best[k][0]:
152
+ best[k] = rank, {c: x[c] for c in ("archive_filename", "hdu_idx", "md5sum", "file_dateobs", "filter", "exposure", "proposal",
153
+ "ra_center", "dec_center")}
154
+ best = {k: v for k, (_, v) in best.items()}
155
+ return sorted(best.values(), key=lambda x: x["hdu_idx"])
156
+ path = cache("noirlab", "pos", f"{exp['id']}_{poskey(ra, dec)}.json") # (the old per-exposure files are not read)
157
+ if path.exists():
158
+ return json.loads(path.read_bytes())
159
+ old = cache("noirlab", exp["id"] + ".json")
160
+ if LEGACY and old.exists():
161
+ return json.loads(old.read_bytes())
162
+ got = by_name(exp, ra, dec) if exp.get("by_id") else find() or by_header(exp, ra, dec)
163
+ if got:
164
+ net.save(path, json.dumps(got))
165
+ return got
166
+
167
+
168
+ def by_header(exp, ra, dec):
169
+ """Fallback when the SIA HDU index has no record of the exposure (audit 7 Nov 2026: 431 of 922 DECam exposures of the
170
+ Nov 3-5 extension runs had an empty index list; for 164 of them the per-HDU headers put the object on a CCD): find the
171
+ public instcal files of the exposure with adv_search (date + box), read their HDU headers (JSON, no pixels) and keep the
172
+ HDUs whose footprint holds a position. Newest file version first. UNTESTED here (written offline from dmeas._hdr_ccds)."""
173
+ import datetime
174
+ import warnings
175
+ from astropy.io import fits
176
+ from astropy.wcs import WCS, FITSFixedWarning
177
+ a0, d0 = orbit.centre_ra(ra, np.median), float(np.median(dec))
178
+ day = datetime.date(2000 + int(exp["id"][4:6]), int(exp["id"][6:8]), int(exp["id"][8:10]))
179
+ h = 1.2
180
+ if not net.exact(): # the box around the tile cell, not around the positions
181
+ a0, d0, grow = net.snap(a0, d0)
182
+ h = round(h + grow, 2)
183
+ c = 1 / max(np.cos(np.radians(min(89.0, abs(d0) + h - 1.2))), 0.05)
184
+ body = dict(outfields=["md5sum", "archive_filename", "release_date", "proc_type", "prod_type"],
185
+ search=[["instrument", "decam"], ["proc_type", "instcal"], ["prod_type", "image"],
186
+ ["caldat", str(day - datetime.timedelta(1)), str(day)],
187
+ ["ra_center", round((a0 - h * c) % 360, 4), round((a0 + h * c) % 360, 4)], ["dec_center", d0 - h, d0 + h]])
188
+ q = json.dumps(body).encode() # cached like the SIA searches (the answer to a past date does not change)
189
+ res = cached_json(cache("noirlab", "find", hashlib.sha1(q).hexdigest()[:16] + ".json"), lambda: json.loads(net.fetch(
190
+ f"{images.ARCHIVE}/api/adv_search/find/?limit=2000&format=json", data=q, headers={"Content-Type": "application/json"}, timeout=900)))[1:]
191
+ today = str(np.datetime64("today"))
192
+ vs = sorted((x for x in res if x["archive_filename"].split("/")[-1].startswith(exp["id"]) and str(x.get("release_date", "9999"))[:10] <= today),
193
+ key=lambda x: x["archive_filename"], reverse=True)
194
+ for x in vs:
195
+ H = _headers(x["md5sum"]) # cached: the lists are per position, the headers are not
196
+ out = []
197
+ for k, e in enumerate(H[1:]):
198
+ if "CRVAL1" not in e or "NAXIS1" not in e:
199
+ continue
200
+ h = fits.Header({q: v for q, v in e.items() if isinstance(v, (int, float, str)) and len(q) <= 8 and q not in ("COMMENT", "HISTORY", "")})
201
+ with warnings.catch_warnings():
202
+ warnings.simplefilter("ignore", FITSFixedWarning)
203
+ px, py = WCS(h).all_world2pix(np.asarray(ra), np.asarray(dec), 0)
204
+ if ((px > -20) & (px < e["NAXIS1"] + 20) & (py > -20) & (py < e["NAXIS2"] + 20)).any():
205
+ out.append(dict(archive_filename=x["archive_filename"], hdu_idx=k, md5sum=x["md5sum"], file_dateobs=None, filter=None,
206
+ exposure=None, proposal=None)) # no CCD centre: not re-validated by hold()
207
+ if out:
208
+ return out
209
+ return []
210
+
211
+
212
+ def _search(search, limit):
213
+ q = json.dumps(dict(outfields=["md5sum", "archive_filename", "release_date", "dateobs_min"], search=[
214
+ ["instrument", "decam"], ["proc_type", "instcal"], ["prod_type", "image"]] + search)).encode()
215
+ return json.loads(net.fetch(f"{images.ARCHIVE}/api/adv_search/find/?limit={limit}&format=json", data=q,
216
+ headers={"Content-Type": "application/json"}, timeout=300))[1:]
217
+
218
+
219
+ def files_by_name(eid, mjd=None):
220
+ """Public-or-not instcal files of a DECam exposure, found by its NAME only (no position is sent): the archive names
221
+ that contain ``<eid>_ooi``. 2013-14 NSC names that are not archive names (old Community Pipeline 'tu2199234', or a
222
+ c4d name the archive lacks) fall back to the exposure START (UTC MJD ``mjd``): the instcal files of that hour and the
223
+ next whose dateobs_min is within 3 s of it (archive names stamp a later time: tu2199234 = c4d_140301_030651).
224
+ Cached when found. = the survey's exposure-ID guard (decamrec img.py _files, 17 Nov 2026)."""
225
+ import datetime
226
+ path = cache("noirlab", "name", eid + ".json")
227
+ if path.exists():
228
+ return json.loads(path.read_bytes())
229
+ out = [x for x in _search([["archive_filename", eid + "_ooi", "icontains"]], 20)]
230
+ if not out and mjd is not None:
231
+ t = datetime.datetime(1858, 11, 17, tzinfo=datetime.timezone.utc) + datetime.timedelta(days=float(mjd))
232
+ for h in sorted({(t + datetime.timedelta(minutes=m)).strftime("c4d_%y%m%d_%H") for m in (0, 20)}):
233
+ for x in _search([["archive_filename", h, "icontains"]], 2000):
234
+ try:
235
+ d = abs(images.mjd_of(str(x["dateobs_min"]).rstrip("Z")) - float(mjd)) * 86400 # any fraction length (3.10's fromisoformat takes 3 or 6 digits only)
236
+ except ValueError:
237
+ continue
238
+ if d < 3 and "_ooi_" in x["archive_filename"]:
239
+ out.append(x)
240
+ out = [{k: x.get(k) for k in ("md5sum", "archive_filename", "release_date")} for x in out]
241
+ if out:
242
+ net.save(path, json.dumps(out).encode())
243
+ return out
244
+
245
+
246
+ def by_name(exp, ra, dec):
247
+ """ID-only CCD list (``exp['by_id']``: extend with local exposure tables, unused): the exposure's files by name
248
+ (``files_by_name``), their HDU headers by md5, and the HDUs whose footprint holds a position, chosen here. Per HDU the
249
+ Legacy Surveys 'ls9' reprocessing first, then the highest name. Nothing in the requests depends on the positions."""
250
+ import warnings
251
+ from astropy.io import fits
252
+ from astropy.wcs import WCS, FITSFixedWarning
253
+ today = str(np.datetime64("today"))
254
+ best = {}
255
+ ra, dec = np.atleast_1d(ra), np.atleast_1d(dec)
256
+ held = np.zeros(len(ra), bool)
257
+ files = [f for f in files_by_name(exp["id"], exp.get("mjd")) if str(f.get("release_date") or "9999")[:10] <= today]
258
+ pref = lambda f: ("ls9" in f["archive_filename"].split("/")[-1], f["archive_filename"].split("/")[-1])
259
+ for f in sorted(files, key=pref, reverse=True): # preferred file first: one CCD per position, from the preferred file
260
+ if held.all():
261
+ break # a lower file can only add an HDU no position needs
262
+ name = f["archive_filename"].split("/")[-1]
263
+ for k, e in enumerate(_headers(f["md5sum"])[1:]):
264
+ if "CRVAL1" not in e or "NAXIS1" not in e:
265
+ continue
266
+ h = fits.Header({q: v for q, v in e.items() if v is not None and isinstance(v, (int, float, str)) and len(q) <= 8
267
+ and q not in ("COMMENT", "HISTORY", "")})
268
+ with warnings.catch_warnings():
269
+ warnings.simplefilter("ignore", FITSFixedWarning)
270
+ x, y = WCS(h).all_world2pix(np.atleast_1d(ra), np.atleast_1d(dec), 0, quiet=True)
271
+ inside = (x >= 0) & (x < e["NAXIS1"]) & (y >= 0) & (y < e["NAXIS2"])
272
+ held |= inside
273
+ if inside.any() and (k not in best or ("ls9" in name, name) > best[k][0]):
274
+ best[k] = ("ls9" in name, name), dict(archive_filename=f["archive_filename"], hdu_idx=k, md5sum=f["md5sum"], file_dateobs=None,
275
+ filter=None, exposure=None, proposal=None)
276
+ return [v for _, (_, v) in sorted(best.items())]
277
+
278
+
279
+ def fetch(exp, pos, outdir):
280
+ if exp["inst"] != "DECam":
281
+ return _fetch_other(exp, pos, outdir)
282
+ from astropy.io import fits
283
+ from astropy.wcs import WCS
284
+ ra, dec = pos(exp["mjd"] + exp["exptime"] / 2 / 86400, SITE)
285
+ paths = []
286
+ for rec in ccds(exp, ra, dec):
287
+ path = outdir / poskey(ra, dec) / f"{exp['id']}_{rec['hdu_idx']}.fits.fz" # one cut folder per position set
288
+ if LEGACY and not path.exists() and (outdir / path.name).exists():
289
+ path = outdir / path.name
290
+ if stale(path, ra, dec, PAD / images.PIX):
291
+ with tempfile.TemporaryDirectory(dir=config.cache_dir()) as tmp:
292
+ with fits.open(images.retrieve(rec, tmp)) as f:
293
+ h0, e = f[0].header, next(x for x in f[1:] if x.data is not None)
294
+ mid = float(h0["MJD-OBS"]) + float(h0["EXPTIME"]) / 2 / 86400
295
+ b = box(WCS(e.header), e.data.shape[1], e.data.shape[0], *pos(mid, SITE), PAD / images.PIX)
296
+ if b is None:
297
+ continue
298
+ write_cut(path, e.data[b[1]:b[3], b[0]:b[2]], e.header, mid, h0["EXPTIME"], str(h0.get("FILTER", "")).split()[0],
299
+ SITE, "DECam", rec["archive_filename"].split("/")[-1], b[0], b[1],
300
+ saturate=float(e.header.get("SATURATE", h0.get("SATURATE", 40000))))
301
+ paths.append(path)
302
+ return paths
@@ -0,0 +1,59 @@
1
+ """Pan-STARRS1 warps (single-exposure skycell images) from MAST, cut on the server (fitscut). PS1 is shallow
2
+ (5-sigma ~21.5-22 per warp): used only when the predicted V is <= 23.5, and its single exposures give points
3
+ only when V <= 22; fainter than that they only add to the shift-and-stack."""
4
+ import io
5
+
6
+ import numpy as np
7
+
8
+ from .. import net, orbit
9
+ from . import PAD, stale, write_cut
10
+
11
+ INSTRUMENTS = ("Pan-STARRS1",)
12
+ SITE = "F51"
13
+ PIX = 0.25
14
+ FITSCUT = "https://ps1images.stsci.edu/cgi-bin/fitscut.cgi"
15
+ V_POINTS, V_STACK = 22.0, 23.5
16
+
17
+
18
+ def exposures(rows, V=None):
19
+ if V is None or V > V_STACK:
20
+ return []
21
+ out = {}
22
+ for r in rows:
23
+ if r["Telescope/Instrument"] in INSTRUMENTS and ".wrp." in r["Image"]:
24
+ x = out.setdefault(r["Image"].split(".wrp.")[1], dict(archive="ps1", id=r["Image"].split(".wrp.")[1], mjd=float(r["MJD"]),
25
+ exptime=float(r["Exptime"]), filt=r["Filter"], inst="GPC1", site=SITE,
26
+ points=V <= V_POINTS, cells=[]))
27
+ if r["Image"] not in x["cells"]: # one exposure, several skycells
28
+ x["cells"].append(r["Image"])
29
+ return list(out.values())
30
+
31
+
32
+ def fetch(exp, pos, outdir):
33
+ net.require("cutouts") # the cutout box gives the target's position to ~2'
34
+ return [p for c in sorted(exp["cells"]) for p in _cell(c, exp, pos, outdir)]
35
+
36
+
37
+ def _cell(cell, exp, pos, outdir):
38
+ from astropy.io import fits
39
+ from astropy.time import Time
40
+ path = outdir / f"ps1_{cell.split('skycell.')[-1]}.fits.fz"
41
+ ra, dec = pos(exp["mjd"] + exp["exptime"] / 2 / 86400, SITE)
42
+ if stale(path, ra, dec, PAD / PIX):
43
+ a0 = orbit.centre_ra(ra, np.median)
44
+ dx = ((ra - a0 + 180) % 360 - 180) * np.cos(np.radians(dec)) * 3600
45
+ x0, x1, y0, y1 = dx.min(), dx.max(), dec.min() * 3600, dec.max() * 3600
46
+ c_ra = a0 + (x0 + x1) / 2 / 3600 / np.cos(np.radians((y0 + y1) / 7200))
47
+ size = int(min(6000, (max(x1 - x0, y1 - y0) + 2 * PAD) / PIX))
48
+ p = cell.split(".")
49
+ red = f"/rings.v3.skycell/{p[3]}/{p[4]}/{cell}.fits"
50
+ b = net.fetch(f"{FITSCUT}?red={red}&ra={c_ra % 360:.6f}&dec={(y0 + y1) / 7200:.6f}&size={size}&format=fits", timeout=600)
51
+ with fits.open(io.BytesIO(b)) as f:
52
+ h = f[0].header
53
+ if not np.isfinite(f[0].data).any():
54
+ return []
55
+ t = Time(float(h["MJD-OBS"]), format="mjd", scale="tai" if h.get("TIMESYS", "UTC").strip() == "TAI" else "utc")
56
+ mid = t.utc.mjd + float(h["EXPTIME"]) / 2 / 86400
57
+ write_cut(path, f[0].data, h, mid, h["EXPTIME"], str(h.get("FPA.FILTER", exp["filt"]))[:1], SITE, "GPC1", cell,
58
+ saturate=float(h.get("CELL.SATURATION", 40000)))
59
+ return [path]
@@ -0,0 +1,52 @@
1
+ """SDSS imaging (DR17 corrected frames, Stripe 82 runs included) from the SAS: the frame (~3 MB, bzip2) is downloaded and
2
+ cut. Frames are calibrated (nanomaggies) and sky-subtracted, with a TAN-SIP header WCS. Drift scan: a frame row is
3
+ exposed ~54 s; the frame's TAI start + half that is used as mid-time (a TNO moves < 0.05" meanwhile). Shallow
4
+ (r 5-sigma ~22.2), so used like PS1: points only for V <= 22, stack only for V <= 23.5."""
5
+ import bz2
6
+ import io
7
+
8
+ import numpy as np
9
+
10
+ from .. import net
11
+ from . import PAD, box, stale, write_cut
12
+
13
+ INSTRUMENTS = ("SDSS",)
14
+ SITE = "645"
15
+ PIX = 0.396
16
+ SAS = "https://data.sdss.org/sas/dr17/eboss/photoObj/frames/301/"
17
+ V_POINTS, V_STACK = 22.0, 23.5
18
+
19
+
20
+ def exposures(rows, V=None):
21
+ if V is None or V > V_STACK:
22
+ return []
23
+ out = {}
24
+ for r in rows:
25
+ if r["Telescope/Instrument"] in INSTRUMENTS and r["Image"].startswith("frame-") and r["Image"][6] in "ugriz":
26
+ out.setdefault(r["Image"], dict(archive="sdss", id=r["Image"], mjd=float(r["MJD"]), exptime=float(r["Exptime"]),
27
+ filt=r["Image"][6], inst="SDSS", site=SITE, points=V <= V_POINTS))
28
+ return list(out.values())
29
+
30
+
31
+ def url(frame):
32
+ """SAS URL of 'frame-r-005194-3-0236'."""
33
+ _, _, run, camcol, _ = frame.split("-")
34
+ return f"{SAS}{int(run)}/{camcol}/{frame}.fits.bz2"
35
+
36
+
37
+ def fetch(exp, pos, outdir):
38
+ from astropy.io import fits
39
+ from astropy.time import Time
40
+ from astropy.wcs import WCS
41
+ path = outdir / f"sdss_{exp['id'][6:]}.fits.fz"
42
+ ra, dec = pos(exp["mjd"] + exp["exptime"] / 2 / 86400, SITE)
43
+ if stale(path, ra, dec, PAD / PIX):
44
+ with fits.open(io.BytesIO(bz2.decompress(net.fetch(url(exp["id"]), timeout=600)))) as f:
45
+ h, d = f[0].header, f[0].data
46
+ mid = Time(float(h["TAI"]) / 86400, format="mjd", scale="tai").utc.mjd + float(h["EXPTIME"]) / 2 / 86400
47
+ b = box(WCS(h), d.shape[1], d.shape[0], *pos(mid, SITE), PAD / PIX)
48
+ if b is None:
49
+ return []
50
+ write_cut(path, d[b[1]:b[3], b[0]:b[2]], h, mid, float(h["EXPTIME"]), exp["filt"], SITE, "SDSS", exp["id"], b[0], b[1],
51
+ saturate=1e30) # ponytail: no saturation level in nanomaggies; saturated stars are r < 14, Gaia fit rejects them
52
+ return [path]