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/net.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""HTTP GET/POST with retries, exponential backoff and a per-host politeness limit.
|
|
2
|
+
|
|
3
|
+
Every web service used here (Data Lab TAP, NOIRLab Astro Data Archive, Gaia TAP, JPL) is shared by
|
|
4
|
+
many people: requests to one host are spaced by ``min_interval_s`` and at most ``max_concurrent``
|
|
5
|
+
run at once in this process (fewer for hosts in ``host_concurrent``).
|
|
6
|
+
|
|
7
|
+
Privacy of undesignated targets: by default (OUTBOUND "field") no request names a position finer than the 1 deg tile
|
|
8
|
+
cell; services that receive an orbit, an epoch + field, or a cutout box run only when asked for per run (``require``);
|
|
9
|
+
every request is appended to <cache>/requests.log; strict mode sends only requests on an allowlist. Each request
|
|
10
|
+
carries a contact in its User-Agent (``contact``).
|
|
11
|
+
"""
|
|
12
|
+
import http.client
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import ssl
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
import urllib.error
|
|
19
|
+
import urllib.parse
|
|
20
|
+
import urllib.request
|
|
21
|
+
|
|
22
|
+
from . import __version__
|
|
23
|
+
|
|
24
|
+
settings = {"min_interval_s": 1.0, "max_concurrent": 2, "retries": 5, "timeout_s": 600, "deadline_s": 1800,
|
|
25
|
+
"contact": "", "log": "", "strict": False, "allow": []}
|
|
26
|
+
# hosts that need a lower limit: JPL sb_ident answers a second concurrent request from one address with 503
|
|
27
|
+
host_concurrent = {"ssd-api.jpl.nasa.gov": 1}
|
|
28
|
+
USER_AGENT = f"orbitsift/{__version__}"
|
|
29
|
+
# What a request may say about a target: "field" (default) sends only field-level positions (the 1 deg tile of
|
|
30
|
+
# ``tiles.tile``, exposure IDs); "exact" sends the exact position/orbit, as before 17 Nov 2026: designated objects only.
|
|
31
|
+
OUTBOUND = os.environ.get("ORBITSIFT_OUTBOUND", "field")
|
|
32
|
+
# Services that receive a target's orbit (ssois), its epoch + field (ident: sb_ident, SkyBoT) or a box around it
|
|
33
|
+
# (cutouts: CADC, PS1 fitscut) run only when asked for in this run: a flag of the command/function, or this list.
|
|
34
|
+
ALLOW = {x.strip() for x in os.environ.get("ORBITSIFT_ALLOW", "").split(",") if x.strip()}
|
|
35
|
+
|
|
36
|
+
# Strict mode (settings "strict", or ORBITSIFT_STRICT=1): only requests matching one of these patterns (re.match on
|
|
37
|
+
# the URL, plus " " and the decoded POST body if any), or one of settings["allow"], are sent; the others raise
|
|
38
|
+
# OutboundBlocked. These are the ones that name no position finer than a 1 deg tile cell: files and headers by ID,
|
|
39
|
+
# bulk catalogues, and the tile-centred queries of field mode. Anything else (e.g. the linker's per-tile box queries)
|
|
40
|
+
# must be listed by the user.
|
|
41
|
+
_A = re.escape("https://astroarchive.noirlab.edu")
|
|
42
|
+
STRICT_ALLOW = [
|
|
43
|
+
_A + r"/api/retrieve/[0-9a-f]{32}/\?hdus=0,\d+$", # one CCD by md5
|
|
44
|
+
_A + r"/api/header/[0-9a-f]{32}/\?format=json$", # headers by md5
|
|
45
|
+
_A + r"/api/adv_search/find/\?limit=\d+&format=json (?!.*_center)", # file search by md5/date
|
|
46
|
+
_A + r"/api/sia/vohdu\?POS=-?\d+\.50000%2C-?\d+\.50000&SIZE=[\d.]+&VERB=3&format=json&limit=\d+&proc_type=instcal&prod_type=image$",
|
|
47
|
+
r"https://datalab\.noirlab\.edu/tap/sync REQUEST=doQuery&LANG=ADQL&FORMAT=csv&QUERY=SELECT [\w, .]+ FROM \w+\.\w+ WHERE "
|
|
48
|
+
r"'t' = Q3C_RADIAL_QUERY\(ra, dec, -?\d+\.5, -?\d+\.5, 0\.75\) AND ra >= -?\d+ AND ra < -?\d+ AND dec >= -?\d+ "
|
|
49
|
+
r"AND dec < -?\d+( AND phot_g_mean_mag < [\d.]+)?$", # catalog.near, one tile cell
|
|
50
|
+
re.escape("https://ssd-api.jpl.nasa.gov/sb_ident.api?") + r"mpc-code=\w+&obs-time=[\d.]+&fov-ra-center=\d\d-\d[02468]-00\.0&"
|
|
51
|
+
r"fov-dec-center=-?\d\d-30-00\.0&", # tile centre
|
|
52
|
+
re.escape("https://ssp.imcce.fr/webservices/skybot/api/conesearch.php?") + r"-ep=[\d.]+&-ra=\d+\.5000000&-dec=-?\d+\.5000000&",
|
|
53
|
+
re.escape("https://ws.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub/CFHT/") + r"\w+\.fits\.fz\?fhead=true$",
|
|
54
|
+
re.escape("https://ws.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub/CFHT/") + r"\w+\.fits\.fz\?cutout=%5B\d+%5D$", # one whole extension
|
|
55
|
+
re.escape("https://dataportal.eso.org/dataportal_new/file/") + r"[\w.:-]+$",
|
|
56
|
+
re.escape("https://data.sdss.org/sas/dr17/") + r"[\w/.-]+$",
|
|
57
|
+
r"https://minorplanetcenter\.net/iau/(MPCORB/(Distant\.txt|MPCORB\.DAT\.gz)|lists/ObsCodes\.html)$",
|
|
58
|
+
r"https://smoka\.nao\.ac\.jp/info\.jsp\?frameid=\w+&date_obs=[\d-]+&i=0$", # by frame
|
|
59
|
+
r"https://smoka\.nao\.ac\.jp/HSCsearch action=Search&instruments=HSC&obs_cat=Science Observation&data_typ=\w+&", # by date
|
|
60
|
+
r"http://casu\.ast\.cam\.ac\.uk/casuadc/ingarch/(displayResults objname=&coordinates=&radius=&nightobs=\d{8}&|"
|
|
61
|
+
r"displayHeader\?recno=\d+$)", # by night/run, record
|
|
62
|
+
re.escape("https://data.minorplanetcenter.net/api/get-obs ") + r'\{"desigs": \["[\w ]+"\]', # by designation
|
|
63
|
+
re.escape("https://ssd-api.jpl.nasa.gov/sbdb_query.api?") + r"fields=[\w,%]+&sb-class=[\w,%]+$",
|
|
64
|
+
re.escape("https://naif.jpl.nasa.gov/pub/naif/generic_kernels/"),
|
|
65
|
+
r'https://api\.lsst\.fink-portal\.org/api/v1/conesearch \{"ra": \d+\.5, "dec": -?\d+\.5, "radius": 3420, "startdate": "[\d-]+", '
|
|
66
|
+
r'"stopdate": "[\d-]+", "columns": "[\w:,]+", "output-format": "csv"\}$', # rubin: one tile cell
|
|
67
|
+
r'https://api\.lsst\.fink-portal\.org/api/v1/sources \{"diaObjectId": "[\d,]+", "columns": "[\w:,]+", "output-format": "csv"\}$',
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ServiceError(RuntimeError):
|
|
72
|
+
"""A web service answered, but with an error instead of data (e.g. a TAP error document)."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class OutboundBlocked(RuntimeError):
|
|
76
|
+
"""A request would send a target's exact position or orbit while OUTBOUND is "field"."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def require(kind, allow=False):
|
|
80
|
+
"""Raise OutboundBlocked unless ``kind`` ("ssois", "ident", "cutouts", "ids") was asked for in this run: ``allow`` (the
|
|
81
|
+
caller's flag), ORBITSIFT_ALLOW, or OUTBOUND "exact"."""
|
|
82
|
+
if not (allow or kind in ALLOW or exact()):
|
|
83
|
+
raise OutboundBlocked(f"{kind}: this service would receive the target's {WHAT[kind]}; for a DESIGNATED object pass "
|
|
84
|
+
f"the per-run flag ({FLAG[kind]}) or set ORBITSIFT_ALLOW={kind}")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
WHAT = {"ssois": "orbital elements", "ident": "tile and epoch (known-object lookup)", "cutouts": "position (a cutout box)",
|
|
88
|
+
"ids": "NSC object ids (they name its detections)"}
|
|
89
|
+
FLAG = {"ssois": "allow_ssois=True / --allow-ssois", "ident": "allow=True / --ident",
|
|
90
|
+
"cutouts": "allow_cutouts=True / --allow-cutouts", "ids": "allow=True / --allow-ids"}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def contact():
|
|
94
|
+
"""Who runs this, for the services' logs (in the User-Agent): settings["contact"] (config [net] contact), else
|
|
95
|
+
ORBITSIFT_CONTACT, else the first line of ~/.orbitsift_contact. Warns once when there is none."""
|
|
96
|
+
global _warned
|
|
97
|
+
c = settings.get("contact") or os.environ.get("ORBITSIFT_CONTACT")
|
|
98
|
+
if not c:
|
|
99
|
+
try:
|
|
100
|
+
with open(os.path.expanduser("~/.orbitsift_contact")) as f:
|
|
101
|
+
c = f.readline()
|
|
102
|
+
except OSError:
|
|
103
|
+
c = ""
|
|
104
|
+
c = " ".join(c.split())
|
|
105
|
+
if not c and not _warned:
|
|
106
|
+
_warned = True
|
|
107
|
+
import warnings
|
|
108
|
+
warnings.warn("orbitsift: no contact for the User-Agent of web requests (archives ask for one): set [net] contact, "
|
|
109
|
+
"ORBITSIFT_CONTACT or ~/.orbitsift_contact, e.g. 'Name; email'", stacklevel=3)
|
|
110
|
+
return c
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
_warned = False
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def user_agent():
|
|
117
|
+
c = contact()
|
|
118
|
+
return f"{USER_AGENT} ({c})" if c else USER_AGENT
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _check(url, data):
|
|
122
|
+
"""Strict-mode allowlist, and the request log (settings["log"]: a file; "" = <cache>/requests.log; "off" = none)."""
|
|
123
|
+
body = urllib.parse.unquote_plus(data.decode(errors="replace")) if data else ""
|
|
124
|
+
line = url + (" " + body if data else "")
|
|
125
|
+
ok = not (settings.get("strict") or os.environ.get("ORBITSIFT_STRICT") == "1") or \
|
|
126
|
+
any(re.match(p, line) for p in STRICT_ALLOW + list(settings.get("allow") or []))
|
|
127
|
+
log = settings.get("log") or ""
|
|
128
|
+
if log != "off":
|
|
129
|
+
if not log:
|
|
130
|
+
from . import config
|
|
131
|
+
log = config.cache_dir() / "requests.log"
|
|
132
|
+
with _lock, open(log, "a") as f:
|
|
133
|
+
f.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S')} {'' if ok else 'BLOCKED '}{line[:2000]}\n")
|
|
134
|
+
if not ok:
|
|
135
|
+
raise OutboundBlocked("strict mode: request not on the allowlist (net.STRICT_ALLOW, config [net] allow): " + line[:200])
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def exact():
|
|
139
|
+
"""True if requests may carry exact positions (ORBITSIFT_OUTBOUND=exact)."""
|
|
140
|
+
return OUTBOUND == "exact"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def snap(ra, dec):
|
|
144
|
+
"""Centre of the 1 deg tile cell holding (ra, dec), and the distance [deg] that covers the whole cell from it."""
|
|
145
|
+
from .tiles import tile
|
|
146
|
+
t = tile(ra, dec)
|
|
147
|
+
return t["ra0"] + 0.5, t["dec0"] + 0.5, 0.71
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
_lock = threading.Lock()
|
|
151
|
+
_last = {}
|
|
152
|
+
_slots = {} # host -> [semaphore, current limit, permits still to withdraw]
|
|
153
|
+
COUNTS = {} # host -> requests sent in this process
|
|
154
|
+
EVENTS = [] # halvings: dict(host, why, limit)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _slot(host):
|
|
158
|
+
with _lock:
|
|
159
|
+
if host not in _slots:
|
|
160
|
+
n = min(int(settings["max_concurrent"]), host_concurrent.get(host, 1 << 30))
|
|
161
|
+
_slots[host] = [threading.BoundedSemaphore(n), n, 0]
|
|
162
|
+
return _slots[host]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _release(host):
|
|
166
|
+
s = _slot(host)
|
|
167
|
+
with _lock:
|
|
168
|
+
keep = s[2] > 0
|
|
169
|
+
s[2] -= keep
|
|
170
|
+
if not keep:
|
|
171
|
+
s[0].release()
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def halve(host, why):
|
|
175
|
+
"""Halve the number of concurrent requests to ``host`` for the rest of the process (at least 1): done at every HTTP
|
|
176
|
+
429, 5xx, timeout, truncated answer or reset connection from it (an archive under load cuts transfers short rather
|
|
177
|
+
than refusing them: survey, 23 Nov 2026); logged in EVENTS."""
|
|
178
|
+
s = _slot(host)
|
|
179
|
+
with _lock:
|
|
180
|
+
new = max(1, s[1] // 2)
|
|
181
|
+
s[2] += s[1] - new
|
|
182
|
+
s[1] = new
|
|
183
|
+
EVENTS.append(dict(host=host, why=why, limit=new, t=time.strftime("%Y-%m-%dT%H:%M:%S")))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _wait_turn(host):
|
|
187
|
+
with _lock:
|
|
188
|
+
now = time.monotonic()
|
|
189
|
+
t = max(now, _last.get(host, 0.0) + float(settings["min_interval_s"]))
|
|
190
|
+
_last[host] = t
|
|
191
|
+
time.sleep(max(0.0, t - now))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _read(r, until):
|
|
195
|
+
"""The whole body, or TimeoutError once the wall clock passes ``until`` (a socket timeout alone never trips on a
|
|
196
|
+
server that keeps sending a few bytes), or IncompleteRead if fewer bytes came than Content-Length announced."""
|
|
197
|
+
out = []
|
|
198
|
+
while chunk := r.read(1 << 16):
|
|
199
|
+
out.append(chunk)
|
|
200
|
+
if time.monotonic() > until:
|
|
201
|
+
raise TimeoutError("answer still incomplete at the time limit")
|
|
202
|
+
b = b"".join(out)
|
|
203
|
+
n = r.headers.get("Content-Length")
|
|
204
|
+
if n is not None and n.isdigit() and len(b) != int(n):
|
|
205
|
+
raise http.client.IncompleteRead(b, int(n) - len(b))
|
|
206
|
+
return b
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def save(path, data):
|
|
210
|
+
"""Write bytes (or text) to ``path`` through a temporary file of this process: a reader, or another process
|
|
211
|
+
writing the same file, never sees a partial file (threads too: in field mode they often fetch the same tile)."""
|
|
212
|
+
tmp = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
|
|
213
|
+
tmp.write_bytes(data.encode() if isinstance(data, str) else data)
|
|
214
|
+
os.replace(tmp, path)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def fetch(url, data=None, headers=None, timeout=None, retries=None, deadline=None, method=None):
|
|
218
|
+
"""Return the body of ``url`` (POST if ``data`` is given, unless ``method`` says otherwise: the MPC's get-obs wants a
|
|
219
|
+
GET with a JSON body). Retries on network errors, HTTP 429 and 5xx with backoff 10, 20, 40 ... s (max 300 s); other HTTP errors raise at once. Each attempt has
|
|
220
|
+
``timeout`` seconds of wall clock (default ``timeout_s``), the whole call ``deadline`` seconds (default
|
|
221
|
+
``deadline_s``) including the waits: no retry starts after it. When the service never answers, it raises
|
|
222
|
+
ServiceError naming the host, the attempts, the time and the last error."""
|
|
223
|
+
host = urllib.parse.urlsplit(url).netloc
|
|
224
|
+
_check(url, data)
|
|
225
|
+
retries = settings["retries"] if retries is None else retries
|
|
226
|
+
timeout = timeout or settings["timeout_s"]
|
|
227
|
+
t0 = time.monotonic()
|
|
228
|
+
end = t0 + float(deadline or settings["deadline_s"])
|
|
229
|
+
err, k = None, 0
|
|
230
|
+
for k in range(int(retries) + 1):
|
|
231
|
+
_slot(host)[0].acquire()
|
|
232
|
+
try:
|
|
233
|
+
_wait_turn(host)
|
|
234
|
+
left = end - time.monotonic()
|
|
235
|
+
if left <= 0:
|
|
236
|
+
break
|
|
237
|
+
with _lock:
|
|
238
|
+
COUNTS[host] = COUNTS.get(host, 0) + 1
|
|
239
|
+
try:
|
|
240
|
+
req = urllib.request.Request(url, data, {"User-Agent": user_agent(), **(headers or {})}, method=method)
|
|
241
|
+
t = min(float(timeout), left)
|
|
242
|
+
with urllib.request.urlopen(req, timeout=t) as r:
|
|
243
|
+
return _read(r, time.monotonic() + t)
|
|
244
|
+
except urllib.error.HTTPError as e:
|
|
245
|
+
if e.code != 429 and e.code < 500:
|
|
246
|
+
raise
|
|
247
|
+
err = e
|
|
248
|
+
halve(host, f"HTTP {e.code}")
|
|
249
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError, http.client.HTTPException) as e:
|
|
250
|
+
if isinstance(getattr(e, "reason", e), ssl.SSLCertVerificationError):
|
|
251
|
+
raise ServiceError(f"{host}: {e.reason}: this Python has no usable certificate bundle (README, "
|
|
252
|
+
"Troubleshooting: certificate errors)") from None
|
|
253
|
+
err = e
|
|
254
|
+
if isinstance(e, TimeoutError) or "timed out" in repr(e):
|
|
255
|
+
halve(host, "timeout")
|
|
256
|
+
elif isinstance(e, (http.client.IncompleteRead, ConnectionResetError)):
|
|
257
|
+
halve(host, "truncated" if isinstance(e, http.client.IncompleteRead) else "reset")
|
|
258
|
+
finally:
|
|
259
|
+
_release(host)
|
|
260
|
+
wait = min(10 * 2 ** k, 300)
|
|
261
|
+
if k == retries or time.monotonic() + wait >= end:
|
|
262
|
+
break
|
|
263
|
+
time.sleep(wait)
|
|
264
|
+
raise ServiceError(f"{host}: no answer after {k + 1} attempt(s) in {time.monotonic() - t0:.0f} s (last error: {err!r}); "
|
|
265
|
+
"the service may be down: re-run later, cached data are kept")
|