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.
- orbitsift/__init__.py +2 -0
- orbitsift/_native.py +13 -0
- orbitsift/ades.py +166 -0
- orbitsift/archives/__init__.py +244 -0
- orbitsift/archives/cadc.py +97 -0
- orbitsift/archives/decam_geom.json +1 -0
- orbitsift/archives/eso.py +213 -0
- orbitsift/archives/hsc_geom.json +2378 -0
- orbitsift/archives/ing.py +70 -0
- orbitsift/archives/listing.py +22 -0
- orbitsift/archives/noirlab.py +302 -0
- orbitsift/archives/ps1.py +59 -0
- orbitsift/archives/sdss.py +52 -0
- orbitsift/archives/smoka.py +369 -0
- orbitsift/blind.py +558 -0
- orbitsift/catalog.py +328 -0
- orbitsift/cli.py +2200 -0
- orbitsift/config.py +85 -0
- orbitsift/confirm.py +1030 -0
- orbitsift/data/nsc_dr2_k4m_ksb.csv.gz +0 -0
- orbitsift/dense.py +788 -0
- orbitsift/dynamics.py +235 -0
- orbitsift/expindex.py +456 -0
- orbitsift/extend.py +690 -0
- orbitsift/external.py +204 -0
- orbitsift/extract.py +148 -0
- orbitsift/growth.py +224 -0
- orbitsift/images.py +676 -0
- orbitsift/itf.py +154 -0
- orbitsift/known.py +716 -0
- orbitsift/link.py +509 -0
- orbitsift/lov.py +642 -0
- orbitsift/mcp_server.py +164 -0
- orbitsift/multiyear.py +409 -0
- orbitsift/net.py +265 -0
- orbitsift/orbit.py +614 -0
- orbitsift/plugins.py +97 -0
- orbitsift/precovery.py +187 -0
- orbitsift/presets/a2.json +85 -0
- orbitsift/presets/confirm_v1.json +190 -0
- orbitsift/presets/confirm_v2.json +236 -0
- orbitsift/presets/lostrec.json +74 -0
- orbitsift/recover.py +377 -0
- orbitsift/rubin.py +328 -0
- orbitsift/survey.py +268 -0
- orbitsift/tiles.py +58 -0
- orbitsift/unused.py +103 -0
- orbitsift/vet.py +304 -0
- orbitsift/workflow/__init__.py +5 -0
- orbitsift/workflow/models.py +103 -0
- orbitsift/workflow/sqlite.py +189 -0
- orbitsift-0.1.0.dist-info/METADATA +443 -0
- orbitsift-0.1.0.dist-info/RECORD +56 -0
- orbitsift-0.1.0.dist-info/WHEEL +4 -0
- orbitsift-0.1.0.dist-info/entry_points.txt +3 -0
- orbitsift-0.1.0.dist-info/licenses/LICENSE +28 -0
orbitsift/__init__.py
ADDED
orbitsift/_native.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Optional compiled kernels (the ``orbitsift-native`` Rust extension, see native/README.md).
|
|
2
|
+
|
|
3
|
+
``lib`` is the extension module, or None when it is not installed (or ORBITSIFT_NATIVE=0): every caller
|
|
4
|
+
then runs its numpy code, which gives the same results.
|
|
5
|
+
"""
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
lib = None
|
|
9
|
+
if os.environ.get("ORBITSIFT_NATIVE", "1") != "0":
|
|
10
|
+
try:
|
|
11
|
+
import orbitsift_native as lib
|
|
12
|
+
except ImportError:
|
|
13
|
+
pass
|
orbitsift/ades.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""ADES PSV (pipe-separated) observation files: writer, reader, and the MPC *validator*.
|
|
2
|
+
|
|
3
|
+
orbitsift never submits to the MPC. Validate your file, review it, and submit it yourself
|
|
4
|
+
(see README, "Reporting to the MPC").
|
|
5
|
+
"""
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
import urllib.error
|
|
9
|
+
import uuid
|
|
10
|
+
from datetime import datetime, timedelta
|
|
11
|
+
|
|
12
|
+
from . import net
|
|
13
|
+
|
|
14
|
+
VALIDATOR_URL = "https://minorplanetcenter.net/submit_psv_test"
|
|
15
|
+
COLUMNS = ["trkSub", "mode", "stn", "obsTime", "ra", "dec", "rmsRA", "rmsDec", "astCat", "mag", "rmsMag", "band"]
|
|
16
|
+
_FMT = {"trkSub": "{:<8}", "mode": "{:<4}", "stn": "{:<4}", "obsTime": "{:<24}", "ra": "{:11.7f}", "dec": "{:+11.7f}",
|
|
17
|
+
"rmsRA": "{:5.3f}", "rmsDec": "{:6.3f}", "astCat": "{:<6}", "mag": "{:5.2f}", "rmsMag": "{:6.2f}", "band": "{}"}
|
|
18
|
+
_WIDTH = {"trkSub": 8, "mode": 4, "stn": 4, "obsTime": 24, "ra": 11, "dec": 11, "rmsRA": 5, "rmsDec": 6, "astCat": 6,
|
|
19
|
+
"mag": 5, "rmsMag": 6, "band": 4}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def obs_time(mjd_utc):
|
|
23
|
+
"""UTC MJD -> ADES obsTime string (ISO 8601, milliseconds, Z)."""
|
|
24
|
+
t = datetime(1858, 11, 17) + timedelta(milliseconds=round(float(mjd_utc) * 86400000))
|
|
25
|
+
return t.strftime("%Y-%m-%dT%H:%M:%S.") + f"{t.microsecond // 1000:03d}Z"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def initials(name):
|
|
29
|
+
"""'Firstname Lastname' -> 'F. Lastname' (ADES name style); names already initialled are kept."""
|
|
30
|
+
parts = name.split()
|
|
31
|
+
if len(parts) < 2 or re.fullmatch(r"([A-Z]\.)+", parts[0]):
|
|
32
|
+
return name.strip()
|
|
33
|
+
return " ".join(p[0] + "." for p in parts[:-1]) + " " + parts[-1]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def header(submitter, observers, measurers=None, stn="W84", design="Reflector", aperture=4.0, detector="CCD",
|
|
37
|
+
comment=(), version="2017"):
|
|
38
|
+
"""ADES header lines for one observation block (observatory, submitter, observers, measurers,
|
|
39
|
+
telescope, comment)."""
|
|
40
|
+
if not submitter:
|
|
41
|
+
raise ValueError("ADES needs a submitter name (config [ades] submitter or --submitter)")
|
|
42
|
+
if not observers:
|
|
43
|
+
raise ValueError("ADES needs the observers of the images (config [ades] observers or FITS OBSERVER)")
|
|
44
|
+
for v in [submitter, stn, design, detector, *observers, *(measurers or []), *comment]:
|
|
45
|
+
if "\n" in str(v) or "\r" in str(v):
|
|
46
|
+
raise ValueError(f"ADES header field with a line break: {v!r}")
|
|
47
|
+
L = [f"# version={version}"] if version else []
|
|
48
|
+
L += ["# observatory", f"! mpcCode {stn}", "# submitter", f"! name {submitter}", "# observers"]
|
|
49
|
+
L += [f"! name {n}" for n in observers]
|
|
50
|
+
L += ["# measurers"] + [f"! name {n}" for n in (measurers or [submitter])]
|
|
51
|
+
L += ["# telescope", f"! design {design}", f"! aperture {aperture}", f"! detector {detector}"]
|
|
52
|
+
if comment:
|
|
53
|
+
L += ["# comment"] + [f"! line {c}" for c in comment]
|
|
54
|
+
return L
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def row(trk, mjd_utc, ra, dec, rms_ra, rms_dec, mag, rms_mag, band, stn="W84", ast_cat="Gaia2", mode="CCD"):
|
|
58
|
+
"""One PSV data line; rmsRA is the RA error times cos(Dec), in arcsec."""
|
|
59
|
+
v = dict(trkSub=trk, mode=mode, stn=stn, obsTime=obs_time(mjd_utc), ra=ra, dec=dec, rmsRA=rms_ra, rmsDec=rms_dec,
|
|
60
|
+
astCat=ast_cat, mag=mag, rmsMag=rms_mag, band=band)
|
|
61
|
+
if len(trk) > 8:
|
|
62
|
+
raise ValueError(f"trkSub '{trk}' longer than 8 characters")
|
|
63
|
+
return "|".join(" " * _WIDTH[c] if v[c] is None else _FMT[c].format(v[c]) for c in COLUMNS)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def column_line():
|
|
67
|
+
return "|".join(f"{c:<{_WIDTH[c]}}" for c in COLUMNS[:-1]) + "|band"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def write(path, blocks):
|
|
71
|
+
"""Write blocks [(header lines, data lines)] to an ADES PSV file (the version line only once)."""
|
|
72
|
+
out = []
|
|
73
|
+
for k, (hdr, rows) in enumerate(blocks):
|
|
74
|
+
out += [h for h in hdr if not (k and h.startswith("# version"))]
|
|
75
|
+
out += [column_line()] + sorted(rows, key=lambda r: (r.split("|")[0], r.split("|")[3]))
|
|
76
|
+
with open(path, "w") as f:
|
|
77
|
+
f.write("\n".join(out) + "\n")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def read(path):
|
|
81
|
+
"""ADES PSV -> {track id: [dict(mjd, ra, dec, rmsRA, rmsDec, mag, band, stn, astCat), ...]} sorted by time.
|
|
82
|
+
Track id = trkSub, else provID, else permID. Header lines are ignored; any column order works."""
|
|
83
|
+
from astropy.time import Time
|
|
84
|
+
out, cols = {}, None
|
|
85
|
+
for line in open(path):
|
|
86
|
+
line = line.rstrip("\n")
|
|
87
|
+
if not line.strip() or line[0] in "#!":
|
|
88
|
+
continue
|
|
89
|
+
f = [x.strip() for x in line.split("|")]
|
|
90
|
+
if "obsTime" in f:
|
|
91
|
+
cols = f
|
|
92
|
+
continue
|
|
93
|
+
if cols is None:
|
|
94
|
+
raise ValueError(f"{path}: data line before the column line")
|
|
95
|
+
r = dict(zip(cols, f))
|
|
96
|
+
trk = r.get("trkSub") or r.get("provID") or r.get("permID")
|
|
97
|
+
num = lambda k, d=None: float(r[k]) if r.get(k) else d
|
|
98
|
+
out.setdefault(trk, []).append(dict(mjd=float(Time(r["obsTime"].rstrip("Z"), scale="utc").mjd), ra=float(r["ra"]),
|
|
99
|
+
dec=float(r["dec"]), rmsRA=num("rmsRA"), rmsDec=num("rmsDec"),
|
|
100
|
+
mag=num("mag"), band=r.get("band", ""), stn=r.get("stn", "W84"),
|
|
101
|
+
astCat=r.get("astCat", "")))
|
|
102
|
+
return {k: sorted(v, key=lambda o: o["mjd"]) for k, v in out.items()}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# astCat that matches the reference catalogue of each kind of measurement written by orbitsift
|
|
106
|
+
AST_CAT = {"nsc": "Gaia2", "forced": "Gaia3", "extend": "Gaia3"}
|
|
107
|
+
|
|
108
|
+
# extend points: the cutout's instrument (INSTRUME written by the archive connector) -> (MPC station, aperture [m],
|
|
109
|
+
# telescope). The station is the archive's SITE except Subaru (T09, the connector's parallax uses 568) and 90Prime
|
|
110
|
+
# (V00, as for NSC rows; the connector uses 695): metres apart, no effect on a distant object's parallax.
|
|
111
|
+
# An instrument missing here is not exported.
|
|
112
|
+
ARCHIVAL = {"DECam": ("W84", 4.0, "DECam (CTIO Blanco 4m)"), "Mosaic2": ("807", 4.0, "Mosaic2 (CTIO Blanco 4m)"),
|
|
113
|
+
"Mosaic3": ("695", 4.0, "Mosaic3 (Kitt Peak Mayall 4m)"), "Mosaic1.1": ("695", 4.0, "Mosaic1.1 (Kitt Peak Mayall 4m)"),
|
|
114
|
+
"90prime": ("V00", 2.3, "90Prime (Kitt Peak Bok 2.3m)"), "MegaCam": ("568", 3.6, "MegaCam (CFHT 3.6m, Maunakea)"),
|
|
115
|
+
"HSC": ("T09", 8.2, "Hyper Suprime-Cam (Subaru 8.2m)"), "SuprimeCam": ("T09", 8.2, "Suprime-Cam (Subaru 8.2m)"),
|
|
116
|
+
"OmegaCAM": ("309", 2.6, "OmegaCAM (VST 2.6m, Paranal)"), "VIMOS": ("309", 8.2, "VIMOS (VLT 8.2m, Paranal)"),
|
|
117
|
+
"WFI": ("809", 2.2, "WFI (MPG/ESO 2.2m, La Silla)"), "EMMI": ("809", 3.58, "EMMI (NTT 3.58m, La Silla)"),
|
|
118
|
+
"GPC1": ("F51", 1.8, "GPC1 (Pan-STARRS1 1.8m, Haleakala)"), "SDSS": ("645", 2.5, "SDSS 2.5m (Apache Point)"),
|
|
119
|
+
"INT/WFC": ("950", 2.5, "WFC (INT 2.5m, La Palma)")}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def lint(path, expect_astcat=None):
|
|
123
|
+
"""Warnings about an ADES file before a human submits it: [dict(code, trk, message, ...)].
|
|
124
|
+
|
|
125
|
+
singleton_night: a night with one observation of a track (the MPC asks for >= 2 per night, and
|
|
126
|
+
single observations are rarely linked); mixed_astcat: one track with positions reduced against
|
|
127
|
+
different catalogues; astcat_mismatch: astCat differs from ``expect_astcat`` (the catalogue the
|
|
128
|
+
positions were actually tied to: Gaia2 for NSC DR2, Gaia3 for forced measurements)."""
|
|
129
|
+
out = []
|
|
130
|
+
for trk, obs in read(path).items():
|
|
131
|
+
per = {}
|
|
132
|
+
for o in obs: # ponytail: nights split at 12 UT (right for the Americas), local noon if needed
|
|
133
|
+
per.setdefault(math.floor(o["mjd"] - 0.5), []).append(o)
|
|
134
|
+
for n, os_ in sorted(per.items()):
|
|
135
|
+
if len(os_) == 1:
|
|
136
|
+
d = obs_time(n)[:10]
|
|
137
|
+
out.append(dict(code="singleton_night", trk=trk, night=d,
|
|
138
|
+
message=f"{trk}: one observation in the night starting {d}; the MPC discourages single "
|
|
139
|
+
"observations per night (drop it or add a second measurement)"))
|
|
140
|
+
cats = sorted({o["astCat"] for o in obs})
|
|
141
|
+
if len(cats) > 1:
|
|
142
|
+
out.append(dict(code="mixed_astcat", trk=trk, astcat=cats,
|
|
143
|
+
message=f"{trk}: astCat {', '.join(cats)} in one track; each row must name the catalogue "
|
|
144
|
+
"its own position was reduced against"))
|
|
145
|
+
if expect_astcat and any(c != expect_astcat for c in cats):
|
|
146
|
+
out.append(dict(code="astcat_mismatch", trk=trk, astcat=cats, expected=expect_astcat,
|
|
147
|
+
message=f"{trk}: astCat {', '.join(cats)} but these positions are tied to {expect_astcat}"))
|
|
148
|
+
return out
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def validate(path, email, obj_type="TNO", ack="orbitsift validation"):
|
|
152
|
+
"""Send a PSV file to the MPC's validation-only endpoint (nothing is submitted as observations) and
|
|
153
|
+
return its answer as plain text. The endpoint requires an acknowledgement e-mail address (ac2)."""
|
|
154
|
+
if not email:
|
|
155
|
+
raise ValueError("the MPC validator needs an e-mail address (config [ades] email or --email)")
|
|
156
|
+
b = uuid.uuid4().hex
|
|
157
|
+
body = b"".join(f"--{b}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n".encode()
|
|
158
|
+
for k, v in (("ack", ack), ("ac2", email), ("obj_type", obj_type)))
|
|
159
|
+
body += f"--{b}\r\nContent-Disposition: form-data; name=\"source\"\r\n\r\n".encode()
|
|
160
|
+
body += open(path, "rb").read() + f"\r\n--{b}--\r\n".encode()
|
|
161
|
+
try:
|
|
162
|
+
txt = net.fetch(VALIDATOR_URL, body, {"Content-Type": f"multipart/form-data; boundary={b}"}, timeout=120, retries=1)
|
|
163
|
+
except urllib.error.HTTPError as e:
|
|
164
|
+
txt = e.read()
|
|
165
|
+
txt = re.sub(r"<script.*?</script>|<style.*?</style>", "", txt.decode(errors="replace"), flags=re.S)
|
|
166
|
+
return re.sub(r"\n\s*\n+", "\n", re.sub(r"<[^>]+>", "", txt)).strip()
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Image archives for ``extend``: one small module per archive, all with the same three names.
|
|
2
|
+
|
|
3
|
+
INSTRUMENTS SSOIS 'Telescope/Instrument' values the module handles
|
|
4
|
+
exposures(rows, V) SSOIS rows of those instruments (predicted V of the object) -> [exposure dict]:
|
|
5
|
+
archive, id, mjd (UTC, approximate), exptime, filt, inst, site (MPC code). An exposure
|
|
6
|
+
with a "listed" text cannot be downloaded anonymously: it is only reported, with how to get it.
|
|
7
|
+
fetch(exp, pos, outdir) -> [path]: cutouts of the CCDs where the orbit clones fall; pos(mjd, site) -> (ra, dec)
|
|
8
|
+
arrays of the clone positions. Cutouts are written by ``write_cut``.
|
|
9
|
+
|
|
10
|
+
The exposures themselves come from one CADC SSOIS search per orbit clone (``ssois``), which sends orbital
|
|
11
|
+
elements only, never observations. Downloads are cached; full CCDs go to a temporary directory and are
|
|
12
|
+
deleted once cut.
|
|
13
|
+
"""
|
|
14
|
+
import gzip
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import urllib.parse
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
from .. import config, net
|
|
24
|
+
|
|
25
|
+
SSOIS = "https://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/cadcbin/ssos/ssosclf.pl"
|
|
26
|
+
NAMES = ("cadc", "noirlab", "eso", "ps1", "sdss", "smoka", "ing", "listing")
|
|
27
|
+
COLUMNS = ("Image", "Ext", "MJD", "Filter", "Exptime", "Telescope/Instrument") # kept from SSOIS rows of these archives
|
|
28
|
+
PAD = 130.0 # arcsec around the clone cloud kept in a cutout (the control tracks are 60-120" away)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def connectors(names):
|
|
32
|
+
"""name -> module for the given archive names (see NAMES)."""
|
|
33
|
+
import importlib
|
|
34
|
+
return {n: importlib.import_module(f".{n}", __name__) for n in names}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cache(*parts):
|
|
38
|
+
p = config.cache_dir().joinpath("extend", *parts)
|
|
39
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
return p
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def cached_json(path, make):
|
|
44
|
+
"""JSON in ``path`` (gzipped if it ends in .gz), made by make() the first time."""
|
|
45
|
+
path = Path(path)
|
|
46
|
+
z = path.suffix == ".gz"
|
|
47
|
+
if not path.exists():
|
|
48
|
+
b = json.dumps(make()).encode()
|
|
49
|
+
net.save(path, gzip.compress(b, mtime=0) if z else b)
|
|
50
|
+
b = path.read_bytes()
|
|
51
|
+
return json.loads(gzip.decompress(b) if z else b)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def ssois_query(el, epoch, start, end):
|
|
55
|
+
"""URL and cache file of ``ssois``."""
|
|
56
|
+
q = [("lang", "en"), ("search", "orbel"), ("epoch", epoch)] + [
|
|
57
|
+
(k, f"{el[n]:.7f}") for k, n in (("a", "a"), ("e", "e"), ("i", "i"), ("longi", "node"), ("peri", "peri"), ("anom", "M"))] + [
|
|
58
|
+
("epoch1", start.replace("-", " ")), ("epoch2", end.replace("-", " ")), ("eellipse", ""), ("eunits", "arcseconds"),
|
|
59
|
+
("extres", "yes"), ("xyres", "yes"), ("format", "tsv")]
|
|
60
|
+
url = f"{SSOIS}?{urllib.parse.urlencode(q)}"
|
|
61
|
+
return url, cache("ssois", hashlib.sha256(url.encode()).hexdigest()[:24] + ".json.gz")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def ssois_guard(allow):
|
|
65
|
+
"""Raise unless SSOIS may be used: it receives the object's orbital elements, so designated objects only."""
|
|
66
|
+
try:
|
|
67
|
+
net.require("ssois", allow)
|
|
68
|
+
except net.OutboundBlocked as e:
|
|
69
|
+
raise net.OutboundBlocked(f"{e}; or give a local exposure table (extend.run exposures=..., orbitsift extend "
|
|
70
|
+
"--exposures)") from None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def ssois(el, epoch, start, end, allow=False):
|
|
74
|
+
"""SSOIS 'orbel' search: images that may hold an object with these heliocentric ecliptic J2000 elements
|
|
75
|
+
(dict a, e, i, node, peri, M at ``epoch``, 'YYYY-MM-DD' at 0h TT) between two ISO dates -> list of row dicts
|
|
76
|
+
(COLUMNS, rows of instruments some connector handles). Only the six elements are sent, and only with ``allow``
|
|
77
|
+
(designated objects; see ``ssois_guard``). Cached."""
|
|
78
|
+
url, path = ssois_query(el, epoch, start, end)
|
|
79
|
+
if not path.exists():
|
|
80
|
+
ssois_guard(allow)
|
|
81
|
+
|
|
82
|
+
def get():
|
|
83
|
+
txt = net.fetch(url, timeout=900).decode(errors="replace")
|
|
84
|
+
if not txt.startswith("Image"):
|
|
85
|
+
raise net.ServiceError("SSOIS: " + txt[:300])
|
|
86
|
+
L = txt.strip().split("\n")
|
|
87
|
+
head = L[0].split("\t")
|
|
88
|
+
known = {i for m in connectors(NAMES).values() for i in m.INSTRUMENTS}
|
|
89
|
+
rows = [dict(zip(head, x.split("\t"))) for x in L[1:]]
|
|
90
|
+
return [{k: r[k] for k in COLUMNS} for r in rows if r.get("Telescope/Instrument") in known]
|
|
91
|
+
return cached_json(path, get)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def box(w, nx, ny, ra, dec, pad):
|
|
95
|
+
"""Pixel box (x0, y0, x1, y1) of the positions (ra, dec) on an image (astropy WCS w, nx x ny) plus pad [px],
|
|
96
|
+
clipped to the image; None if no position is within pad of it."""
|
|
97
|
+
x, y = w.all_world2pix(np.asarray(ra, float), np.asarray(dec, float), 0, quiet=True)
|
|
98
|
+
m = np.isfinite(x) & np.isfinite(y) & (x > -pad) & (x < nx + pad) & (y > -pad) & (y < ny + pad)
|
|
99
|
+
if not m.any():
|
|
100
|
+
return None
|
|
101
|
+
x, y = x[m], y[m]
|
|
102
|
+
b = (int(max(0, x.min() - pad)), int(max(0, y.min() - pad)), int(min(nx, x.max() + pad + 1)), int(min(ny, y.max() + pad + 1)))
|
|
103
|
+
return b if b[2] - b[0] > 20 and b[3] - b[1] > 20 else None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def stale(path, ra, dec, pad):
|
|
107
|
+
"""True if a cached cut is missing or none of these positions is within ``pad`` px of it (the PAD it was cut with):
|
|
108
|
+
cuts are boxed around one object's clones and named by exposure (+ CCD), so another object on the same exposure,
|
|
109
|
+
or a moved cloud, must cut again."""
|
|
110
|
+
path = Path(path)
|
|
111
|
+
if not path.exists():
|
|
112
|
+
return True
|
|
113
|
+
from astropy.io import fits
|
|
114
|
+
from astropy.wcs import WCS
|
|
115
|
+
h = fits.getheader(path, 1)
|
|
116
|
+
return box(WCS(h), int(h.get("ZNAXIS1", h.get("NAXIS1"))), int(h.get("ZNAXIS2", h.get("NAXIS2"))), ra, dec, pad) is None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def section(s):
|
|
120
|
+
"""IRAF section '[x0:x1,y0:y1]' (1-based, inclusive) -> numpy slices (rows, columns)."""
|
|
121
|
+
(x0, x1), (y0, y1) = (sorted(int(v) for v in p.split(":")) for p in s.strip("[] ").split(","))
|
|
122
|
+
return slice(y0 - 1, y1), slice(x0 - 1, x1)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def raw_amp(data, h, bias=None, data_sec=None):
|
|
126
|
+
"""A raw amplifier/CCD: overscan (row medians of BIASSEC) subtracted, trimmed to DATASEC; the header WCS is shifted to
|
|
127
|
+
the trimmed origin. No flat field: the measurement's local background absorbs large scales -> (image, header, level)."""
|
|
128
|
+
a = np.asarray(data, np.float32)
|
|
129
|
+
bs, ds = section(bias or h["BIASSEC"]), section(data_sec or h["DATASEC"])
|
|
130
|
+
ov = np.median(a[ds[0], bs[1]], axis=1)[:, None]
|
|
131
|
+
h = h.copy()
|
|
132
|
+
h["CRPIX1"], h["CRPIX2"] = float(h["CRPIX1"]) - ds[1].start, float(h["CRPIX2"]) - ds[0].start
|
|
133
|
+
return a[ds] - ov, h, float(np.median(ov))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def tan_header(h):
|
|
137
|
+
"""A header astropy can read, RA first: IRAF ZPX (old NOIRLab Mosaic) becomes ZPN with the same radial polynomial (projp0..9;
|
|
138
|
+
the small lngcor/latcor surfaces are dropped), TNX becomes TAN (its polynomial dropped). What is left is smooth and the
|
|
139
|
+
Gaia-tied affine correction of the cut absorbs it locally."""
|
|
140
|
+
import re
|
|
141
|
+
h = h.copy()
|
|
142
|
+
wat = "".join(str(h[k]) for k in sorted(k for k in h if k.startswith("WAT2_"))).replace(" ", "")
|
|
143
|
+
for k in ("CTYPE1", "CTYPE2"):
|
|
144
|
+
v = str(h.get(k, ""))
|
|
145
|
+
if v[5:8] == "ZPX":
|
|
146
|
+
h[k] = v[:5] + "ZPN"
|
|
147
|
+
elif v[5:8] == "TNX":
|
|
148
|
+
h[k] = v[:5] + "TAN"
|
|
149
|
+
if str(h.get("CTYPE2", ""))[5:8] == "ZPN":
|
|
150
|
+
for n, v in re.findall(r"projp(\d)=([-+.\dEe]+)", wat):
|
|
151
|
+
h[f"PV2_{n}"] = float(v)
|
|
152
|
+
for k in [k for k in h if k.startswith("WAT")]:
|
|
153
|
+
del h[k]
|
|
154
|
+
if str(h.get("CTYPE1", "")).startswith("DEC"): # raw 90prime: world axes swapped (rows of CD)
|
|
155
|
+
for a, b in (("CTYPE1", "CTYPE2"), ("CRVAL1", "CRVAL2"), ("CD1_1", "CD2_1"), ("CD1_2", "CD2_2")):
|
|
156
|
+
h[a], h[b] = h.get(b, 0.0), h.get(a, 0.0)
|
|
157
|
+
return h
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def gaia_wcs(img, ra0, dec0, pix, mid, radius, angles=np.arange(-3, 3.1, 0.5)):
|
|
161
|
+
"""TAN WCS header of a raw image with no sky WCS (pointing ra0, dec0 somewhere within ``radius`` deg of it, pixel
|
|
162
|
+
scale ``pix`` ["] known), solved on Gaia DR3: the brightest peaks are matched to Gaia G < 19 for the 8 axis
|
|
163
|
+
orientations x small rotations (histogram of pixel offsets), then a linear fit of the matched pairs. None if
|
|
164
|
+
fewer than 8 stars match."""
|
|
165
|
+
from scipy import ndimage
|
|
166
|
+
from astropy.io import fits
|
|
167
|
+
from .. import extend
|
|
168
|
+
d = np.nan_to_num(np.asarray(img, float))
|
|
169
|
+
d = d - ndimage.median_filter(d[::8, ::8], 9).repeat(8, 0).repeat(8, 1)[:d.shape[0], :d.shape[1]]
|
|
170
|
+
sig = 1.4826 * np.median(np.abs(d - np.median(d)))
|
|
171
|
+
sm = ndimage.gaussian_filter(d, 2)
|
|
172
|
+
yy, xx = np.nonzero((sm == ndimage.maximum_filter(sm, 11)) & (sm > 5 * sig) & (d < 0.8 * d.max()))
|
|
173
|
+
o = np.argsort(-sm[yy, xx])[:150]
|
|
174
|
+
px = np.c_[xx[o], yy[o]].astype(float)
|
|
175
|
+
gra, gde, g = extend._gaia(ra0, dec0, radius, mid)
|
|
176
|
+
k = np.argsort(np.where(np.isfinite(g), g, 99))[:600]
|
|
177
|
+
gra, gde = gra[k], gde[k]
|
|
178
|
+
c = np.cos(np.radians(dec0))
|
|
179
|
+
xi, eta = ((gra - ra0 + 180) % 360 - 180) * c * 3600 / pix, (gde - dec0) * 3600 / pix # flat sky: refined below
|
|
180
|
+
best = (0,)
|
|
181
|
+
for flip in (1, -1):
|
|
182
|
+
for base in (0, 90, 180, 270):
|
|
183
|
+
for a in angles:
|
|
184
|
+
t = np.radians(base + a)
|
|
185
|
+
R = np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]]) @ np.diag([flip, 1])
|
|
186
|
+
q = np.c_[xi, eta] @ R.T
|
|
187
|
+
dx, dy = (px[:, None, 0] - q[None, :, 0]).ravel(), (px[:, None, 1] - q[None, :, 1]).ravel()
|
|
188
|
+
lim = 3600 * radius / pix + max(d.shape)
|
|
189
|
+
H, xe, ye = np.histogram2d(dx, dy, bins=int(2 * lim / 20), range=[[-lim, lim], [-lim, lim]])
|
|
190
|
+
i, j = np.unravel_index(H.argmax(), H.shape)
|
|
191
|
+
if H[i, j] > best[0]:
|
|
192
|
+
best = (H[i, j], R, xe[i] + 10, ye[j] + 10)
|
|
193
|
+
if best[0] < 10:
|
|
194
|
+
return None
|
|
195
|
+
_, R, ox, oy = best
|
|
196
|
+
q = np.c_[xi, eta] @ R.T + [ox, oy]
|
|
197
|
+
dd = np.hypot(px[:, None, 0] - q[None, :, 0], px[:, None, 1] - q[None, :, 1])
|
|
198
|
+
for tol in (20.0, 6.0, 2.0):
|
|
199
|
+
i, j = np.nonzero((dd < tol) & (dd == dd.min(1, keepdims=True)))
|
|
200
|
+
if len(i) < 8:
|
|
201
|
+
return None
|
|
202
|
+
A = np.c_[np.ones(len(i)), px[i]]
|
|
203
|
+
h = fits.Header()
|
|
204
|
+
h["CTYPE1"], h["CTYPE2"], h["CRVAL1"], h["CRVAL2"] = "RA---TAN", "DEC--TAN", float(gra[j].mean()), float(gde[j].mean())
|
|
205
|
+
# tangent-plane coordinates of the matched Gaia stars about CRVAL, as a linear function of pixel
|
|
206
|
+
from astropy.wcs import WCS
|
|
207
|
+
w0 = WCS(h)
|
|
208
|
+
w0.wcs.crpix, w0.wcs.cd = [1, 1], np.eye(2) / 3600
|
|
209
|
+
u, v = w0.all_world2pix(gra[j], gde[j], 0)
|
|
210
|
+
cu, cv = np.linalg.lstsq(A, u, rcond=None)[0], np.linalg.lstsq(A, v, rcond=None)[0]
|
|
211
|
+
CD = np.array([cu[1:], cv[1:]]) / 3600
|
|
212
|
+
crpix = np.linalg.solve(CD * 3600, -np.array([cu[0], cv[0]]))
|
|
213
|
+
h["CRPIX1"], h["CRPIX2"] = float(crpix[0] + 1), float(crpix[1] + 1)
|
|
214
|
+
h["CD1_1"], h["CD1_2"], h["CD2_1"], h["CD2_2"] = (float(x) for x in CD.ravel())
|
|
215
|
+
w = WCS(h)
|
|
216
|
+
gx, gy = w.all_world2pix(gra, gde, 0)
|
|
217
|
+
dd = np.hypot(px[:, None, 0] - gx[None, :], px[:, None, 1] - gy[None, :])
|
|
218
|
+
h["WCSNMAT"] = len(i)
|
|
219
|
+
return h
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def write_cut(path, data, header, mid, exptime, filt, site, inst, origin, x0=0, y0=0, saturate=None):
|
|
223
|
+
"""A cutout as a tile-compressed FITS file (RICE, noise-quantised at 1/2 of the background sigma): primary
|
|
224
|
+
header with MJD-MID (UTC), EXPTIME, FILTER, SITE, INSTRUME, ORIGFILE; image in HDU 1 with the WCS of ``header``
|
|
225
|
+
shifted by the cut origin (x0, y0)."""
|
|
226
|
+
from astropy.io import fits
|
|
227
|
+
skip = ("SIMPLE", "XTENSION", "BITPIX", "NAXIS", "PCOUNT", "GCOUNT", "EXTEND", "BSCALE", "BZERO", "CHECKSUM", "DATASUM",
|
|
228
|
+
"COMMENT", "HISTORY", "")
|
|
229
|
+
h = fits.Header([c for c in header.cards if not c.keyword.startswith(("Z", "TTYPE", "TFORM", "NAXIS")) and c.keyword not in skip])
|
|
230
|
+
h["CRPIX1"] = float(header["CRPIX1"]) - x0
|
|
231
|
+
h["CRPIX2"] = float(header["CRPIX2"]) - y0
|
|
232
|
+
if saturate is not None:
|
|
233
|
+
h["SATURATE"] = float(saturate)
|
|
234
|
+
p0 = fits.Header()
|
|
235
|
+
for k, v in (("MJD-MID", float(mid)), ("EXPTIME", float(exptime)), ("FILTER", str(filt)), ("SITE", str(site)),
|
|
236
|
+
("INSTRUME", str(inst)), ("ORIGFILE", str(origin)[:68])):
|
|
237
|
+
p0[k] = v
|
|
238
|
+
path = Path(path)
|
|
239
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
240
|
+
tmp = path.with_suffix(".part")
|
|
241
|
+
fits.HDUList([fits.PrimaryHDU(header=p0), fits.CompImageHDU(np.asarray(data, np.float32), header=h, compression_type="RICE_1",
|
|
242
|
+
quantize_level=2.0, dither_seed=1)]).writeto(tmp, overwrite=True)
|
|
243
|
+
os.replace(tmp, path)
|
|
244
|
+
return path
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""CADC: CFHT MegaCam images (Elixir-processed 'p' files, public): cut on the server per CCD, or (by id) whole CCD
|
|
2
|
+
extensions by file name, cut here."""
|
|
3
|
+
import io
|
|
4
|
+
import urllib.parse
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from .. import expindex, net
|
|
9
|
+
from . import PAD, box, cache, stale, write_cut
|
|
10
|
+
|
|
11
|
+
INSTRUMENTS = ("CFHT/MegaCam",)
|
|
12
|
+
BASE = "https://ws.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub/CFHT/"
|
|
13
|
+
SITE = "568"
|
|
14
|
+
PIX = 0.187
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def exposures(rows, V=None):
|
|
18
|
+
"""Broad-band MegaCam rows (u g r i z, gri) of >= 30 s."""
|
|
19
|
+
out = {}
|
|
20
|
+
for r in rows:
|
|
21
|
+
f = r["Filter"]
|
|
22
|
+
if r["Telescope/Instrument"] in INSTRUMENTS and f[:1].lower() in "ugriz" and "CAHK" not in f.upper() and float(r["Exptime"]) >= 30:
|
|
23
|
+
out.setdefault(r["Image"], dict(archive="cadc", id=r["Image"], mjd=float(r["MJD"]), exptime=float(r["Exptime"]),
|
|
24
|
+
filt=f.split(".")[0].lower(), inst="MegaCam", site=SITE))
|
|
25
|
+
return list(out.values())
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def headers(oid):
|
|
29
|
+
"""Primary + extension headers of a MegaCam file (one small request, cached)."""
|
|
30
|
+
from astropy.io.fits import Header
|
|
31
|
+
p = cache("cfht", f"{oid}.hdr")
|
|
32
|
+
if not p.exists():
|
|
33
|
+
net.save(p, net.fetch(f"{BASE}{oid}.fits.fz?fhead=true", timeout=300))
|
|
34
|
+
out, cur = [], []
|
|
35
|
+
for card in p.read_bytes().decode("latin-1").split("\n"):
|
|
36
|
+
if card.startswith("END") and not card[3:].strip():
|
|
37
|
+
out.append(Header.fromstring("\n".join(cur), sep="\n"))
|
|
38
|
+
cur = []
|
|
39
|
+
elif card.strip() and not card.startswith(("COMMENT", "HISTORY")):
|
|
40
|
+
cur.append(card)
|
|
41
|
+
return out
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def ccd_by_id(oid, n):
|
|
45
|
+
"""One whole extension of a MegaCam file, asked for by file name and extension number only (no pixel range, so
|
|
46
|
+
nothing about a position); kept in <ccd_cache>/cfht (images.CCD_CACHE, else <cache>/extend/cfht/ccd)."""
|
|
47
|
+
from pathlib import Path
|
|
48
|
+
from .. import images
|
|
49
|
+
p = (Path(images.CCD_CACHE) / "cfht" if images.CCD_CACHE else cache("cfht", "ccd", "x").parent) / f"{oid}_{n:02d}.fits.fz"
|
|
50
|
+
if not p.exists():
|
|
51
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
net.save(p, net.fetch(f"{BASE}{oid}.fits.fz?cutout=%5B{n}%5D", timeout=900))
|
|
53
|
+
return p
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def fetch(exp, pos, outdir):
|
|
57
|
+
"""The CCDs of a MegaCam exposure that hold the positions, cut around them. ``exp['by_id']``: the whole extension is
|
|
58
|
+
fetched by file name (``ccd_by_id``) and cut here; otherwise the cut is made by the server, which receives the box
|
|
59
|
+
(``net.require('cutouts')``)."""
|
|
60
|
+
by_id = exp.get("by_id")
|
|
61
|
+
if not by_id:
|
|
62
|
+
net.require("cutouts") # the cutout box gives the target's position to ~2'
|
|
63
|
+
from astropy.io import fits
|
|
64
|
+
from astropy.wcs import WCS
|
|
65
|
+
H = headers(exp["id"])
|
|
66
|
+
hh = dict(H[1]) if len(H) > 1 else {}
|
|
67
|
+
hh.update({k: v for k, v in H[0].items() if k})
|
|
68
|
+
mid = expindex.mid_time(hh, "MegaCam")[0] # shutter mid-time (MJD-OBS is the start of the observation)
|
|
69
|
+
ra, dec = pos(mid, SITE)
|
|
70
|
+
paths = []
|
|
71
|
+
for n, h in enumerate(H[1:], 1):
|
|
72
|
+
if "CRVAL1" not in h:
|
|
73
|
+
continue
|
|
74
|
+
nx, ny = int(h.get("ZNAXIS1", h.get("NAXIS1"))), int(h.get("ZNAXIS2", h.get("NAXIS2")))
|
|
75
|
+
hw = h.copy()
|
|
76
|
+
hw["NAXIS"], hw["NAXIS1"], hw["NAXIS2"] = 2, nx, ny
|
|
77
|
+
pad = exp.get("pad", PAD)
|
|
78
|
+
if by_id: # by id: only a CCD that holds a position is fetched
|
|
79
|
+
x, y = WCS(hw).all_world2pix(np.atleast_1d(ra), np.atleast_1d(dec), 0, quiet=True)
|
|
80
|
+
if not ((x >= 0) & (x < nx) & (y >= 0) & (y < ny)).any():
|
|
81
|
+
continue
|
|
82
|
+
b = box(WCS(hw), nx, ny, ra, dec, pad / PIX)
|
|
83
|
+
path = outdir / f"cfht_{exp['id']}_{n:02d}.fits.fz"
|
|
84
|
+
if stale(path, ra, dec, pad / PIX):
|
|
85
|
+
if by_id:
|
|
86
|
+
with fits.open(ccd_by_id(exp["id"], n)) as f:
|
|
87
|
+
e = next(x for x in f if x.data is not None)
|
|
88
|
+
write_cut(path, e.data[b[1]:b[3], b[0]:b[2]].astype(np.float32), e.header, mid, hh["EXPTIME"], exp["filt"],
|
|
89
|
+
SITE, "MegaCam", f"{exp['id']}[{n}]", b[0], b[1], saturate=float(h.get("SATURATE", 65000)))
|
|
90
|
+
else:
|
|
91
|
+
cut = urllib.parse.quote(f"[{n}][{b[0] + 1}:{b[2]},{b[1] + 1}:{b[3]}]")
|
|
92
|
+
with fits.open(io.BytesIO(net.fetch(f"{BASE}{exp['id']}.fits.fz?cutout={cut}", timeout=600))) as f:
|
|
93
|
+
e = next(x for x in f if x.data is not None) # the server shifts CRPIX to the cut
|
|
94
|
+
write_cut(path, e.data.astype(np.float32), e.header, mid, hh["EXPTIME"], exp["filt"], SITE, "MegaCam",
|
|
95
|
+
f"{exp['id']}[{n}]", saturate=float(h.get("SATURATE", 65000)))
|
|
96
|
+
paths.append(path)
|
|
97
|
+
return paths
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"0": [-0.30916, 0.90457], "1": [0.0016, 0.90387], "2": [0.31231, 0.9035], "3": [-0.46455, 0.74083], "4": [-0.15381, 0.74072], "5": [0.15693, 0.74005], "6": [0.46751, 0.73902], "7": [-0.62008, 0.57673], "8": [-0.30959, 0.5768], "9": [0.00133, 0.57622], "10": [0.3121, 0.57545], "11": [0.62259, 0.57427], "12": [-0.77564, 0.41247], "13": [-0.4656, 0.41261], "14": [-0.15467, 0.41231], "15": [0.15652, 0.41141], "16": [0.46723, 0.41083], "17": [0.7775, 0.40989], "18": [-0.77596, 0.24851], "19": [-0.46608, 0.24803], "20": [-0.15518, 0.24764], "21": [0.15613, 0.24707], "22": [0.4673, 0.24633], "23": [0.77731, 0.24561], "24": [-0.93138, 0.08435], "25": [-0.62171, 0.08368], "26": [-0.31115, 0.08266], "27": [0.00037, 0.0825], "28": [0.31148, 0.0818], "29": [0.62241, 0.08135], "30": [0.93199, 0.08104], "31": [-0.93184, -0.08015], "32": [-0.62206, -0.08126], "33": [-0.31147, -0.08189], "34": [-0.00021, -0.08241], "35": [0.3109, -0.08309], "36": [0.62166, -0.0829], "37": [0.93148, -0.08313], "38": [-0.77715, -0.24559], "39": [-0.46722, -0.24603], "40": [-0.15614, -0.24675], "41": [0.15516, -0.24755], "42": [0.4661, -0.24785], "43": [0.77627, -0.24754], "44": [-0.77721, -0.40976], "45": [-0.46763, -0.41041], "46": [-0.15646, -0.41146], "47": [0.15455, -0.41214], "48": [0.46596, -0.41199], "49": [0.77573, -0.41203], "50": [-0.6225, -0.57416], "51": [-0.31206, -0.57529], "52": [-0.00095, -0.57604], "53": [0.31017, -0.57646], "54": [0.62024, -0.57639], "55": [-0.46747, -0.73885], "56": [-0.15634, -0.73996], "57": [0.15466, -0.74038], "58": [0.46506, -0.74021], "59": [-0.31249, -0.90346], "60": [0.30953, -0.90443]}
|