Headers¶
- class fitsy.Header¶
Bases:
objectDict-like view of a FITS header.
A
Headeris an owned snapshot that is shared with the parent HDU wrapper. Cloning the Python object yields another handle to the same underlying header, so a mutation made through one handle (for examplehdu.header['FOO'] = 'bar') is visible through every other handle.Headers obtained from a read-only
FitsFile(fitsy.open()withmode='readonly', the default) raiseValueErrorfrom every mutating method. Open the file withmode='update'to enable in-memory edits.Examples
>>> with fitsy.open("image.fits") as f: ... hdr = f[0].header ... bitpix = hdr["BITPIX"] ... for key in hdr: ... print(key, hdr[key])
- __contains__(key, /)¶
Return key in self.
- __delitem__(key, /)¶
Delete self[key].
- __getitem__(key, /)¶
Return self[key].
- __iter__()¶
Implement iter(self).
- __len__()¶
Return len(self).
- __setitem__(key, value, /)¶
Set self[key] to value.
- add_commentary(kind, text)¶
Append a commentary card.
- Parameters:
kind ({'COMMENT', 'HISTORY', ''}) – Commentary kind. The empty string emits a blank-keyword commentary card.
text (str) – Commentary text. Long lines are split across multiple 80-byte cards on serialization.
- Raises:
TypeError – If
kindis not one of the recognized values.ValueError – If the header is read-only.
- cards(key)¶
Return every card matching
keyas a list of(value, comment)tuples, in declaration order.Useful when a keyword appears more than once and you need programmatic access to every occurrence (the indexed accessor only returns the first). Commentary cards yield
(text, None). Returns an empty list if no match is found.
- comment(key)¶
Inline comment for the first card with this keyword.
- Parameters:
key (str) – Keyword (case-insensitive match).
- Returns:
str or None – The comment text, or
Noneif no such card exists orthe matching card has no inline comment.
- date¶
Creation date of this HDU (
DATE), always UTC, as an ISO-8601 string.Returns
Noneif the keyword is absent.
- get(key, default=None)¶
Non-raising lookup (
header.get(key, default=None)).
- insert(position, keyword, value=None, comment=None, *, after=False)¶
Insert a value card at a specified position.
- Parameters:
position (int or str) – Integer index (0 = first card), or the keyword of an existing card; in the latter case the new card is inserted before/after it depending on after.
keyword (str) – Card keyword.
value (Any, optional) – Card value.
Nonerecords an undefined-value card.comment (str, optional) – Optional inline comment.
after (bool, optional) – When position is a keyword, set
after=Trueto insert the new card just after that card rather than before it.
- Raises:
KeyError – If position is a keyword that does not exist.
ValueError – If the header is read-only.
- items()¶
All
(keyword, value)pairs in declaration order.Commentary cards (COMMENT, HISTORY, blank) report
Nonefor the value.- Returns:
list of tuple
- keys()¶
All keywords in declaration order.
Duplicates are kept, matching FITS semantics where
HISTORYandCOMMENTcards repeat.
- mjd_avg_utc¶
Average/mid time of the observation as UTC MJD (
MJD-AVG/DATE-AVG).
- mjd_begin_utc¶
Start of the observation as UTC MJD. Reads
MJD-BEG/DATE-BEG/TSTARTand converts fromTIMESYS; falls back toUTSTART.
- mjd_end_utc¶
End of the observation as UTC MJD. Reads
MJD-END/DATE-END/TSTOPand converts fromTIMESYS; falls back toUTSTOP.
- mjd_obs_utc¶
Observation start converted to UTC MJD, regardless of
TIMESYS.Handles the full set of time scales defined in WCS Paper IV:
UTC,GMT,TAI,TT/TDT/ET,GPS,TCG,TDB, andTCB. Barycentric/geocentric scales are reduced to TT via the linear relations in Sec.3.1.2 before the leap-second table is applied.- Returns:
float or None – UTC MJD of the observation start, or
Noneif the observation time is absent or the time scale cannot be reduced to UTC (e.g.LOCAL,UT1).
- mjd_ref¶
Reference epoch as MJD. Reads
MJDREFI``+``MJDREFF->MJDREF->JDREFI``+``JDREFF->JDREF->DATEREF. Zero point for relative time values in the HDU.
- obs_ecef¶
Observatory location as ITRS/ECEF Cartesian
(x, y, z)in meters. ReadsOBSGEO-X/Y/Zdirectly; falls back to geodetic keywords converted via WGS84.
- obs_geodetic¶
Observatory geodetic coordinates
(lat_deg, lon_deg, alt_m)on the WGS84 ellipsoid.Tries
OBSGEO-B/L/Hfirst, then non-standard variants (SITELAT,SITELONG,SITEELEV, etc.).Noneif neither latitude nor longitude is present.
- obs_orbit¶
URI, URL, or name.
- Type:
Orbit ephemeris file (
OBSORBIT)
- read_only¶
True when this header was obtained from a read-only file.
In that case, mutating methods raise
ValueError.
- rename_keyword(oldname, newname)¶
Rename every value card whose keyword equals oldname to use newname.
- Parameters:
- Raises:
KeyError – If no card with oldname exists.
ValueError – If the header is read-only or newname is not a valid keyword.
- set(keyword, value=None, comment=None, *, before=None, after=None)¶
Set a header card with optional positional placement.
Equivalent to
astropy.io.fits.Header.set: if the keyword already exists its value (and comment, if supplied) are updated in place; otherwise a new card is appended unlessbeforeorafteris given, in which case the new card is inserted at that position.- Parameters:
keyword (str) – Card keyword. May be a HIERARCH name.
value (Any, optional) – New value. If omitted (and the card already exists), only the comment is updated.
comment (str, optional) – New comment.
Noneleaves the existing comment intact when updating, or emits no comment when inserting.before (str, optional) – Insert the new card immediately before the first card whose keyword equals this. Ignored if keyword already exists.
after (str, optional) – Insert the new card immediately after the first card whose keyword equals this. Ignored if keyword already exists. Mutually exclusive with before.
- Raises:
ValueError – If both before and after are supplied, or if the header is read-only.
KeyError – If the named before/after card does not exist.
- time_elapsed¶
Wall-clock elapsed time in seconds (
TELAPSE), including dead time.Noneif absent orTIMEUNITis unrecognized.
- time_exposure¶
Start of the observation as MJD in the native
TIMESYSscale.Effective exposure time in seconds (
XPOSURE), excluding dead time.Noneif absent orTIMEUNITis unrecognized.
- time_sys¶
Active time scale (
TIMESYS), upper-cased.Returns
"UTC"when the keyword is absent, per the FITS standard default.- Returns:
str – One of
"UTC","TAI","TT","TDB","TCG","TCB","GPS","LOCAL", etc. (WCS Paper IV Table 1).
- time_unit¶
Time unit for numeric time values (
TIMEUNIT), lower-cased.Returns
"s"when the keyword is absent (FITS standard default).
- to_dict()¶
Plain
dictview of the header.Comments are dropped; duplicate keywords are deduplicated by last-seen value. Convenience for ad-hoc work; round-trip fidelity requires
items().
- tostring()¶
Serialize the header as a single string of 80-character FITS cards (no separators, terminated by
ENDand padded to a 2880-byte block). Mirrorsastropy.io.fits.Header.tostringso this object can be fed toastropy.wcs.WCSviafits.Header.fromstring(h.tostring()).
- unit_for(key)¶
Unit string for key extracted from the [unit] comment convention. Returns
Noneif the keyword is absent or carries no unit annotation.
- update(other)¶
Merge another header (or a
str-keyed mapping) into this one.For each
(key, value)inother, behaves likeself[key] = value: existing keywords are overwritten in place, new keywords are appended.Commentary cards (
COMMENT,HISTORY, blank-keyword) are not copied; useadd_commentary()if you want to transfer them explicitly.- Parameters:
other (Header or Mapping[str, Any]) – The values to merge in.
Headerinstances copy their value cards; mappings are iterated in declaration order.- Raises:
ValueError – If the header is read-only.
TypeError – If
otheris neither aHeadernor a string-keyed mapping.
- validate(fix=False, warn=True)¶
Check the header for deprecated, non-standard, or missing keywords.
- Parameters:
- Returns:
Header – A new independent snapshot of this header (fixed when
fix=True, otherwise an unmodified clone).
- value_in_si(key)¶
Value of key converted to the SI base unit for its dimension.
Reads the unit from the [unit] comment annotation and applies the conversion factor. Returns
Noneif the keyword is absent, non-numeric, unannotated, or the unit is unrecognized.
- class fitsy.HeaderCommentary¶
Bases:
objectList-like view of every commentary card body that shares a keyword (
COMMENT,HISTORY, blank-keyword). Returned byfitsy.Header.__getitem__()for those keywords; mirrorsastropy.io.fits.header._HeaderCommentaryCards.len(view)– number of cardsview[i]– text body of the i-th cardstr(view)/repr(view)– newline-joined bodiesiterable
- __getitem__(key, /)¶
Return self[key].
- __iter__()¶
Implement iter(self).
- __len__()¶
Return len(self).