Writing FITS files¶
- fitsy.image(data, header=None, primary=True)¶
Build an image HDU from an array.
- Parameters:
data (array-like) – Image pixels. A numpy array of dtype
bool,int8,uint8,int16,uint16,int32,uint32,int64,uint64,float32orfloat64, or anythingnumpy.asarray()accepts (nested lists, tuples, objects implementing__array__). The returned HDU’sNAXISlist is the reverse ofdata.shape, because numpy lists axes slowest-first and FITS lists them fastest-first.header (Header or mapping, optional) – Extra header cards to merge in. A
Headeror adict. Values may be scalars or(value, comment)tuples. DefaultNone, which adds no extra cards.primary (bool, optional) – Default
True. Builds the header withSIMPLE = T. Set toFalseto build an image extension header instead (XTENSION = 'IMAGE'withPCOUNTandGCOUNT).
- Returns:
ImageBuilder – Pass to
write().- Raises:
TypeError – If data is neither an array of one of the dtypes above nor something
numpy.asarray()accepts.
Notes
int8,uint16,uint32anduint64have no direct FITS type. fitsy stores each one under the FITS unsigned-integer convention, which a conforming reader decodes back to the original values. Aboolarray is stored asBITPIX = 8.A float array holds physical values, so a
BZERO,BSCALEorBLANKcard in header is dropped. Those cards describe integer storage that the array no longer has, and keeping one would scale the values a second time when the file is read back. An integer array keeps the card that header supplies, in place of the card fitsy would compute.Pass
primary=Falseto everyimage()call after the first item passed towrite().write()raisesfitsy.FitsErrorif a later HDU still declaresSIMPLE, or if the first HDU does not.A
COMMENT,HISTORYor blank-keyword card in header carries into the built HDU, after the value cards.
- fitsy.compressed_image(data, header=None, *, tile_shape=None, extname=None)¶
Tile-compress a numpy array into a
BINTABLEHDU (ZIMAGE).The result is a tile-compressed image extension: a
BINTABLEwithZIMAGE = Twhose rows each hold one compressed tile.fitsy.open()reads it back as an image.- Parameters:
data (array-like) – Image pixels. A numpy array of dtype
bool,int8,uint8,int16,uint16,int32,uint32,int64,uint64,float32orfloat64, or anythingnumpy.asarray()accepts.header (Header or mapping, optional) – Extra cards merged into the synthesized image header before compression. A
Headeror adict. DefaultNone, which adds no extra cards.tile_shape (sequence of int, optional) – Tile shape in FITS axis order (
tile_shape[0]is theNAXIS1direction). Length must equaldata.ndim. DefaultNone, which tiles as(NAXIS1, 1, 1, ...)– one row per tile (Pence & Seaman 2010 Sec.3).extname (str, optional) –
EXTNAMEkeyword on the resulting BINTABLE. Default"COMPRESSED_IMAGE".
- Returns:
BinTableBuilder – Pass to
write().- Raises:
TypeError – If data is neither an array of one of the dtypes above nor something
numpy.asarray()accepts.FitsError – If data has no axes (a 0-D array). Also raised if tile_shape is given and its length does not equal
data.ndim, or if one of its entries is0.
Notes
This function emits
ZCMPTYPE = 'GZIP_1'compressed tiles.GZIP_1is lossless for every dtype listed above.fitsy computes the structural cards of the compressed HDU itself. It therefore ignores a structural card, such as
BITPIX, and a reservedZcard, such asZBITPIX, in header. SetEXTNAMEthrough extname. Every other card carries into the compressed HDU and survives decompression, including aCOMMENT,HISTORYor blank-keyword card, which lands after the value cards.
- fitsy.bintable(columns, units=None, extname=None)¶
Build a
BINTABLEHDU from a column dictionary.- Parameters:
columns (dict[str, sequence]) –
One entry per column. All columns must share the same row count. Supported value kinds:
a numpy
bool,uint8,int16,int32,int64,float32orfloat64array (1-D, or 2-D for a fixed-repeat column)list[str]->nA(right-padded to the longest string)list[complex]->M(C128)list[list[float]]->1PDvariable-length column (heap-stored,f64element type). This applies to any nested numeric list, ragged or not. Pass a 2-D numpy array to get a fixed-repeat column instead.a flat sequence of numbers (
[1, 2, 3], a tuple, arange), converted withnumpy.asarray()and encoded as the dtype numpy infers
units (dict[str, str], optional) – Per-column
TUNITnstrings. DefaultNone, which adds noTUNITncards. A key that names no column in columns is ignored.extname (str, optional) –
EXTNAMEkeyword for this extension. DefaultNone, which adds noEXTNAMEcard.
- Returns:
BinTableBuilder – Pass to
write().- Raises:
ValueError – If a column’s values do not match one of the kinds listed above, or if the columns disagree on row count.
Notes
A numpy array of
int8,uint16,uint32oruint64is not one of the supported kinds; convert it first, for example witharr.astype(numpy.int32).
- fitsy.ascii_table(columns, formats=None, tnulls=None, units=None, extname=None)¶
Build an ASCII
TABLEHDU from a column dictionary.- Parameters:
columns (dict[str, sequence]) –
One entry per column. All columns must share the same row count. Supported value kinds:
list[str]->A{maxlen}list[int],list[Optional[int]], or a numpy integer array ->I{w}by default. ANonecell needs a matching entry in tnulls.list[float]or a numpy float array ->E{w}.{d}by default
formats (dict[str, str], optional) – Per-column override for the auto-chosen
TFORMcode, such as{"flux": "F10.3"}. The format kind must match the column’s value kind:Ifor an integer column,F/E/Dfor a float column,Afor a string column. DefaultNone, which auto-chooses every column’s format.tnulls (dict[str, str], optional) –
TNULLsentinel string for a numeric column that holds an undefined cell (Nonefor an integer column,nanfor a float column). DefaultNone, which sets noTNULL.units (dict[str, str], optional) – Per-column
TUNITstrings. DefaultNone, which adds noTUNITcards.extname (str, optional) –
EXTNAMEkeyword. DefaultNone, which adds noEXTNAMEcard.
- Returns:
AsciiTableBuilder – Pass to
write().- Raises:
TypeError – If a column’s values do not match
list[str],list[Optional[int]], orlist[float], or if formats gives a format kind that does not match the column’s value kind.ValueError – If a string cell holds a byte outside ASCII 32-126 (Standard Sec.7.2.5).
FitsError – If formats holds a string that is not a valid
TFORMcode, if the columns disagree on row count, if a rendered cell or aTNULLsentinel does not fit the column’s field width, or if a numeric column holds an undefined cell with no matching entry in tnulls.
- fitsy.write(path, hdus, overwrite=False, *, checksums=False)¶
Write a sequence of HDU builders to disk.
- Parameters:
path (str or os.PathLike) – Destination path.
hdus (list) – Builders returned by
image(),bintable(),ascii_table()orcompressed_image(). When the first item is an image builder, it becomes the primary HDU, and it must have been built withprimary=True. When the first item is any other builder, fitsy writes an empty primary HDU before it. A table-only file thus needs no placeholder image.overwrite (bool, optional) – Default
False, which raisesfitsy.FitsErrorinstead of truncating an existing file at path.Truetruncates and overwrites it.checksums (bool, optional) – Default
False.Truecomputes and stampsCHECKSUMandDATASUMcards on every emitted HDU (FITS Checksum Proposal).
- Raises:
ValueError – If hdus is empty.
TypeError – If an item of hdus is not an
ImageBuilder,BinTableBuilderorAsciiTableBuilder.FitsError – If path cannot be opened for writing, for example because it already exists and overwrite is
False. Also raised if an HDU built with the wrong primary value reaches the writer – a non-first image HDU built withprimary=True, or a first image HDU built withprimary=False.
Notes
When checksums is
False, fitsy writes aCHECKSUMorDATASUMcard already present in a builder’s header verbatim, unchanged.Examples
>>> import numpy as np, fitsy >>> fitsy.write("out.fits", [ ... fitsy.image(np.zeros((10, 10), dtype=np.float32)), ... ])
- fitsy.append(path, data, header=None)¶
Append one image HDU to an existing FITS file.
Writes the new HDU directly after the last existing HDU. fitsy rewrites no existing HDU.
- Parameters:
path (str or os.PathLike) – FITS file to append to. The file must already exist and must parse as FITS.
data (array-like) – Image pixels for the new HDU. A numpy array of dtype
bool,int8,uint8,int16,uint16,int32,uint32,int64,uint64,float32orfloat64, or anythingnumpy.asarray()accepts.header (Header or mapping, optional) – Extra header cards for the new HDU. Default
None.
- Raises:
Notes
fitsy writes the new HDU as an extension, with
XTENSION = 'IMAGE'. fitsy parses the whole file first, to check it and to find the offset of the append. Any bytes after the last HDU are overwritten.fitsy builds the new HDU with
fitsy.image(). See that function for the dtype rule, and for theBZEROandBSCALEcards it adds for an unsigned dtype.
- fitsy.setval(path, key, value=None, *, ext=None, comment=None)¶
Set one header keyword in path. Rewrites the file.
- Parameters:
path (str or os.PathLike) – File to edit.
key (str) – Header keyword to set.
value (bool, int, float, complex, str, or None, optional) – New card value. Default
None, which writes a card with an undefined value.ext (int or str, keyword-only, optional) – HDU index or
EXTNAME. Default is HDU 0.comment (str, keyword-only, optional) – New card comment. Default
None, which leaves an existing card’s comment unchanged.
- Raises:
FitsError – If path cannot be opened or parsed as FITS, if key is not a valid FITS keyword, or if the rewrite fails.
IndexError – If ext is an out-of-range integer.
KeyError – If ext is a string that names no HDU.
TypeError – If ext is neither an int, a str, nor omitted. Also raised if value is a type fitsy cannot store in a header card.
ValueError – If key names a structural card managed by the writer, such as
BITPIXorNAXIS.
- fitsy.delval(path, key, *, ext=None)¶
Remove one header keyword from path. Rewrites the file.
- Parameters:
path (str or os.PathLike) – File to edit.
key (str) – Header keyword to remove.
ext (int or str, keyword-only, optional) – HDU index or
EXTNAME. Default is HDU 0.
- Raises:
FitsError – If path cannot be opened or parsed as FITS, or if the rewrite fails.
IndexError – If ext is an out-of-range integer.
KeyError – If ext is a string that names no HDU, or if key is absent from the selected header. Call
getval(), or testkey in headeron an open file, to guard an optional card.TypeError – If ext is neither an int, a str, nor omitted.
ValueError – If key names a structural card managed by the writer, such as
BITPIXorNAXIS.
- class fitsy.ImageBuilder¶
Bases:
objectOpaque image HDU spec produced by
image().Pass to
write()as part of a list of builders.
- class fitsy.BinTableBuilder¶
Bases:
objectOpaque BINTABLE HDU spec produced by
bintable().
- class fitsy.AsciiTableBuilder¶
Bases:
objectOpaque ASCII TABLE HDU spec produced by
ascii_table().