skywrapped 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.
skywrapped/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ __version__ = "0.1.0"
2
+
3
+ # Capture software whose light frames are checked by a header fixture (tests/fixtures/headers); the web page lists them.
4
+ TESTED_VENDORS = ("ASIAIR", "Celestron Origin", "N.I.N.A.", "ZWO Seestar", "Dwarf 3", "Ekos/KStars")
@@ -0,0 +1,4 @@
1
+ from .frame import Frame, to_frame
2
+ from .header import header_bytes_needed, read_header
3
+
4
+ __all__ = ["Frame", "to_frame", "read_header", "header_bytes_needed"]
@@ -0,0 +1,311 @@
1
+ """Normalise a FITS/XISF header into a Frame record. Standard library only."""
2
+ import math
3
+ import re
4
+ from dataclasses import dataclass
5
+ from datetime import datetime, timedelta
6
+
7
+ from .header import HeaderError
8
+ from .labels import clean_label
9
+ from .wcs import field_of_view, frame_centre
10
+
11
+ MAX_EXPOSURE_S = 86_400.0 # one sub longer than a day is not a real value
12
+ MAX_SUBS = 100_000 # nor is a stack of more subs than this
13
+
14
+ _MOUNT = re.compile(r"AM\d|EQ-?\d|HEQ\d|CEM\d|GEM\d|CGX|CGEM|EQM|iOptron|GTi|AZ-?GTi|Simulator|Telescope Driver"
15
+ r"|^\s*$|Mount", re.I)
16
+ _ASIAIR = re.compile(r"ASIAIR|ZWO \d+AIR", re.I)
17
+ _STACK_WORDS = {"stack", "stacked", "master", "integration", "drizzle", "drizzled"}
18
+ _NAME_TYPES = (("darkflat", "darkflat"), ("dark", "dark"), ("flat", "flat"), ("bias", "bias"), ("light", "light"))
19
+ _SITE_KEYS = (("SITELAT", "SITELONG"), ("LAT-OBS", "LONG-OBS"), ("OBSGEO-B", "OBSGEO-L"), ("LATITUDE", "LONGITUD"))
20
+ _DT = re.compile(r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?\s*(Z|[+-]\d{2}:?\d{2})?$")
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Frame:
25
+ path: str
26
+ vendor: str
27
+ frame_type: str
28
+ is_stack: bool
29
+ sub_count: int
30
+ exposure_s: float
31
+ integration_s: float
32
+ start_utc: datetime | None
33
+ start_local: datetime | None
34
+ object_hint: str | None
35
+ ra_deg: float | None
36
+ dec_deg: float | None
37
+ fov_deg: tuple[float, float] | None
38
+ focal_mm: float | None
39
+ camera: str | None
40
+ telescope: str | None
41
+ filter: str | None
42
+ gain: float | None
43
+ iso: int | None
44
+ sensor_c: float | None
45
+ site: tuple[float, float] | None
46
+
47
+
48
+ def _num(v, key):
49
+ x = v.get(key)
50
+ if isinstance(x, bool):
51
+ return None
52
+ if isinstance(x, str):
53
+ try:
54
+ x = float(x)
55
+ except ValueError:
56
+ return None
57
+ if not isinstance(x, (int, float)) or not math.isfinite(x):
58
+ return None
59
+ return float(x)
60
+
61
+
62
+ def _text(v, key):
63
+ x = v.get(key)
64
+ if x is None or isinstance(x, bool):
65
+ return None
66
+ s = str(x).strip()
67
+ return s or None
68
+
69
+
70
+ def _parse_dt(date, time):
71
+ """Return a naive datetime (UTC if the string carries an offset) or None."""
72
+ if not isinstance(date, str):
73
+ return None
74
+ m = _DT.match(date.strip())
75
+ if not m:
76
+ return None
77
+ y, mo, d, hh, mm, ss, frac, tz = m.groups()
78
+ try:
79
+ if hh is None:
80
+ t = _text({"t": time}, "t")
81
+ tm = re.match(r"^(\d{1,2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?$", t) if t else None
82
+ if not tm:
83
+ return None # no time of day: never invent a midnight start
84
+ hh, mm, ss, frac = tm.groups()
85
+ ss = ss or "0"
86
+ us = int((frac or "0")[:6].ljust(6, "0"))
87
+ dt = datetime(int(y), int(mo), int(d), int(hh), int(mm), int(ss), us)
88
+ except ValueError:
89
+ return None
90
+ if tz and tz != "Z":
91
+ sign = 1 if tz[0] == "+" else -1
92
+ digits = tz[1:].replace(":", "")
93
+ dt -= sign * timedelta(hours=int(digits[:2]), minutes=int(digits[2:]))
94
+ return dt
95
+
96
+
97
+ def _file_name(path):
98
+ return path.replace("\\", "/").rsplit("/", 1)[-1]
99
+
100
+
101
+ _SEESTAR_SCOPE = re.compile(r"^S\s?(30|50)(?:_.*)?$", re.I)
102
+ _SEESTAR_STACK_NAME = re.compile(r"^Stacked_\d+_", re.I)
103
+
104
+
105
+ def _str(v, key):
106
+ """A header value only when it is a string (a numeric FRAME is a counter, not a type)."""
107
+ return _text(v, key) if isinstance(v.get(key), str) else None
108
+
109
+
110
+ def _vendor(v, name=""):
111
+ creator = _text(v, "CREATOR") or ""
112
+ if creator.startswith("Origin "):
113
+ return "origin"
114
+ if _ASIAIR.search(creator):
115
+ return "asiair"
116
+ if "N.I.N.A." in (_text(v, "SWCREATE") or ""):
117
+ return "nina"
118
+ if "seestar" in creator.lower() or (_text(v, "INSTRUME") or "").lower().startswith("seestar"):
119
+ return "seestar"
120
+ scope = _text(v, "TELESCOP") or ""
121
+ if _SEESTAR_SCOPE.match(scope) or (
122
+ _SEESTAR_STACK_NAME.match(name) and (_num(v, "STACKCNT") is not None or _num(v, "TOTALEXP") is not None)):
123
+ return "seestar"
124
+ if scope.upper().startswith("DWARF"):
125
+ return "dwarf"
126
+ if (_text(v, "ORIGIN") or "").upper() == "DWARFLAB" or (_text(v, "INSTRUME") or "").upper().startswith("DWARF"):
127
+ return "dwarf"
128
+ # INDI drivers (Ekos/KStars) write FRAME and PIXSIZE1 together; no other capture app does
129
+ if _str(v, "FRAME") and _num(v, "PIXSIZE1") is not None:
130
+ return "ekos"
131
+ return "generic"
132
+
133
+
134
+ def _type_from_keyword(raw):
135
+ s = raw.lower().replace("frame", "")
136
+ s = re.sub(r"[\s_-]+", " ", s).strip()
137
+ if "dark flat" in s or "darkflat" in s or "flatdark" in s or "flat dark" in s:
138
+ return "darkflat"
139
+ for word in ("bias", "offset", "zero"):
140
+ if word in s:
141
+ return "bias"
142
+ if "dark" in s:
143
+ return "dark"
144
+ if "flat" in s:
145
+ return "flat"
146
+ for word in ("light", "object", "science"):
147
+ if word in s:
148
+ return "light"
149
+ return None
150
+
151
+
152
+ _CAL_WORDS = {
153
+ "darkflat": "darkflat", "darkflats": "darkflat", "flatdark": "darkflat", "flatdarks": "darkflat",
154
+ "dark": "dark", "darks": "dark", "flat": "flat", "flats": "flat",
155
+ "bias": "bias", "biases": "bias", "offset": "bias", "offsets": "bias",
156
+ "cali": "calibration", "calibration": "calibration", "master": "calibration", "masters": "calibration",
157
+ }
158
+ _CAL_ORDER = ("darkflat", "dark", "flat", "bias", "calibration")
159
+ _NEUTRAL_WORDS = {"raw", "frame", "frames", "dwarf", "library", "lib", "tele", "wide"}
160
+ _NEUTRAL_PATTERN = re.compile(r"^(\d+|\d+(\.\d+)?(s|ms|sec)|-?\d+c|gain\d+|bin\d+|iso\d+)$")
161
+
162
+
163
+ def _folder_type(path):
164
+ """Type from the two nearest folders, only when a folder is clearly calibration: every token of its name is a
165
+ calibration or neutral word (or number/exposure/temperature/gain/bin/iso) and at least one is calibration."""
166
+ dirs = path.replace("\\", "/").split("/")[:-1]
167
+ for d in reversed(dirs[-2:]):
168
+ tokens = [t for t in re.split(r"[^a-z0-9]+", d.lower()) if t]
169
+ cal = {_CAL_WORDS[t] for t in tokens if t in _CAL_WORDS}
170
+ if cal and all(t in _CAL_WORDS or t in _NEUTRAL_WORDS or _NEUTRAL_PATTERN.match(t) for t in tokens):
171
+ return next(c for c in _CAL_ORDER if c in cal)
172
+ return None
173
+
174
+
175
+ _COORD_FRAMES = {"icrs", "fk4", "fk5", "galactic", "ecliptic"} # a FRAME card naming a coordinate system
176
+
177
+
178
+ def _frame_type(v, name, path=""):
179
+ """light/dark/flat/bias/darkflat/calibration from IMAGETYP or FRAME; "other" when a type keyword is present but
180
+ names no known type (SNAPSHOT, FOCUS, TEST...: never counted); otherwise from the file name, then the folders,
181
+ and "unknown" (counted as a light, flagged) only when no type keyword exists at all."""
182
+ present = False
183
+ for key in ("IMAGETYP", "FRAME"):
184
+ # only a string is a type keyword: a numeric FRAME = 12 is a frame counter
185
+ raw = _text(v, key) if isinstance(v.get(key), str) else None
186
+ if not raw or (key == "FRAME" and raw.lower() in _COORD_FRAMES):
187
+ continue
188
+ present = True
189
+ t = _type_from_keyword(raw)
190
+ if t:
191
+ return t
192
+ if present:
193
+ return "other"
194
+ low = name.lower()
195
+ for prefix, t in _NAME_TYPES:
196
+ if low.startswith(prefix + "_"):
197
+ return t
198
+ return _folder_type(path) or "unknown"
199
+
200
+
201
+ def _stack_by_name(lname):
202
+ if lname.startswith("light_"):
203
+ return False
204
+ return any(t in _STACK_WORDS or t.endswith("stack") for t in re.split(r"[^a-z0-9]+", lname))
205
+
206
+
207
+ def _gear(vendor, v):
208
+ """(camera, telescope) names fit to print (labels.clean_label); smart scopes get their product name."""
209
+ cam_raw, scope_raw = _text(v, "INSTRUME"), _text(v, "TELESCOP")
210
+ both = f"{cam_raw or ''} {scope_raw or ''}"
211
+ if vendor == "seestar": # TELESCOP is "S50_<device id>"
212
+ name = "Seestar S30" if re.search(r"S\s*30", both, re.I) else "Seestar S50"
213
+ return name, name
214
+ if vendor == "dwarf": # "DWARFIII" in both cards
215
+ name = "Dwarf 2" if re.search(r"DWARF\s*(II|2)(?![I\d])", both, re.I) else "Dwarf 3"
216
+ return name, name
217
+ telescope = None if scope_raw is None or _MOUNT.search(scope_raw) else clean_label(scope_raw)
218
+ camera = clean_label(cam_raw) or ("Camera" if cam_raw else None)
219
+ return camera, telescope
220
+
221
+
222
+ def _site(v):
223
+ for la, lo in _SITE_KEYS:
224
+ lat, lon = _num(v, la), _num(v, lo)
225
+ if lat is not None and lon is not None:
226
+ if lat == 0.0 and lon == 0.0:
227
+ continue
228
+ return (lat, lon)
229
+ return None
230
+
231
+
232
+ def to_frame(values: dict, comments: dict, path: str) -> Frame:
233
+ """Normalise one header. A stack flagged only by its file name (no NCOMBINE/STACKCNT/LIVETIME/
234
+ TOTALEXP/EXPTOT) keeps sub_count=1 and integration_s=exposure_s: err low, never N-fold high."""
235
+ v = values
236
+ name = _file_name(path)
237
+ vendor = _vendor(v, name)
238
+
239
+ # an implausible count is unknown (ignored); see the exposure below
240
+ counts = [c for c in (_num(v, "NCOMBINE"), _num(v, "STACKCNT")) if c is not None and c <= MAX_SUBS]
241
+ count = max(counts, default=0.0)
242
+ kinds = ((_str(v, "IMAGETYP") or "") + " " + (_str(v, "FRAME") or "")).lower()
243
+ is_stack = count > 1 or "master" in kinds or _stack_by_name(name.lower())
244
+ sub_count = int(count) if count > 1 else 1
245
+ if vendor == "dwarf":
246
+ # a Dwarf stack is a 3-plane image (raw subs are one Bayer plane) or says so by name or RESTACK;
247
+ # its EXPTIME is already the total integration and no keyword gives the sub count
248
+ is_stack = is_stack or (_num(v, "NAXIS3") or 0) >= 3 or bool(_num(v, "RESTACK"))
249
+
250
+ exposure, implausible = 0.0, False
251
+ for key in ("EXPTIME", "EXPOSURE"):
252
+ x = _num(v, key)
253
+ if x is None or x <= 0:
254
+ continue
255
+ if x > MAX_EXPOSURE_S and not (vendor == "dwarf" and is_stack): # a Dwarf stack's EXPTIME is its total
256
+ implausible = True
257
+ continue
258
+ exposure = x
259
+ break
260
+ if implausible and not exposure:
261
+ # an exposure that cannot be true is unknown, and a light of unknown length is not counted at all:
262
+ # the scan reports it as unreadable
263
+ raise HeaderError("implausible exposure")
264
+
265
+ integration = None
266
+ for key in ("LIVETIME", "TOTALEXP", "EXPTOT"):
267
+ integration = _num(v, key)
268
+ if integration is not None and integration > 0:
269
+ break
270
+ integration = None
271
+ if integration is None:
272
+ integration = sub_count * exposure
273
+
274
+ dt = _parse_dt(v.get("DATE-OBS"), v.get("TIME-OBS"))
275
+ local = vendor == "origin" or "local" in str(comments.get("DATE-OBS", "")).lower()
276
+ if vendor == "dwarf":
277
+ local = True # no UTC claim in the header; the date matches the device's own clock in the file name
278
+ if dt is not None:
279
+ dt -= timedelta(seconds=exposure) # DATE-OBS is the END of the exposure
280
+ start_utc = None if local else dt
281
+ start_local = dt if local else None
282
+
283
+ ra_dec = frame_centre(v)
284
+ camera, telescope = _gear(vendor, v)
285
+ iso = _num(v, "ISOSPEED")
286
+ if iso is None:
287
+ iso = _num(v, "ISO")
288
+
289
+ return Frame(
290
+ path=path,
291
+ vendor=vendor,
292
+ frame_type=_frame_type(v, name, path),
293
+ is_stack=is_stack,
294
+ sub_count=sub_count,
295
+ exposure_s=exposure,
296
+ integration_s=integration,
297
+ start_utc=start_utc,
298
+ start_local=start_local,
299
+ object_hint=_text(v, "OBJECT"),
300
+ ra_deg=ra_dec[0] if ra_dec else None,
301
+ dec_deg=ra_dec[1] if ra_dec else None,
302
+ fov_deg=field_of_view(v),
303
+ focal_mm=_num(v, "FOCALLEN"),
304
+ camera=camera,
305
+ telescope=telescope,
306
+ filter=_text(v, "FILTER"),
307
+ gain=_num(v, "GAIN"),
308
+ iso=int(iso) if iso is not None else None,
309
+ sensor_c=_num(v, "CCD-TEMP"),
310
+ site=_site(v),
311
+ )
@@ -0,0 +1,187 @@
1
+ """Read FITS, FITS-compressed (.fz) and XISF headers from raw bytes. Standard library only."""
2
+ import re
3
+ import struct
4
+ import xml.etree.ElementTree as ET
5
+
6
+ BLOCK = 2880
7
+ CARD = 80
8
+ XISF_MAGIC = b"XISF0100"
9
+ FITS_MAGIC = b"SIMPLE"
10
+
11
+
12
+ class HeaderError(ValueError):
13
+ """The bytes are not a readable FITS or XISF header."""
14
+
15
+
16
+ # a binary table's own structure, which must never stand in for the image's (NAXIS1 = 8 bytes per row, ...)
17
+ _TABLE_KEY = re.compile(r"^(XTENSION|BITPIX|NAXIS\d*|PCOUNT|GCOUNT|TFIELDS|THEAP|(TTYPE|TFORM|TUNIT|TDIM)\d+)$")
18
+ _ZNAXIS = re.compile(r"^ZNAXIS(\d+)$")
19
+
20
+
21
+ def _parse_value(text):
22
+ """Split the value field of a card into (value, comment)."""
23
+ text = text.strip()
24
+ if text.startswith("'"):
25
+ out, i = [], 1
26
+ while i < len(text):
27
+ if text[i] == "'":
28
+ if text[i + 1:i + 2] == "'":
29
+ out.append("'")
30
+ i += 2
31
+ continue
32
+ break
33
+ out.append(text[i])
34
+ i += 1
35
+ rest = text[i + 1:]
36
+ comment = rest.split("/", 1)[1].strip() if "/" in rest else ""
37
+ return "".join(out).rstrip(), comment
38
+ raw, _, comment = text.partition("/")
39
+ return _typed(raw.strip()), comment.strip()
40
+
41
+
42
+ def _typed(token):
43
+ if token == "T":
44
+ return True
45
+ if token == "F":
46
+ return False
47
+ try:
48
+ return int(token)
49
+ except ValueError:
50
+ pass
51
+ try:
52
+ return float(token.replace("D", "E").replace("d", "e"))
53
+ except ValueError:
54
+ return token
55
+
56
+
57
+ def _parse_fits(data, offset):
58
+ """Parse one FITS header starting at offset.
59
+
60
+ Returns (values, comments, next_offset), or None when no END card is in data.
61
+ """
62
+ values, comments = {}, {}
63
+ last_key = None
64
+ pos = offset
65
+ while pos + CARD <= len(data):
66
+ card = data[pos:pos + CARD].decode("ascii", "replace")
67
+ pos += CARD
68
+ key = card[:8].strip().upper()
69
+ if key == "END":
70
+ end = offset + -(-(pos - offset) // BLOCK) * BLOCK
71
+ return values, comments, end
72
+ if key == "CONTINUE":
73
+ prev = values.get(last_key)
74
+ rest = card[8:].strip()
75
+ # a continued string is marked by a trailing '&'
76
+ if isinstance(prev, str) and prev.endswith("&") and rest.startswith("'"):
77
+ values[last_key] = prev[:-1] + _parse_value(rest)[0]
78
+ continue
79
+ if not key or key in ("COMMENT", "HISTORY") or card[8:10] != "= ":
80
+ continue
81
+ value, comment = _parse_value(card[10:])
82
+ if key not in values:
83
+ values[key] = value
84
+ if comment:
85
+ comments[key] = comment
86
+ last_key = key
87
+ else:
88
+ last_key = None
89
+ return None
90
+
91
+
92
+ def _merge_extension(values, comments, ext_values, ext_comments):
93
+ """The primary header with the first extension's keys over it.
94
+
95
+ An IMAGE extension is the image, so all of its keys apply. A binary table (an fpacked .fz image is one) never
96
+ lends its own structure keys; when it holds a compressed image (ZIMAGE = T), ZBITPIX/ZNAXIS/ZNAXISn are the
97
+ image's BITPIX/NAXIS/NAXISn.
98
+ """
99
+ if str(ext_values.get("XTENSION", "")).strip().upper() == "IMAGE":
100
+ return {**values, **ext_values}, {**comments, **ext_comments}
101
+ out, out_c = dict(values), dict(comments)
102
+ for k, x in ext_values.items():
103
+ if _TABLE_KEY.match(k):
104
+ continue
105
+ out[k] = x
106
+ if k in ext_comments:
107
+ out_c[k] = ext_comments[k]
108
+ if ext_values.get("ZIMAGE") is True:
109
+ for k, x in ext_values.items():
110
+ m = _ZNAXIS.match(k)
111
+ if m:
112
+ out[f"NAXIS{m.group(1)}"] = x
113
+ for z, k in (("ZBITPIX", "BITPIX"), ("ZNAXIS", "NAXIS")):
114
+ if z in ext_values:
115
+ out[k] = ext_values[z]
116
+ return out, out_c
117
+
118
+
119
+ def _fits_headers_complete(data):
120
+ """Walk the primary header (and the first extension's, for .fz). None means more bytes are needed."""
121
+ first = _parse_fits(data, 0)
122
+ if first is None:
123
+ return None
124
+ values, comments, end = first
125
+ if values.get("NAXIS") == 0 and values.get("EXTEND") is True:
126
+ second = _parse_fits(data, end)
127
+ if second is None:
128
+ return None
129
+ ext_values, ext_comments, end = second
130
+ values, comments = _merge_extension(values, comments, ext_values, ext_comments)
131
+ return values, comments, end
132
+
133
+
134
+ def _next_size(have):
135
+ return (have // BLOCK + 1) * BLOCK
136
+
137
+
138
+ def header_bytes_needed(prefix: bytes) -> int:
139
+ """0 when every needed header in prefix is complete, else the total bytes to read next."""
140
+ if not prefix:
141
+ return BLOCK
142
+ if prefix.startswith(XISF_MAGIC):
143
+ if len(prefix) < 16:
144
+ return 16
145
+ total = 16 + struct.unpack_from("<I", prefix, 8)[0]
146
+ return 0 if len(prefix) >= total else total
147
+ if prefix.startswith(FITS_MAGIC):
148
+ if _fits_headers_complete(prefix) is not None:
149
+ return 0
150
+ return _next_size(len(prefix))
151
+ if len(prefix) < len(XISF_MAGIC) and (XISF_MAGIC.startswith(prefix) or FITS_MAGIC.startswith(prefix)):
152
+ return BLOCK
153
+ raise HeaderError("not a FITS or XISF header")
154
+
155
+
156
+ def read_header(data: bytes):
157
+ """Return (values, comments) with upper-case keys."""
158
+ if data.startswith(XISF_MAGIC):
159
+ return _read_xisf(data)
160
+ # anything else is tried as FITS cards: it must still yield an END card
161
+ result = _fits_headers_complete(data)
162
+ if result is None:
163
+ raise HeaderError("not a FITS or XISF header (no END card in the bytes given)")
164
+ return result[0], result[1]
165
+
166
+
167
+ def _read_xisf(data):
168
+ if len(data) < 16:
169
+ raise HeaderError("truncated XISF header")
170
+ length = struct.unpack_from("<I", data, 8)[0]
171
+ if len(data) < 16 + length:
172
+ raise HeaderError("truncated XISF header")
173
+ try:
174
+ root = ET.fromstring(data[16:16 + length])
175
+ except ET.ParseError as exc:
176
+ raise HeaderError(f"bad XISF XML: {exc}") from exc
177
+ values, comments = {}, {}
178
+ for el in root.iter():
179
+ if el.tag.rsplit("}", 1)[-1] != "FITSKeyword":
180
+ continue
181
+ key = el.get("name", "").strip().upper()
182
+ if not key or key in ("COMMENT", "HISTORY") or key in values:
183
+ continue
184
+ values[key], _ = _parse_value(el.get("value", ""))
185
+ if el.get("comment"):
186
+ comments[key] = el.get("comment")
187
+ return values, comments
@@ -0,0 +1,39 @@
1
+ """Telescope and camera names fit to print: no device ids, serial numbers or long free text. Standard library only.
2
+
3
+ Every TELESCOP/INSTRUME string that can reach a card or summary.json passes through ``clean_label`` (frame.py).
4
+ """
5
+ import re
6
+ import unicodedata
7
+
8
+ MAX_LEN = 32
9
+ _HEX_SUFFIX = re.compile(r"[_-][0-9A-Fa-f]{6,}$") # "S50_4a8b9c2d" -> "S50"
10
+ _DIGIT_RUN = re.compile(r"\d{6,}") # serial numbers, dates
11
+ _NOT_ALLOWED = re.compile(r"[^A-Za-z0-9 .,+/'\"()#&-]")
12
+ _EMPTY_PARENS = re.compile(r"\(\s*\)")
13
+ _EDGE = " .,+/&#-"
14
+
15
+
16
+ def clean_label(raw) -> str | None:
17
+ """A short printable name from a header string, or None when nothing is left.
18
+
19
+ Strips a trailing device id (``_``/``-`` then 6+ hex digits) and any run of 6+ digits, keeps only
20
+ ``[A-Za-z0-9 .,+/'"()#&-]`` (accents are folded first, underscores become spaces) and cuts at 32 characters on a
21
+ word boundary.
22
+ """
23
+ if raw is None or isinstance(raw, bool):
24
+ return None
25
+ s = str(raw).strip()
26
+ prev = None
27
+ while s != prev:
28
+ prev = s
29
+ s = _HEX_SUFFIX.sub("", s).strip()
30
+ s = _DIGIT_RUN.sub(" ", s)
31
+ s = unicodedata.normalize("NFKD", s).replace("_", " ")
32
+ s = _NOT_ALLOWED.sub("", s)
33
+ s = _EMPTY_PARENS.sub(" ", s)
34
+ s = re.sub(r"\s+", " ", s).strip(_EDGE)
35
+ if len(s) > MAX_LEN:
36
+ head = s[:MAX_LEN + 1]
37
+ s = head.rsplit(" ", 1)[0] if " " in head else s[:MAX_LEN]
38
+ s = s.strip(_EDGE)
39
+ return s or None
@@ -0,0 +1,123 @@
1
+ """Field centre and size from a FITS header's plate solve, else optics. Standard library only."""
2
+ import math
3
+ import re
4
+
5
+
6
+ def _num(v, key):
7
+ x = v.get(key)
8
+ if isinstance(x, bool) or not isinstance(x, (int, float)):
9
+ return None
10
+ return float(x) if math.isfinite(x) else None
11
+
12
+
13
+ def _position(ra, dec):
14
+ """(RA, Dec) when both are finite and on the sky (RA 0-360, wrapped to [0, 360); |Dec| <= 90), else None."""
15
+ if ra is None or dec is None or not (math.isfinite(ra) and math.isfinite(dec)):
16
+ return None
17
+ if not 0.0 <= ra <= 360.0 or abs(dec) > 90.0:
18
+ return None
19
+ return ra % 360.0, dec
20
+
21
+
22
+ def parse_sexagesimal(s, hours):
23
+ """'-05 23 28' / '12:30:00' / '5h35m17s' -> degrees (hours are multiplied by 15). None if unreadable.
24
+
25
+ ``hours=True`` reads a right ascension (None outside 0-360 degrees, 24h wraps to 0); ``hours=False`` reads a
26
+ declination (None beyond +-90). Non-finite text ('NaN', 'inf') is None too.
27
+ """
28
+ if not isinstance(s, str):
29
+ return None
30
+ text = s.strip()
31
+ if not text:
32
+ return None
33
+ sign = -1.0 if text.startswith("-") else 1.0
34
+ parts = [p for p in re.split(r"[\s:hdms°'\"′″]+", text.lstrip("+-")) if p]
35
+ if not 1 <= len(parts) <= 3:
36
+ return None
37
+ try:
38
+ nums = [float(p) for p in parts]
39
+ except ValueError:
40
+ return None
41
+ value = sign * sum(n / 60.0 ** i for i, n in enumerate(nums)) * (15.0 if hours else 1.0)
42
+ if not math.isfinite(value):
43
+ return None
44
+ if hours:
45
+ return value % 360.0 if 0.0 <= value <= 360.0 else None
46
+ return value if abs(value) <= 90.0 else None
47
+
48
+
49
+ def _cd_matrix(v):
50
+ """Return the 2x2 CD matrix (deg/pixel) or None if the header has no linear scale."""
51
+ cd = [_num(v, k) for k in ("CD1_1", "CD1_2", "CD2_1", "CD2_2")]
52
+ if any(c is not None for c in cd):
53
+ return [[cd[0] or 0.0, cd[1] or 0.0], [cd[2] or 0.0, cd[3] or 0.0]]
54
+ d1, d2 = _num(v, "CDELT1"), _num(v, "CDELT2")
55
+ if d1 is None or d2 is None:
56
+ return None
57
+ pc = [_num(v, k) for k in ("PC1_1", "PC1_2", "PC2_1", "PC2_2")]
58
+ if any(p is not None for p in pc):
59
+ p11 = 1.0 if pc[0] is None else pc[0]
60
+ p22 = 1.0 if pc[3] is None else pc[3]
61
+ return [[d1 * p11, d1 * (pc[1] or 0.0)], [d2 * (pc[2] or 0.0), d2 * p22]]
62
+ rot = math.radians(_num(v, "CROTA2") or 0.0)
63
+ c, s = math.cos(rot), math.sin(rot)
64
+ return [[d1 * c, -d2 * s], [d1 * s, d2 * c]]
65
+
66
+
67
+ def _wcs_centre(v):
68
+ cd = _cd_matrix(v)
69
+ n1, n2 = _num(v, "NAXIS1"), _num(v, "NAXIS2")
70
+ ra0, dec0 = _num(v, "CRVAL1"), _num(v, "CRVAL2")
71
+ if cd is None or n1 is None or n2 is None or _position(ra0, dec0) is None:
72
+ return None
73
+ crpix1 = _num(v, "CRPIX1")
74
+ crpix2 = _num(v, "CRPIX2")
75
+ if crpix1 is None or crpix2 is None:
76
+ return None
77
+ dx, dy = (n1 + 1) / 2 - crpix1, (n2 + 1) / 2 - crpix2
78
+ x = math.radians(cd[0][0] * dx + cd[0][1] * dy) # intermediate world coords, radians
79
+ y = math.radians(cd[1][0] * dx + cd[1][1] * dy)
80
+ rho = math.hypot(x, y)
81
+ if rho == 0.0:
82
+ return ra0 % 360.0, dec0
83
+ c = math.atan(rho) # TAN: angular distance from the tangent point
84
+ d0 = math.radians(dec0)
85
+ sin_c, cos_c = math.sin(c), math.cos(c)
86
+ dec = math.asin(max(-1.0, min(1.0, cos_c * math.sin(d0) + y * sin_c * math.cos(d0) / rho)))
87
+ dra = math.atan2(x * sin_c, rho * math.cos(d0) * cos_c - y * math.sin(d0) * sin_c)
88
+ return (ra0 + math.degrees(dra)) % 360.0, math.degrees(dec)
89
+
90
+
91
+ def frame_centre(v):
92
+ """(RA, Dec) in degrees at the frame centre; plate solve first, then RA/DEC, then OBJCTRA/OBJCTDEC."""
93
+ c = _wcs_centre(v)
94
+ if c is not None:
95
+ return _position(*c)
96
+ c = _position(_num(v, "RA"), _num(v, "DEC"))
97
+ if c is not None:
98
+ return c
99
+ return _position(parse_sexagesimal(v.get("OBJCTRA"), hours=True), parse_sexagesimal(v.get("OBJCTDEC"), hours=False))
100
+
101
+
102
+ def _field(w, h):
103
+ """A field no wider than the sky (garbage scales would make the catalogue search endless), else None."""
104
+ ok = all(math.isfinite(x) and 0.0 < x <= 360.0 for x in (w, h))
105
+ return (w, h) if ok else None
106
+
107
+
108
+ def field_of_view(v):
109
+ """(width, height) in degrees from the WCS scale, else from pixel size and focal length."""
110
+ n1, n2 = _num(v, "NAXIS1"), _num(v, "NAXIS2")
111
+ if n1 is None or n2 is None:
112
+ return None
113
+ cd = _cd_matrix(v)
114
+ if cd is not None:
115
+ sx = math.hypot(cd[0][0], cd[1][0])
116
+ sy = math.hypot(cd[0][1], cd[1][1])
117
+ if sx > 0 and sy > 0 and _field(n1 * sx, n2 * sy):
118
+ return n1 * sx, n2 * sy
119
+ focal, pix = _num(v, "FOCALLEN"), _num(v, "XPIXSZ")
120
+ if focal and pix and focal > 0 and pix > 0:
121
+ scale = 206.265 * pix / focal / 3600.0 # degrees per pixel
122
+ return _field(n1 * scale, n2 * scale)
123
+ return None