skyhound 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.
- skyhound/__init__.py +9 -0
- skyhound/archives/__init__.py +21 -0
- skyhound/archives/_common.py +246 -0
- skyhound/archives/base.py +361 -0
- skyhound/archives/clients/__init__.py +1 -0
- skyhound/archives/clients/remote_fits.py +144 -0
- skyhound/archives/clients/stdpsf.py +190 -0
- skyhound/archives/euclid.py +707 -0
- skyhound/archives/gaia.py +58 -0
- skyhound/archives/hips2fits.py +242 -0
- skyhound/archives/legacysurvey.py +141 -0
- skyhound/archives/mast.py +600 -0
- skyhound/archives/panstarrs.py +142 -0
- skyhound/archives/registry.py +120 -0
- skyhound/archives/simbad.py +54 -0
- skyhound/archives/tap.py +201 -0
- skyhound/archives/vizier.py +198 -0
- skyhound/cli.py +382 -0
- skyhound/core/__init__.py +65 -0
- skyhound/core/auth.py +285 -0
- skyhound/core/batch.py +256 -0
- skyhound/core/cache.py +140 -0
- skyhound/core/citations.py +62 -0
- skyhound/core/coords.py +148 -0
- skyhound/core/coverage.py +383 -0
- skyhound/core/errors.py +61 -0
- skyhound/core/jobs.py +291 -0
- skyhound/core/limits.py +15 -0
- skyhound/core/output.py +51 -0
- skyhound/core/preview.py +85 -0
- skyhound/core/provenance.py +87 -0
- skyhound/core/psf.py +226 -0
- skyhound/core/psf_batch.py +239 -0
- skyhound/core/psf_empirical.py +346 -0
- skyhound/core/quicklook.py +188 -0
- skyhound/core/resolve.py +182 -0
- skyhound/core/results.py +266 -0
- skyhound/core/sources.py +473 -0
- skyhound/core/target.py +282 -0
- skyhound/data/__init__.py +1 -0
- skyhound/data/zenodo.py +178 -0
- skyhound/mcp/__init__.py +1 -0
- skyhound/mcp/server.py +502 -0
- skyhound/py.typed +0 -0
- skyhound-0.1.0.dist-info/METADATA +270 -0
- skyhound-0.1.0.dist-info/RECORD +49 -0
- skyhound-0.1.0.dist-info/WHEEL +4 -0
- skyhound-0.1.0.dist-info/entry_points.txt +3 -0
- skyhound-0.1.0.dist-info/licenses/LICENSE +28 -0
skyhound/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""skyhound: retrieve astronomical data from telescope archives.
|
|
2
|
+
|
|
3
|
+
All real logic lives in this library. The MCP server (``skyhound.mcp``) and the
|
|
4
|
+
CLI (``skyhound.cli``) are thin wrappers around it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
|
|
9
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Archive backends: one module per archive, all implementing ``archives.base.Archive``."""
|
|
2
|
+
|
|
3
|
+
from skyhound.archives.base import Archive, ArchiveStatus, Capability
|
|
4
|
+
from skyhound.archives.registry import (
|
|
5
|
+
archive_names,
|
|
6
|
+
check_coverage_all,
|
|
7
|
+
get_archive,
|
|
8
|
+
list_archives,
|
|
9
|
+
register,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"Archive",
|
|
14
|
+
"ArchiveStatus",
|
|
15
|
+
"Capability",
|
|
16
|
+
"archive_names",
|
|
17
|
+
"check_coverage_all",
|
|
18
|
+
"get_archive",
|
|
19
|
+
"list_archives",
|
|
20
|
+
"register",
|
|
21
|
+
]
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Helpers shared by archive backends: ADQL limits, saving results, health checks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
8
|
+
from dataclasses import replace
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
import requests
|
|
13
|
+
from astropy import units as u
|
|
14
|
+
from astropy.coordinates import SkyCoord
|
|
15
|
+
from astropy.table import Table
|
|
16
|
+
|
|
17
|
+
from skyhound.core.errors import (
|
|
18
|
+
ArchiveUnavailableError,
|
|
19
|
+
InvalidQueryError,
|
|
20
|
+
short_message,
|
|
21
|
+
)
|
|
22
|
+
from skyhound.core.output import output_path
|
|
23
|
+
from skyhound.core.provenance import Provenance, write_provenance
|
|
24
|
+
from skyhound.core.results import ImageResult, TableResult
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from skyhound.archives.base import Archive, ArchiveStatus
|
|
28
|
+
|
|
29
|
+
_SELECT_HEAD = re.compile(r"^\s*SELECT\s+((?:DISTINCT|ALL)\s+)?(?:TOP\s+(\d+)\s+)?", re.I)
|
|
30
|
+
_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
31
|
+
|
|
32
|
+
MAX_CONE_RADIUS_ARCSEC = 3600.0
|
|
33
|
+
"""Largest cone search radius accepted by default (1 degree)."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def limit_adql(adql: str, max_rows: int) -> str:
|
|
37
|
+
"""Make ``adql`` return at most ``max_rows + 1`` rows (the extra row detects truncation).
|
|
38
|
+
|
|
39
|
+
Adds ``TOP max_rows+1`` after ``SELECT [DISTINCT]``, or lowers an existing larger TOP.
|
|
40
|
+
A smaller TOP set by the caller is kept. Queries not starting with SELECT are left
|
|
41
|
+
alone; callers also pass ``maxrec`` to the service.
|
|
42
|
+
"""
|
|
43
|
+
if max_rows < 1:
|
|
44
|
+
raise ValueError(f"max_rows must be >= 1, got {max_rows}")
|
|
45
|
+
adql = adql.strip().rstrip(";").strip()
|
|
46
|
+
match = _SELECT_HEAD.match(adql)
|
|
47
|
+
if not match:
|
|
48
|
+
return adql
|
|
49
|
+
top = match.group(2)
|
|
50
|
+
if top is not None and int(top) <= max_rows:
|
|
51
|
+
return adql
|
|
52
|
+
head = f"SELECT {match.group(1) or ''}TOP {max_rows + 1} "
|
|
53
|
+
return head + adql[match.end() :]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def validate_columns(columns: Iterable[str]) -> list[str]:
|
|
57
|
+
"""Column names must be plain identifiers (no expressions, no injection)."""
|
|
58
|
+
cols = list(columns)
|
|
59
|
+
bad = [c for c in cols if not _IDENTIFIER.match(c)]
|
|
60
|
+
if bad:
|
|
61
|
+
raise InvalidQueryError(
|
|
62
|
+
f"Invalid column name(s) {bad}: use plain column names. "
|
|
63
|
+
"For expressions, write an ADQL query instead."
|
|
64
|
+
)
|
|
65
|
+
return cols
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def validate_radius(radius_arcsec: float, maximum: float = MAX_CONE_RADIUS_ARCSEC) -> float:
|
|
69
|
+
if not 0 < radius_arcsec <= maximum:
|
|
70
|
+
raise InvalidQueryError(
|
|
71
|
+
f"radius_arcsec must be > 0 and <= {maximum:g}, got {radius_arcsec:g}. "
|
|
72
|
+
"For larger areas, write an ADQL query or split the search."
|
|
73
|
+
)
|
|
74
|
+
return float(radius_arcsec)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def cone_adql(
|
|
78
|
+
table: str,
|
|
79
|
+
ra_col: str,
|
|
80
|
+
dec_col: str,
|
|
81
|
+
columns: Sequence[str],
|
|
82
|
+
coord: SkyCoord,
|
|
83
|
+
radius_arcsec: float,
|
|
84
|
+
) -> str:
|
|
85
|
+
"""ADQL cone search, nearest first, with a ``dist_arcsec`` column."""
|
|
86
|
+
icrs = coord.icrs
|
|
87
|
+
ra, dec, r = float(icrs.ra.deg), float(icrs.dec.deg), radius_arcsec / 3600.0
|
|
88
|
+
point = f"POINT('ICRS', {ra_col}, {dec_col})"
|
|
89
|
+
centre = f"POINT('ICRS', {ra!r}, {dec!r})"
|
|
90
|
+
cols = ", ".join(columns) if columns else "*"
|
|
91
|
+
return (
|
|
92
|
+
f"SELECT {cols}, DISTANCE({point}, {centre}) * 3600 AS dist_arcsec "
|
|
93
|
+
f"FROM {table} "
|
|
94
|
+
f"WHERE 1 = CONTAINS({point}, CIRCLE('ICRS', {ra!r}, {dec!r}, {r!r})) "
|
|
95
|
+
f"ORDER BY dist_arcsec"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def save_table(
|
|
100
|
+
archive: Archive,
|
|
101
|
+
table: Table,
|
|
102
|
+
*,
|
|
103
|
+
kind: str,
|
|
104
|
+
params: Mapping[str, Any],
|
|
105
|
+
query: str | dict[str, Any],
|
|
106
|
+
max_rows: int,
|
|
107
|
+
coord: SkyCoord | None = None,
|
|
108
|
+
out_dir: str | Path | None = None,
|
|
109
|
+
service_url: str | None = None,
|
|
110
|
+
release: str | None = None,
|
|
111
|
+
notes: Sequence[str] = (),
|
|
112
|
+
) -> TableResult:
|
|
113
|
+
"""Write the table (capped at ``max_rows``) and its provenance sidecar."""
|
|
114
|
+
path = output_path(archive.name, kind, params, ".ecsv", coord=coord, out_dir=out_dir)
|
|
115
|
+
result = TableResult.from_table(table, path, max_rows=max_rows, archive=archive.name)
|
|
116
|
+
prov = Provenance(
|
|
117
|
+
archive=archive.name,
|
|
118
|
+
query=query,
|
|
119
|
+
service_url=service_url,
|
|
120
|
+
release=release,
|
|
121
|
+
citation=archive.citation(),
|
|
122
|
+
extra={"kind": kind, "params": dict(params), "truncated": result.truncated},
|
|
123
|
+
)
|
|
124
|
+
if notes:
|
|
125
|
+
prov.extra["notes"] = list(notes)
|
|
126
|
+
return replace(result, provenance_path=write_provenance(path, prov), notes=tuple(notes))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def finish_image(
|
|
130
|
+
archive: Archive,
|
|
131
|
+
path: Path,
|
|
132
|
+
*,
|
|
133
|
+
band: str | None,
|
|
134
|
+
query: str | dict[str, Any],
|
|
135
|
+
service_url: str | None = None,
|
|
136
|
+
release: str | None = None,
|
|
137
|
+
notes: Sequence[str] = (),
|
|
138
|
+
extra: Mapping[str, Any] | None = None,
|
|
139
|
+
expected: tuple[SkyCoord, float] | None = None,
|
|
140
|
+
) -> ImageResult:
|
|
141
|
+
"""Summarise a downloaded FITS image and write its provenance sidecar.
|
|
142
|
+
|
|
143
|
+
``expected`` = (position, size in arcsec) of the request: the image must actually be
|
|
144
|
+
of that position (see ``check_centre``); otherwise the file is deleted and an error
|
|
145
|
+
raised, so a wrong cutout is never kept.
|
|
146
|
+
"""
|
|
147
|
+
result = ImageResult.from_fits(path, band=band, archive=archive.name)
|
|
148
|
+
if expected is not None:
|
|
149
|
+
try:
|
|
150
|
+
check_centre(result, *expected)
|
|
151
|
+
except ArchiveUnavailableError:
|
|
152
|
+
path.unlink(missing_ok=True)
|
|
153
|
+
raise
|
|
154
|
+
prov = Provenance(
|
|
155
|
+
archive=archive.name,
|
|
156
|
+
query=query,
|
|
157
|
+
service_url=service_url,
|
|
158
|
+
release=release,
|
|
159
|
+
citation=archive.citation(),
|
|
160
|
+
extra=dict(extra or {}),
|
|
161
|
+
)
|
|
162
|
+
if notes:
|
|
163
|
+
prov.extra["notes"] = list(notes)
|
|
164
|
+
return replace(result, provenance_path=write_provenance(path, prov), notes=tuple(notes))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def check_centre(result: ImageResult, coord: SkyCoord, size_arcsec: float) -> None:
|
|
168
|
+
"""Raise if the image is not of the requested position.
|
|
169
|
+
|
|
170
|
+
A full-size cutout must be centred within max(1", 1.5 px); a truncated one (at an image
|
|
171
|
+
edge) must still contain the position. Catches mixed-up responses, which happened with
|
|
172
|
+
a client shared between threads.
|
|
173
|
+
"""
|
|
174
|
+
if result.wcs_center is None or not result.pixel_scale_arcsec:
|
|
175
|
+
return
|
|
176
|
+
scale = result.pixel_scale_arcsec
|
|
177
|
+
full = all(n * scale >= 0.9 * size_arcsec for n in result.shape[-2:])
|
|
178
|
+
tolerance = max(1.0, 1.5 * scale) if full else 0.75 * size_arcsec
|
|
179
|
+
centre = SkyCoord(result.wcs_center[0] * u.deg, result.wcs_center[1] * u.deg)
|
|
180
|
+
offset = float(centre.separation(coord.icrs).arcsec)
|
|
181
|
+
if offset > tolerance:
|
|
182
|
+
raise ArchiveUnavailableError(
|
|
183
|
+
f"The returned cutout is centred {offset:.1f} arcsec from the requested position "
|
|
184
|
+
f"(tolerance {tolerance:.1f}); it was discarded as a mixed-up or wrong response. "
|
|
185
|
+
"Retry the request."
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
_AVAILABLE = re.compile(r"<(?:\w+:)?available>\s*(true|false)\s*</", re.I)
|
|
190
|
+
_NOTE = re.compile(r"<(?:\w+:)?note>(.*?)</(?:\w+:)?note>", re.I | re.S)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _visible_text(page: str, limit: int = 200) -> str:
|
|
194
|
+
page = re.sub(r"<(script|style|svg)[^>]*>.*?</\1>", " ", page, flags=re.S | re.I)
|
|
195
|
+
text = html.unescape(re.sub(r"<[^>]+>", " ", page))
|
|
196
|
+
text = re.sub(r"\s+", " ", text).strip()
|
|
197
|
+
return text if len(text) <= limit else text[: limit - 3] + "..."
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def vosi_available(service_url: str, *, timeout: float = 15.0) -> tuple[bool, str]:
|
|
201
|
+
"""Check ``<service_url>/availability`` (IVOA VOSI). Returns (available, message).
|
|
202
|
+
|
|
203
|
+
Does not trust the HTTP status alone: some archives answer maintenance with an
|
|
204
|
+
HTML page and status 200.
|
|
205
|
+
"""
|
|
206
|
+
url = service_url.rstrip("/") + "/availability"
|
|
207
|
+
try:
|
|
208
|
+
response = requests.get(url, timeout=timeout)
|
|
209
|
+
except requests.RequestException as exc:
|
|
210
|
+
return False, f"{url} unreachable ({type(exc).__name__}: {short_message(exc)})"
|
|
211
|
+
body = response.text
|
|
212
|
+
match = _AVAILABLE.search(body)
|
|
213
|
+
if match:
|
|
214
|
+
available = match.group(1).lower() == "true"
|
|
215
|
+
note = _NOTE.search(body)
|
|
216
|
+
message = html.unescape(note.group(1)).strip() if note else ""
|
|
217
|
+
if message.lower() in {"null", "none"}: # some services put a literal "null" here
|
|
218
|
+
message = ""
|
|
219
|
+
return available, message or ("available" if available else "service reports unavailable")
|
|
220
|
+
if not response.ok:
|
|
221
|
+
return False, f"{url} returned HTTP {response.status_code}"
|
|
222
|
+
return False, (
|
|
223
|
+
f"{url} returned a web page instead of a VOSI availability document "
|
|
224
|
+
f"(likely maintenance): '{_visible_text(body)}'"
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def status_from_endpoints(
|
|
229
|
+
archive: Archive, endpoints: Sequence[tuple[str, str]], *, timeout: float = 15.0
|
|
230
|
+
) -> ArchiveStatus:
|
|
231
|
+
"""Combine VOSI checks of (label, url) endpoints into one ArchiveStatus."""
|
|
232
|
+
from skyhound.archives.base import ArchiveStatus
|
|
233
|
+
|
|
234
|
+
details: dict[str, Any] = {}
|
|
235
|
+
for label, url in endpoints:
|
|
236
|
+
ok, message = vosi_available(url, timeout=timeout)
|
|
237
|
+
details[label] = {"url": url, "available": ok, "message": message}
|
|
238
|
+
up = [label for label, d in details.items() if d["available"]]
|
|
239
|
+
if not up:
|
|
240
|
+
message = "No endpoint is available; try again later."
|
|
241
|
+
elif len(up) == len(details):
|
|
242
|
+
message = "available"
|
|
243
|
+
else:
|
|
244
|
+
down = [label for label in details if label not in up]
|
|
245
|
+
message = f"Available via {', '.join(up)}; {', '.join(down)} down."
|
|
246
|
+
return ArchiveStatus(archive.name, bool(up), message, details=details)
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"""The ``Archive`` interface every archive backend implements.
|
|
2
|
+
|
|
3
|
+
A backend declares which capabilities it supports and overrides only those methods;
|
|
4
|
+
the others raise ``CapabilityNotSupportedError`` with a pointer to what to do instead.
|
|
5
|
+
Coordinates arrive already parsed (ICRS ``SkyCoord``); results are written to disk and
|
|
6
|
+
returned as ``TableResult`` / ``ImageResult``, each with a provenance sidecar.
|
|
7
|
+
|
|
8
|
+
Every archive also declares its sky ``coverage()``, so a position outside the footprint
|
|
9
|
+
can be rejected with a clear message before any query runs.
|
|
10
|
+
|
|
11
|
+
Archives that need a login set ``auth_method`` and implement ``_login()``: a small
|
|
12
|
+
wrapper around that archive's own mechanism (astroquery's ``login``, a token header,
|
|
13
|
+
...). Callers always use ``login()`` / ``ensure_login()``, which find credentials the
|
|
14
|
+
same way for every archive (see ``core.auth``).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from abc import ABC, abstractmethod
|
|
20
|
+
from dataclasses import dataclass, field, replace
|
|
21
|
+
from datetime import UTC, datetime
|
|
22
|
+
from enum import StrEnum
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, ClassVar
|
|
25
|
+
|
|
26
|
+
from astropy.coordinates import SkyCoord
|
|
27
|
+
|
|
28
|
+
from skyhound.core.auth import AuthMethod, Credentials, CredentialStore, env_var_names
|
|
29
|
+
from skyhound.core.coverage import Coverage, CoverageCheck, CoverageStatus
|
|
30
|
+
from skyhound.core.errors import (
|
|
31
|
+
AgenticAstronomerError,
|
|
32
|
+
AuthenticationFailedError,
|
|
33
|
+
AuthenticationRequiredError,
|
|
34
|
+
CapabilityNotSupportedError,
|
|
35
|
+
InvalidQueryError,
|
|
36
|
+
OutsideCoverageError,
|
|
37
|
+
)
|
|
38
|
+
from skyhound.core.limits import DEFAULT_MAX_DOWNLOAD_MB, DEFAULT_MAX_ROWS
|
|
39
|
+
from skyhound.core.psf import PSFResult
|
|
40
|
+
from skyhound.core.results import DownloadResult, ImageResult, TableResult
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Capability(StrEnum):
|
|
44
|
+
"""What an archive can do."""
|
|
45
|
+
|
|
46
|
+
CONE_SEARCH = "cone_search"
|
|
47
|
+
CUTOUT = "cutout"
|
|
48
|
+
ADQL = "adql"
|
|
49
|
+
SPECTRA = "spectra"
|
|
50
|
+
PRODUCTS = "products"
|
|
51
|
+
PSF = "psf"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class ArchiveStatus:
|
|
56
|
+
"""Result of a health check."""
|
|
57
|
+
|
|
58
|
+
archive: str
|
|
59
|
+
available: bool
|
|
60
|
+
message: str = ""
|
|
61
|
+
checked_utc: str = field(
|
|
62
|
+
default_factory=lambda: (
|
|
63
|
+
datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
details: dict[str, Any] = field(default_factory=dict)
|
|
67
|
+
|
|
68
|
+
def summary(self) -> dict[str, Any]:
|
|
69
|
+
out: dict[str, Any] = {
|
|
70
|
+
"archive": self.archive,
|
|
71
|
+
"available": self.available,
|
|
72
|
+
"message": self.message,
|
|
73
|
+
"checked_utc": self.checked_utc,
|
|
74
|
+
}
|
|
75
|
+
if self.details:
|
|
76
|
+
out["details"] = self.details
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class Archive(ABC):
|
|
81
|
+
"""Base class for archive backends.
|
|
82
|
+
|
|
83
|
+
Subclasses set the class attributes and implement ``status()``, ``citation()`` and
|
|
84
|
+
``coverage()``, plus the methods matching their ``capabilities``.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
name: ClassVar[str]
|
|
88
|
+
"""Registry key: lowercase, e.g. 'gaia' or 'euclid-esa'."""
|
|
89
|
+
title: ClassVar[str] = ""
|
|
90
|
+
"""Human-readable name, e.g. 'ESA Gaia Archive'."""
|
|
91
|
+
description: ClassVar[str] = ""
|
|
92
|
+
capabilities: ClassVar[frozenset[Capability]] = frozenset()
|
|
93
|
+
bands: ClassVar[tuple[str, ...]] = ()
|
|
94
|
+
"""Bands available for cutouts, if any."""
|
|
95
|
+
service_url: ClassVar[str | None] = None
|
|
96
|
+
|
|
97
|
+
auth_method: ClassVar[AuthMethod] = AuthMethod.NONE
|
|
98
|
+
auth_required: ClassVar[bool] = False
|
|
99
|
+
"""True if nothing works without a login; False if login only unlocks extra data."""
|
|
100
|
+
auth_host: ClassVar[str | None] = None
|
|
101
|
+
"""Login host, used to find an entry in ~/.netrc (e.g. 'eas.esac.esa.int')."""
|
|
102
|
+
auth_signup_url: ClassVar[str | None] = None
|
|
103
|
+
"""Where a person registers for an account or creates a token."""
|
|
104
|
+
|
|
105
|
+
_logged_in_as: str | None = None
|
|
106
|
+
|
|
107
|
+
@abstractmethod
|
|
108
|
+
def status(self) -> ArchiveStatus:
|
|
109
|
+
"""Check whether the service is reachable. Must not raise for a down service."""
|
|
110
|
+
|
|
111
|
+
@abstractmethod
|
|
112
|
+
def citation(self) -> str:
|
|
113
|
+
"""Citation / acknowledgement text required when using this archive's data."""
|
|
114
|
+
|
|
115
|
+
@abstractmethod
|
|
116
|
+
def coverage(self) -> Coverage:
|
|
117
|
+
"""The sky area this archive's data spans.
|
|
118
|
+
|
|
119
|
+
Return the same object on every call (e.g. build it once in ``__init__``), so a
|
|
120
|
+
``MOCCoverage`` is downloaded and parsed only once per process.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def check_coverage(self, coord: SkyCoord, radius_arcsec: float = 0.0) -> CoverageCheck:
|
|
124
|
+
"""Is ``coord`` (plus a cone of ``radius_arcsec``) inside this archive's footprint?"""
|
|
125
|
+
result = self.coverage().check(coord, radius_arcsec)
|
|
126
|
+
return replace(result, archive=self.name, message=f"{self.name}: {result.message}")
|
|
127
|
+
|
|
128
|
+
def _require_coverage(self, coord: SkyCoord, radius_arcsec: float = 0.0) -> tuple[str, ...]:
|
|
129
|
+
"""Raise ``OutsideCoverageError`` if outside; return notes worth passing on.
|
|
130
|
+
|
|
131
|
+
Data methods call this before querying, so an empty answer is explained instead
|
|
132
|
+
of silently returned. Partial or unknown coverage only produces a note.
|
|
133
|
+
"""
|
|
134
|
+
check = self.check_coverage(coord, radius_arcsec)
|
|
135
|
+
if check.status is CoverageStatus.OUTSIDE:
|
|
136
|
+
raise OutsideCoverageError(check.message)
|
|
137
|
+
if check.status is CoverageStatus.PARTIAL:
|
|
138
|
+
return (check.message,)
|
|
139
|
+
if check.status is CoverageStatus.UNKNOWN and self.coverage().kind != "pointed":
|
|
140
|
+
return (check.message,)
|
|
141
|
+
return ()
|
|
142
|
+
|
|
143
|
+
# Authentication
|
|
144
|
+
|
|
145
|
+
def _login(self, credentials: Credentials) -> None:
|
|
146
|
+
"""Log in with ``credentials``; raise on failure. Override in archives that need it.
|
|
147
|
+
|
|
148
|
+
Keep it small: call the archive's own login (e.g. ``Euclid.login(user=...,
|
|
149
|
+
password=...)``). Any exception is turned into ``AuthenticationFailedError``.
|
|
150
|
+
"""
|
|
151
|
+
raise NotImplementedError(f"{type(self).__name__} sets auth_method but has no _login")
|
|
152
|
+
|
|
153
|
+
def _logout(self) -> None: # noqa: B027 (optional hook, empty by default)
|
|
154
|
+
"""Override if the archive keeps a server-side session."""
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def logged_in(self) -> bool:
|
|
158
|
+
return self._logged_in_as is not None
|
|
159
|
+
|
|
160
|
+
def login(
|
|
161
|
+
self, credentials: Credentials | None = None, *, store: CredentialStore | None = None
|
|
162
|
+
) -> None:
|
|
163
|
+
"""Log in with the given credentials, or the stored ones (see ``core.auth``)."""
|
|
164
|
+
if self.auth_method is AuthMethod.NONE:
|
|
165
|
+
raise AuthenticationFailedError(f"Archive '{self.name}' does not use a login.")
|
|
166
|
+
creds = credentials or (store or CredentialStore()).get(self.name, host=self.auth_host)
|
|
167
|
+
if creds is None or not creds.satisfies(self.auth_method):
|
|
168
|
+
raise AuthenticationRequiredError(self._login_hint(found=creds is not None))
|
|
169
|
+
try:
|
|
170
|
+
self._login(creds)
|
|
171
|
+
except AgenticAstronomerError:
|
|
172
|
+
raise
|
|
173
|
+
except Exception as exc:
|
|
174
|
+
who = f" as '{creds.username}'" if creds.username else ""
|
|
175
|
+
detail = (str(exc).strip().splitlines() or [""])[0][:200]
|
|
176
|
+
raise AuthenticationFailedError(
|
|
177
|
+
f"Login to '{self.name}'{who} failed ({type(exc).__name__}: {detail}). "
|
|
178
|
+
f"If the credentials are wrong, a person should re-run "
|
|
179
|
+
f"`skyhound login {self.name}` in a terminal "
|
|
180
|
+
f"(credentials came from: {creds.source})."
|
|
181
|
+
) from exc
|
|
182
|
+
self._logged_in_as = creds.username or "token"
|
|
183
|
+
|
|
184
|
+
def logout(self) -> None:
|
|
185
|
+
if self.logged_in:
|
|
186
|
+
try:
|
|
187
|
+
self._logout()
|
|
188
|
+
finally:
|
|
189
|
+
self._logged_in_as = None
|
|
190
|
+
|
|
191
|
+
def ensure_login(self, *, store: CredentialStore | None = None) -> None:
|
|
192
|
+
"""Log in if needed and possible. Data methods call this first.
|
|
193
|
+
|
|
194
|
+
Raises ``AuthenticationRequiredError`` only when the archive cannot be used
|
|
195
|
+
anonymously and no credentials are stored; otherwise continues anonymously.
|
|
196
|
+
"""
|
|
197
|
+
if self.auth_method is AuthMethod.NONE or self.logged_in:
|
|
198
|
+
return
|
|
199
|
+
creds = (store or CredentialStore()).get(self.name, host=self.auth_host)
|
|
200
|
+
if creds is not None and creds.satisfies(self.auth_method):
|
|
201
|
+
self.login(creds)
|
|
202
|
+
elif self.auth_required:
|
|
203
|
+
raise AuthenticationRequiredError(self._login_hint(found=creds is not None))
|
|
204
|
+
|
|
205
|
+
def auth_status(self, *, store: CredentialStore | None = None) -> dict[str, Any]:
|
|
206
|
+
"""Login state, safe to show to a model (never includes secrets)."""
|
|
207
|
+
out: dict[str, Any] = {"archive": self.name, "auth_method": self.auth_method.value}
|
|
208
|
+
if self.auth_method is AuthMethod.NONE:
|
|
209
|
+
out["message"] = "No login needed."
|
|
210
|
+
return out
|
|
211
|
+
creds = (store or CredentialStore()).get(self.name, host=self.auth_host)
|
|
212
|
+
ready = creds is not None and creds.satisfies(self.auth_method)
|
|
213
|
+
out.update(
|
|
214
|
+
{
|
|
215
|
+
"auth_required": self.auth_required,
|
|
216
|
+
"logged_in": self.logged_in,
|
|
217
|
+
"credentials_found": ready,
|
|
218
|
+
"credentials_source": creds.source if creds else None,
|
|
219
|
+
"username": creds.username if creds else None,
|
|
220
|
+
}
|
|
221
|
+
)
|
|
222
|
+
if not ready:
|
|
223
|
+
out["message"] = self._login_hint(found=creds is not None)
|
|
224
|
+
return out
|
|
225
|
+
|
|
226
|
+
def _login_hint(self, *, found: bool) -> str:
|
|
227
|
+
names = env_var_names(self.name)
|
|
228
|
+
what = "an API token" if self.auth_method is AuthMethod.TOKEN else "a username and password"
|
|
229
|
+
env = (
|
|
230
|
+
names["token"]
|
|
231
|
+
if self.auth_method is AuthMethod.TOKEN
|
|
232
|
+
else f"{names['username']} and {names['password']}"
|
|
233
|
+
)
|
|
234
|
+
problem = "The stored credentials are incomplete" if found else "No credentials found"
|
|
235
|
+
need = (
|
|
236
|
+
f"needs {what}"
|
|
237
|
+
if self.auth_required
|
|
238
|
+
else f"needs {what} for non-public data (public data works without a login)"
|
|
239
|
+
)
|
|
240
|
+
hint = (
|
|
241
|
+
f"{problem} for archive '{self.name}', which {need}. "
|
|
242
|
+
f"A person (not the agent) should run `skyhound login {self.name}` "
|
|
243
|
+
f"in a terminal, or set {env}."
|
|
244
|
+
)
|
|
245
|
+
if self.auth_signup_url:
|
|
246
|
+
hint += f" Get an account or token at {self.auth_signup_url}."
|
|
247
|
+
return hint
|
|
248
|
+
|
|
249
|
+
# Capabilities: override the ones listed in ``capabilities``.
|
|
250
|
+
|
|
251
|
+
def cone_search(
|
|
252
|
+
self,
|
|
253
|
+
coord: SkyCoord,
|
|
254
|
+
radius_arcsec: float,
|
|
255
|
+
*,
|
|
256
|
+
columns: list[str] | None = None,
|
|
257
|
+
max_rows: int = DEFAULT_MAX_ROWS,
|
|
258
|
+
out_dir: Path | None = None,
|
|
259
|
+
table: str | None = None,
|
|
260
|
+
) -> TableResult:
|
|
261
|
+
"""Catalogue sources within ``radius_arcsec`` of ``coord``.
|
|
262
|
+
|
|
263
|
+
``table`` selects another catalogue where the archive has several (e.g. a VizieR
|
|
264
|
+
catalogue ID, or a Euclid Deep-field table); ``None`` uses the archive's default.
|
|
265
|
+
"""
|
|
266
|
+
raise self._unsupported(Capability.CONE_SEARCH)
|
|
267
|
+
|
|
268
|
+
def cutout(
|
|
269
|
+
self,
|
|
270
|
+
coord: SkyCoord,
|
|
271
|
+
size_arcsec: float,
|
|
272
|
+
*,
|
|
273
|
+
band: str | None = None,
|
|
274
|
+
out_dir: Path | None = None,
|
|
275
|
+
) -> ImageResult:
|
|
276
|
+
"""Square image cutout of side ``size_arcsec`` centred on ``coord``."""
|
|
277
|
+
raise self._unsupported(Capability.CUTOUT)
|
|
278
|
+
|
|
279
|
+
def query(
|
|
280
|
+
self,
|
|
281
|
+
adql: str,
|
|
282
|
+
*,
|
|
283
|
+
max_rows: int = DEFAULT_MAX_ROWS,
|
|
284
|
+
out_dir: Path | None = None,
|
|
285
|
+
) -> TableResult:
|
|
286
|
+
"""Run an ADQL query."""
|
|
287
|
+
raise self._unsupported(Capability.ADQL)
|
|
288
|
+
|
|
289
|
+
def search_products(
|
|
290
|
+
self,
|
|
291
|
+
coord: SkyCoord,
|
|
292
|
+
radius_arcsec: float,
|
|
293
|
+
*,
|
|
294
|
+
filters: dict[str, Any] | None = None,
|
|
295
|
+
max_rows: int = DEFAULT_MAX_ROWS,
|
|
296
|
+
out_dir: Path | None = None,
|
|
297
|
+
) -> TableResult:
|
|
298
|
+
"""Observations / data products near ``coord``; the table has a product ID column."""
|
|
299
|
+
raise self._unsupported(Capability.PRODUCTS)
|
|
300
|
+
|
|
301
|
+
def download_product(
|
|
302
|
+
self,
|
|
303
|
+
product_id: str,
|
|
304
|
+
*,
|
|
305
|
+
max_mb: float = DEFAULT_MAX_DOWNLOAD_MB,
|
|
306
|
+
out_dir: Path | None = None,
|
|
307
|
+
) -> DownloadResult:
|
|
308
|
+
"""Download a product found with ``search_products``, refusing if over ``max_mb``."""
|
|
309
|
+
raise self._unsupported(Capability.PRODUCTS)
|
|
310
|
+
|
|
311
|
+
def psf(
|
|
312
|
+
self,
|
|
313
|
+
coord: SkyCoord,
|
|
314
|
+
*,
|
|
315
|
+
band: str | None = None,
|
|
316
|
+
size_px: int | None = None,
|
|
317
|
+
method: str = "auto",
|
|
318
|
+
out_dir: Path | None = None,
|
|
319
|
+
) -> PSFResult:
|
|
320
|
+
"""PSF at ``coord`` in ``band``: an odd ``size_px`` square, sum 1, peak centred.
|
|
321
|
+
|
|
322
|
+
``method``: ``'model'`` (the survey's own PSF model or a published library),
|
|
323
|
+
``'empirical'`` (built here from isolated Gaia stars in a cutout of the field) or
|
|
324
|
+
``'auto'`` (model if the archive has one, else empirical). This default handles
|
|
325
|
+
``'empirical'`` / ``'auto'`` for every archive with cutouts.
|
|
326
|
+
"""
|
|
327
|
+
if method not in ("auto", "model", "empirical"):
|
|
328
|
+
raise InvalidQueryError("method must be 'auto', 'model' or 'empirical'.")
|
|
329
|
+
if method == "model" or Capability.CUTOUT not in self.capabilities:
|
|
330
|
+
raise self._unsupported(Capability.PSF)
|
|
331
|
+
from skyhound.core.psf_empirical import empirical_psf
|
|
332
|
+
|
|
333
|
+
return empirical_psf(self, coord, band=band, size_px=size_px, out_dir=out_dir)
|
|
334
|
+
|
|
335
|
+
# Helpers
|
|
336
|
+
|
|
337
|
+
def supports(self, capability: Capability | str) -> bool:
|
|
338
|
+
return Capability(capability) in self.capabilities
|
|
339
|
+
|
|
340
|
+
def describe(self) -> dict[str, Any]:
|
|
341
|
+
"""Short description for ``list_archives``."""
|
|
342
|
+
out: dict[str, Any] = {
|
|
343
|
+
"name": self.name,
|
|
344
|
+
"title": self.title or self.name,
|
|
345
|
+
"capabilities": sorted(c.value for c in self.capabilities),
|
|
346
|
+
}
|
|
347
|
+
if self.description:
|
|
348
|
+
out["description"] = self.description
|
|
349
|
+
if self.bands:
|
|
350
|
+
out["bands"] = list(self.bands)
|
|
351
|
+
out["coverage"] = self.coverage().describe()
|
|
352
|
+
if self.auth_method is not AuthMethod.NONE:
|
|
353
|
+
out["login"] = {"method": self.auth_method.value, "required": self.auth_required}
|
|
354
|
+
return out
|
|
355
|
+
|
|
356
|
+
def _unsupported(self, capability: Capability) -> CapabilityNotSupportedError:
|
|
357
|
+
offered = ", ".join(sorted(c.value for c in self.capabilities)) or "none"
|
|
358
|
+
return CapabilityNotSupportedError(
|
|
359
|
+
f"Archive '{self.name}' does not support {capability.value}. "
|
|
360
|
+
f"It supports: {offered}. Use list_archives to find one that does."
|
|
361
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Plain HTTP clients for services without an astroquery / pyvo module (see CLAUDE.md)."""
|