Headers

class fitsy.Header

Bases: object

Dict-like view of a FITS header.

A Header is 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 example hdu.header['FOO'] = 'bar') is visible through every other handle.

Headers obtained from a read-only FitsFile (fitsy.open() with mode='readonly', the default) raise ValueError from every mutating method. Open the file with mode='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 kind is not one of the recognized values.

  • ValueError – If the header is read-only.

cards(key)

Return every card matching key as 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 None if no such card exists or

  • the matching card has no inline comment.

date

Creation date of this HDU (DATE), always UTC, as an ISO-8601 string.

Returns None if the keyword is absent.

get(key, default=None)

Non-raising lookup (header.get(key, default=None)).

Parameters:
  • key (str) – Keyword to look up.

  • default (object, optional) – Value to return if key is absent. Defaults to None.

Returns:

object – The matching value, or default if absent.

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. None records an undefined-value card.

  • comment (str, optional) – Optional inline comment.

  • after (bool, optional) – When position is a keyword, set after=True to 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 None for the value.

Returns:

list of tuple

keys()

All keywords in declaration order.

Duplicates are kept, matching FITS semantics where HISTORY and COMMENT cards 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/TSTART and converts from TIMESYS; falls back to UTSTART.

mjd_end_utc

End of the observation as UTC MJD. Reads MJD-END/DATE-END/TSTOP and converts from TIMESYS; falls back to UTSTOP.

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, and TCB. 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 None if 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. Reads OBSGEO-X/Y/Z directly; 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/H first, then non-standard variants (SITELAT, SITELONG, SITEELEV, etc.). None if 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:
  • oldname (str) – Existing keyword.

  • newname (str) – Replacement keyword. Must be a valid FITS or HIERARCH keyword.

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 unless before or after is 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. None leaves 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. None if absent or TIMEUNIT is unrecognized.

time_exposure

Start of the observation as MJD in the native TIMESYS scale.

Effective exposure time in seconds (XPOSURE), excluding dead time. None if absent or TIMEUNIT is 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 dict view 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 END and padded to a 2880-byte block). Mirrors astropy.io.fits.Header.tostring so this object can be fed to astropy.wcs.WCS via fits.Header.fromstring(h.tostring()).

unit_for(key)

Unit string for key extracted from the [unit] comment convention. Returns None if 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) in other, behaves like self[key] = value: existing keywords are overwritten in place, new keywords are appended.

Commentary cards (COMMENT, HISTORY, blank-keyword) are not copied; use add_commentary() if you want to transfer them explicitly.

Parameters:

other (Header or Mapping[str, Any]) – The values to merge in. Header instances copy their value cards; mappings are iterated in declaration order.

Raises:
  • ValueError – If the header is read-only.

  • TypeError – If other is neither a Header nor a string-keyed mapping.

validate(fix=False, warn=True)

Check the header for deprecated, non-standard, or missing keywords.

Parameters:
  • fix (bool, optional) – When True, every suggested fix is applied to the returned header copy. Defaults to False.

  • warn (bool, optional) – When True (the default), each issue is emitted as a Python warnings warning prefixed with [warning] or [error]. Set to False to suppress all output.

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 None if the keyword is absent, non-numeric, unannotated, or the unit is unrecognized.

class fitsy.HeaderCommentary

Bases: object

List-like view of every commentary card body that shares a keyword (COMMENT, HISTORY, blank-keyword). Returned by fitsy.Header.__getitem__() for those keywords; mirrors astropy.io.fits.header._HeaderCommentaryCards.

  • len(view) – number of cards

  • view[i] – text body of the i-th card

  • str(view) / repr(view) – newline-joined bodies

  • iterable

__getitem__(key, /)

Return self[key].

__iter__()

Implement iter(self).

__len__()

Return len(self).