Previous topic

FITS/Image Utilities

Next topic

FITSDIFF

This Page

STPyFITS

The stpyfits module serves as a layer on top of PyFITS to support the use of single-valued arrays in extensions using the NPIX/PIXVALUE convention developed at STScI. The standard PyFITS module implements the strict FITS conventions, and these single-valued arrays are not part of the FITS standard.

The stpyfits module is an extension to the pyfits module which offers additional features specific to STScI. These features include the handling of Constant Data Value Arrays.

The pyfits module is:

A module for reading and writing FITS files and manipulating their contents.

A module for reading and writing Flexible Image Transport System (FITS) files. This file format was endorsed by the International Astronomical Union in 1999 and mandated by NASA as the standard format for storing high energy astrophysics data. For details of the FITS standard, see the NASA/Science Office of Standards and Technology publication, NOST 100-2.0.

For detailed examples of usage, see the PyFITS User’s Manual.

exception pytools.stpyfits.VerifyError

Bases: exceptions.Exception

Verify exception class.

class pytools.stpyfits.TableHDU(data=None, header=None, name=None)

Bases: pyfits.core._TableBaseHDU

FITS ASCII table extension HDU class.

Parameters :
 

data : array

data of the table

header : Header instance

header to be used for the HDU

name : str

the EXTNAME value

class pytools.stpyfits.ColDefs(input, tbtype='BinTableHDU')

Bases: object

Column definitions class.

It has attributes corresponding to the Column attributes (e.g. ColDefs has the attribute names while Column has name). Each attribute in ColDefs is a list of corresponding attribute values from all Column objects.

Parameters :
 

input : sequence of Column objects

an (table) HDU

tbtype : str, optional

which table HDU, "BinTableHDU" (default) or "TableHDU" (text table).

add_col(column)

Append one Column to the column definition.

Warning

New in pyfits 2.3: This function appends the new column to the ColDefs object in place. Prior to pyfits 2.3, this function returned a new ColDefs with the new column at the end.

change_attrib(col_name, attrib, new_value)

Change an attribute (in the commonName list) of a Column.

col_name : str or int
The column name or index to change
attrib : str
The attribute name
value : object
The new value for the attribute
change_name(col_name, new_name)

Change a Column‘s name.

col_name : str
The current name of the column
new_name : str
The new name of the column
change_unit(col_name, new_unit)

Change a Column‘s unit.

col_name : str or int
The column name or index
new_unit : str
The new unit for the column
del_col(col_name)

Delete (the definition of) one Column.

col_name : str or int
The column’s name or index
info(attrib='all')

Get attribute(s) information of the column definition.

Parameters :
 

attrib : str

Can be one or more of the attributes listed in _commonNames. The default is "all" which will print out all attributes. It forgives plurals and blanks. If there are two or more attribute names, they must be separated by comma(s).

Notes

This function doesn’t return anything, it just prints to stdout.

pytools.stpyfits.PrimaryHDU

alias of st_PrimaryHDU

class pytools.stpyfits.StreamingHDU(name, header)

A class that provides the capability to stream data to a FITS file instead of requiring data to all be written at once.

The following pseudocode illustrates its use:

header = pyfits.Header()

for all the cards you need in the header:
    header.update(key,value,comment)

shdu = pyfits.StreamingHDU('filename.fits',header)

for each piece of data:
    shdu.write(data)

shdu.close()

Construct a StreamingHDU object given a file name and a header.

Parameters :
 

name : file path, file object, or file like object

The file to which the header and data will be streamed. If opened, the file object must be opened for append (ab+).

header : Header instance

The header object associated with the data to be written to the file.

Notes

The file will be opened and the header appended to the end of the file. If the file does not already exist, it will be created, and if the header represents a Primary header, it will be written to the beginning of the file. If the file does not exist and the provided header is not a Primary header, a default Primary HDU will be inserted at the beginning of the file and the provided header will be added as the first extension. If the file does already exist, but the provided header represents a Primary header, the header will be modified to an image extension header and appended to the end of the file.

close()

Close the physical FITS file.

size()

Return the size (in bytes) of the data portion of the HDU.

write(data)

Write the given data to the stream.

Parameters :
 

data : ndarray

Data to stream to the file.

Returns :
 

writeComplete : int

Flag that when True indicates that all of the required data has been written to the stream.

Notes

Only the amount of data specified in the header provided to the class constructor may be written to the stream. If the provided data would cause the stream to overflow, an IOError exception is raised and the data is not written. Once sufficient data has been written to the stream to satisfy the amount specified in the header, the stream is padded to fill a complete FITS block and no more data will be accepted. An attempt to write more data after the stream has been filled will raise an IOError exception. If the dtype of the input data does not match what is expected by the header, a TypeError exception is raised.

class pytools.stpyfits.GroupsHDU(data=None, header=None, name=None)

Bases: pyfits.core.PrimaryHDU

FITS Random Groups HDU class.

TODO: Write me

size()

Returns the size (in bytes) of the HDU’s data part.

pytools.stpyfits.HDUList

alias of st_HDUList

class pytools.stpyfits.GroupData

Bases: pyfits.core.FITS_rec

Random groups data object.

Allows structured access to FITS Group data in a manner analogous to tables.

par(parName)

Get the group parameter values.

pytools.stpyfits.ImageHDU

alias of st_ImageHDU

class pytools.stpyfits.FITS_rec

Bases: pyfits.rec.recarray

FITS record array class.

FITS_rec is the data part of a table HDU’s data part. This is a layer over the recarray, so we can deal with scaled columns.

It inherits all of the standard methods from numpy.ndarray.

field(key)

A view of a Column‘s data as an array.

class pytools.stpyfits.Section(hdu)

Image section.

TODO: elaborate

class pytools.stpyfits.CompImageHDU(data=None, header=None, name=None, compressionType='RICE_1', tileSize=None, hcompScale=0.0, hcompSmooth=0, quantizeLevel=16.0)

Bases: pyfits.core.BinTableHDU

Compressed Image HDU class.

Parameters :
 

data : array, optional

data of the image

header : Header instance, optional

header to be associated with the image; when reading the HDU from a file ( data = “DELAYED” ), the header read from the file

name : str, optional

the EXTNAME value; if this value is None, then the name from the input image header will be used; if there is no name in the input image header then the default name COMPRESSED_IMAGE is used.

compressionType : str, optional

compression algorithm ‘RICE_1’, ‘PLIO_1’, ‘GZIP_1’, ‘HCOMPRESS_1’

tileSize : int, optional

compression tile sizes. Default treats each row of image as a tile.

hcompScale : float, optional

HCOMPRESS scale parameter

hcompSmooth : float, optional

HCOMPRESS smooth parameter

quantizeLevel : float, optional

floating point quantization level; see note below

Notes

The pyfits module supports 2 methods of image compression.

  1. The entire FITS file may be externally compressed with the gzip or pkzip utility programs, producing a *.gz or *.zip file, respectively. When reading compressed files of this type, pyfits first uncompresses the entire file into a temporary file before performing the requested read operations. The pyfits module does not support writing to these types of compressed files. This type of compression is supported in the _File class, not in the CompImageHDU class. The file compression type is recognized by the .gz or .zip file name extension.
  2. The CompImageHDU class supports the FITS tiled image compression convention in which the image is subdivided into a grid of rectangular tiles, and each tile of pixels is individually compressed. The details of this FITS compression convention are described at the FITS Support Office web site. Basically, the compressed image tiles are stored in rows of a variable length arrray column in a FITS binary table. The pyfits module recognizes that this binary table extension contains an image and treats it as if it were an image extension. Under this tile-compression format, FITS header keywords remain uncompressed. At this time, pyfits does not support the ability to extract and uncompress sections of the image without having to uncompress the entire image.

The pyfits module supports 3 general-purpose compression algorithms plus one other special-purpose compression technique that is designed for data masks with positive integer pixel values. The 3 general purpose algorithms are GZIP, Rice, and HCOMPRESS, and the special-purpose technique is the IRAF pixel list compression technique (PLIO). The compressionType parameter defines the compression algorithm to be used.

The FITS image can be subdivided into any desired rectangular grid of compression tiles. With the GZIP, Rice, and PLIO algorithms, the default is to take each row of the image as a tile. The HCOMPRESS algorithm is inherently 2-dimensional in nature, so the default in this case is to take 16 rows of the image per tile. In most cases, it makes little difference what tiling pattern is used, so the default tiles are usually adequate. In the case of very small images, it could be more efficient to compress the whole image as a single tile. Note that the image dimensions are not required to be an integer multiple of the tile dimensions; if not, then the tiles at the edges of the image will be smaller than the other tiles. The tileSize parameter may be provided as a list of tile sizes, one for each dimension in the image. For example a tileSize value of [100,100] would divide a 300 X 300 image into 9 100 X 100 tiles.

The 4 supported image compression algorithms are all ‘loss-less’ when applied to integer FITS images; the pixel values are preserved exactly with no loss of information during the compression and uncompression process. In addition, the HCOMPRESS algorithm supports a ‘lossy’ compression mode that will produce larger amount of image compression. This is achieved by specifying a non-zero value for the hcompScale parameter. Since the amount of compression that is achieved depends directly on the RMS noise in the image, it is usually more convenient to specify the hcompScale factor relative to the RMS noise. Setting hcompScale = 2.5 means use a scale factor that is 2.5 times the calculated RMS noise in the image tile. In some cases it may be desirable to specify the exact scaling to be used, instead of specifying it relative to the calculated noise value. This may be done by specifying the negative of the desired scale value (typically in the range -2 to -100).

Very high compression factors (of 100 or more) can be achieved by using large hcompScale values, however, this can produce undesireable ‘blocky’ artifacts in the compressed image. A variation of the HCOMPRESS algorithm (called HSCOMPRESS) can be used in this case to apply a small amount of smoothing of the image when it is uncompressed to help cover up these artifacts. This smoothing is purely cosmetic and does not cause any significant change to the image pixel values. Setting the hcompSmooth parameter to 1 will engage the smoothing algorithm.

Floating point FITS images (which have BITPIX = -32 or -64) usually contain too much ‘noise’ in the least significant bits of the mantissa of the pixel values to be effectively compressed with any lossless algorithm. Consequently, floating point images are first quantized into scaled integer pixel values (and thus throwing away much of the noise) before being compressed with the specified algorithm (either GZIP, RICE, or HCOMPRESS). This technique produces much higher compression factors than simply using the GZIP utility to externally compress the whole FITS file, but it also means that the original floating point value pixel values are not exactly perserved. When done properly, this integer scaling technique will only discard the insignificant noise while still preserving all the real imformation in the image. The amount of precision that is retained in the pixel values is controlled by the quantizeLevel parameter. Larger values will result in compressed images whose pixels more closely match the floating point pixel values, but at the same time the amount of compression that is achieved will be reduced. Users should experiment with different values for this parameter to determine the optimal value that preserves all the useful information in the image, without needlessly preserving all the ‘noise’ which will hurt the compression efficiency.

The default value for the quantizeLevel scale factor is 16, which means that scaled integer pixel values will be quantized such that the difference between adjacent integer values will be 1/16th of the noise level in the image background. An optimized algorithm is used to accurately estimate the noise in the image. As an example, if the RMS noise in the background pixels of an image = 32.0, then the spacing between adjacent scaled integer pixel values will equal 2.0 by default. Note that the RMS noise is independently calculated for each tile of the image, so the resulting integer scaling factor may fluctuate slightly for each tile. In some cases, it may be desireable to specify the exact quantization level to be used, instead of specifying it relative to the calculated noise value. This may be done by specifying the negative of desired quantization level for the value of quantizeLevel. In the previous example, one could specify quantizeLevel`=-2.0 so that the quantized integer levels differ by 2.0. Larger negative values for `quantizeLevel means that the levels are more coarsely-spaced, and will produce higher compression factors.

scale(type=None, option='old', bscale=1, bzero=0)

Scale image data by using BSCALE and BZERO.

Calling this method will scale self.data and update the keywords of BSCALE and BZERO in self._header and self._imageHeader. This method should only be used right before writing to the output file, as the data will be scaled and is therefore not very usable after the call.

Parameters :
 

type : str, optional

destination data type, use a string representing a numpy dtype name, (e.g. 'uint8', 'int16', 'float32' etc.). If is None, use the current data type.

option : str, optional

how to scale the data: if "old", use the original BSCALE and BZERO values when the data was read/created. If "minmax", use the minimum and maximum of the data to scale. The option will be overwritten by any user-specified bscale/bzero values.

bscale, bzero : int, optional

user specified BSCALE and BZERO values.

updateCompressedData()

Compress the image data so that it may be written to a file.

updateHeader()

Update the table header cards to match the compressed data.

updateHeaderData(imageHeader, name=None, compressionType=None, tileSize=None, hcompScale=None, hcompSmooth=None, quantizeLevel=None)

Update the table header (_header) to the compressed image format and to match the input data (if any). Create the image header (_imageHeader) from the input image header (if any) and ensure it matches the input data. Create the initially-empty table data array to hold the compressed data.

This method is mainly called internally, but a user may wish to call this method after assigning new data to the CompImageHDU object that is of a different type.

Parameters :
 

imageHeader : Header instance

header to be associated with the image

name : str, optional

the EXTNAME value; if this value is None, then the name from the input image header will be used; if there is no name in the input image header then the default name ‘COMPRESSED_IMAGE’ is used

compressionType : str, optional

compression algorithm ‘RICE_1’, ‘PLIO_1’, ‘GZIP_1’, ‘HCOMPRESS_1’; if this value is None, use value already in the header; if no value already in the header, use ‘RICE_1’

tileSize : sequence of int, optional

compression tile sizes as a list; if this value is None, use value already in the header; if no value already in the header, treat each row of image as a tile

hcompScale : float, optional

HCOMPRESS scale parameter; if this value is None, use the value already in the header; if no value already in the header, use 1

hcompSmooth : float, optional

HCOMPRESS smooth parameter; if this value is None, use the value already in the header; if no value already in the header, use 0

quantizeLevel : float, optional

floating point quantization level; if this value is None, use the value already in the header; if no value already in header, use 16

class pytools.stpyfits.Header(cards=[], txtfile=None)

FITS header class.

The purpose of this class is to present the header like a dictionary as opposed to a list of cards.

The attribute ascard supplies the header like a list of cards.

The header class uses the card’s keyword as the dictionary key and the cards value is the dictionary value.

The has_key, get, and keys methods are implemented to provide the corresponding dictionary functionality. The header may be indexed by keyword value and like a dictionary, the associated value will be returned. When the header contains cards with duplicate keywords, only the value of the first card with the given keyword will be returned.

The header may also be indexed by card list index number. In that case, the value of the card at the given index in the card list will be returned.

A delete method has been implemented to allow deletion from the header. When del is called, all cards with the given keyword are deleted from the header.

The Header class has an associated iterator class _Header_iter which will allow iteration over the unique keywords in the header dictionary.

Construct a Header from a CardList and/or text file.

Parameters :
 

cards : A list of Card objects, optional

The cards to initialize the header with.

txtfile : file path, file object or file-like object, optional

Input ASCII header parameters file.

add_blank(value='', before=None, after=None)

Add a blank card.

Parameters :
 

value : str, optional

text to be added.

before : str or int, optional

same as in Header.update

after : str or int, optional

same as in Header.update

add_comment(value, before=None, after=None)

Add a COMMENT card.

Parameters :
 

value : str

text to be added.

before : str or int, optional

same as in Header.update

after : str or int, optional

same as in Header.update

add_history(value, before=None, after=None)

Add a HISTORY card.

Parameters :
 

value : str

history text to be added.

before : str or int, optional

same as in Header.update

after : str or int, optional

same as in Header.update

ascardlist()

Returns a CardList object.

copy()

Make a copy of the Header.

fromTxtFile(inFile, replace=False)

Input the header parameters from an ASCII file.

The input header cards will be used to update the current header. Therefore, when an input card key matches a card key that already exists in the header, that card will be updated in place. Any input cards that do not already exist in the header will be added. Cards will not be deleted from the header.

Parameters :
 

inFile : file path, file object or file-like object

Input header parameters file.

replace : bool, optional

When True, indicates that the entire header should be replaced with the contents of the ASCII file instead of just updating the current header.

get(key, default=None)

Get a keyword value from the CardList. If no keyword is found, return the default value.

Parameters :
 

key : str or int

keyword name or index

default : object, optional

if no keyword is found, the value to be returned.

get_comment()

Get all comment cards as a list of string texts.

get_history()

Get all history cards as a list of string texts.

has_key(key)

Check for existence of a keyword.

Parameters :
 

key : str or int

Keyword name. If given an index, always returns 0.

Returns :
 

has_key : bool

Returns True if found, otherwise, False.

items()

Return a list of all keyword-value pairs from the CardList.

keys()

Return a list of keys with duplicates removed.

rename_key(oldkey, newkey, force=0)

Rename a card’s keyword in the header.

Parameters :
 

oldkey : str or int

old keyword

newkey : str

new keyword

force : bool

When True, if new key name already exists, force to have duplicate name.

toTxtFile(outFile, clobber=False)

Output the header parameters to a file in ASCII format.

Parameters :
 

outFile : file path, file object or file-like object

Output header parameters file.

clobber : bool

When True, overwrite the output file if it exists.

update(key, value, comment=None, before=None, after=None, savecomment=False)

Update one header card.

If the keyword already exists, it’s value and/or comment will be updated. If it does not exist, a new card will be created and it will be placed before or after the specified location. If no before or after is specified, it will be appended at the end.

Parameters :
 

key : str

keyword

value : str

value to be used for updating

comment : str, optional

to be used for updating, default=None.

before : str or int, optional

name of the keyword, or index of the Card before which the new card will be placed. The argument before takes precedence over after if both specified.

after : str or int, optional

name of the keyword, or index of the Card after which the new card will be placed.

savecomment : bool, optional

When True, preserve the current comment for an existing keyword. The argument savecomment takes precedence over comment if both specified. If comment is not specified then the current comment will automatically be preserved.

class pytools.stpyfits.Undefined

Undefined value.

class pytools.stpyfits.RecordValuedKeywordCard(key='', value='', comment='')

Bases: pyfits.core.Card

Class to manage record-valued keyword cards as described in the FITS WCS Paper IV proposal for representing a more general distortion model.

Record-valued keyword cards are string-valued cards where the string is interpreted as a definition giving a record field name, and its floating point value. In a FITS header they have the following syntax:

keyword = 'field-specifier: float'

where keyword is a standard eight-character FITS keyword name, float is the standard FITS ASCII representation of a floating point number, and these are separated by a colon followed by a single blank. The grammar for field-specifier is:

field-specifier:
    field
    field-specifier.field

field:
    identifier
    identifier.index

where identifier is a sequence of letters (upper or lower case), underscores, and digits of which the first character must not be a digit, and index is a sequence of digits. No blank characters may occur in the field-specifier. The index is provided primarily for defining array elements though it need not be used for that purpose.

Multiple record-valued keywords of the same name but differing values may be present in a FITS header. The field-specifier may be viewed as part of the keyword name.

Some examples follow:

DP1     = 'NAXIS: 2'
DP1     = 'AXIS.1: 1'
DP1     = 'AXIS.2: 2'
DP1     = 'NAUX: 2'
DP1     = 'AUX.1.COEFF.0: 0'
DP1     = 'AUX.1.POWER.0: 1'
DP1     = 'AUX.1.COEFF.1: 0.00048828125'
DP1     = 'AUX.1.POWER.1: 1'
Parameters :
 

key : str, optional

The key, either the simple key or one that contains a field-specifier

value : str, optional

The value, either a simple value or one that contains a field-specifier

comment : str, optional

The comment

classmethod coerce(card)

Coerces an input Card object to a RecordValuedKeywordCard object if the value of the card meets the requirements of this type of card.

Parameters :
 

card : Card object

A Card object to coerce

Returns :
 

card :

  • If the input card is coercible:

    a new RecordValuedKeywordCard constructed from the key, value, and comment of the input card.

  • If the input card is not coercible:

    the input card

classmethod createCard(key='', value='', comment='')

Create a card given the input key, value, and comment. If the input key and value qualify for a RecordValuedKeywordCard then that is the object created. Otherwise, a standard Card object is created.

Parameters :
 

key : str, optional

The key

value : str, optional

The value

comment : str, optional

The comment

Returns :
 

card :

Either a RecordValuedKeywordCard or a Card object.

classmethod createCardFromString(input)

Create a card given the input string. If the input string can be parsed into a key and value that qualify for a RecordValuedKeywordCard then that is the object created. Otherwise, a standard Card object is created.

Parameters :
 

input : str

The string representing the card

Returns :
 

card :

either a RecordValuedKeywordCard or a Card object

strvalue()

Method to extract the field specifier and value from the card image. This is what is reported to the user when requesting the value of the Card using either an integer index or the card key without any field specifier.

classmethod upperKey(key)

classmethod to convert a keyword value that may contain a field-specifier to uppercase. The effect is to raise the key to uppercase and leave the field specifier in its original case.

Parameters :
 

key : int or str

A keyword value that could be an integer, a key, or a key.field-specifier value

Returns :
 

Integer input :

the original integer key

String input :

the converted string

classmethod validKeyValue(key, value=0)

Determine if the input key and value can be used to form a valid RecordValuedKeywordCard object. The key parameter may contain the key only or both the key and field-specifier. The value may be the value only or the field-specifier and the value together. The value parameter is optional, in which case the key parameter must contain both the key and the field specifier.

Parameters :
 

key : str

The key to parse

value : str or float-like, optional

The value to parse

Returns :
 

valid input : A list containing the key, field-specifier, value

invalid input : An empty list

Examples

>>> validKeyValue('DP1','AXIS.1: 2')
>>> validKeyValue('DP1.AXIS.1', 2)
>>> validKeyValue('DP1.AXIS.1')
class pytools.stpyfits.Delayed(hdu=None, field=None)

Delayed file-reading data.

class pytools.stpyfits.Column(name=None, format=None, unit=None, null=None, bscale=None, bzero=None, disp=None, start=None, dim=None, array=None)

Class which contains the definition of one column, e.g. ttype, tform, etc. and the array containing values for the column. Does not support theap yet.

Construct a Column by specifying attributes. All attributes except format can be optional.

Parameters :
 

name : str, optional

column name, corresponding to TTYPE keyword

format : str, optional

column format, corresponding to TFORM keyword

unit : str, optional

column unit, corresponding to TUNIT keyword

null : str, optional

null value, corresponding to TNULL keyword

bscale : int-like, optional

bscale value, corresponding to TSCAL keyword

bzero : int-like, optional

bzero value, corresponding to TZERO keyword

disp : str, optional

display format, corresponding to TDISP keyword

start : int, optional

column starting position (ASCII table only), corresponding to TBCOL keyword

dim : str, optional

column dimension corresponding to TDIM keyword

copy()

Return a copy of this Column.

class pytools.stpyfits.Card(key='', value='', comment='')

Bases: pyfits.core._Verify

Construct a card from key, value, and (optionally) comment. Any specifed arguments, except defaults, must be compliant to FITS standard.

Parameters :
 

key : str, optional

keyword name

value : str, optional

keyword value

comment : str, optional

comment

ascardimage(option='silentfix')

Generate a (new) card image from the attributes: key, value, and comment, or from raw string.

Parameters :
 

option : str

Output verification option. Must be one of "fix", "silentfix", "ignore", "warn", or "exception". See verify for more info.

fromstring(input)

Construct a Card object from a (raw) string. It will pad the string if it is not the length of a card image (80 columns). If the card image is longer than 80 columns, assume it contains CONTINUE card(s).

class pytools.stpyfits.ErrorURLopener(*args, **kwargs)

Bases: urllib.FancyURLopener

A class to use with urlretrieve to allow IOError exceptions to be raised when a file specified by a URL cannot be accessed.

http_error_default(url, fp, errcode, errmsg, headers)
class pytools.stpyfits.CardList(cards=[], keylist=None)

Bases: list

FITS header card list class.

Construct the CardList object from a list of Card objects.

Parameters :
 

cards :

A list of Card objects.

append(card, useblanks=True, bottom=False)

Append a Card to the CardList.

Parameters :
 

card : Card object

The Card to be appended.

useblanks : bool, optional

Use any extra blank cards?

If useblanks is True, and if there are blank cards directly before END, it will use this space first, instead of appending after these blank cards, so the total space will not increase. When useblanks is False, the card will be appended at the end, even if there are blank cards in front of END.

bottom : bool, optional

If False the card will be appended after the last non-commentary card. If True the card will be appended after the last non-blank card.

copy()

Make a (deep)copy of the CardList.

count_blanks()

Returns how many blank cards are directly before the END card.

filterList(key)

Construct a CardList that contains references to all of the cards in this CardList that match the input key value including any special filter keys (*, ?, and ...).

Parameters :
 

key : str

key value to filter the list with

Returns :
 

cardlist : :

A CardList object containing references to all the requested cards.

index_of(key, backward=False)

Get the index of a keyword in the CardList.

Parameters :
 

key : str or int

The keyword name (a string) or the index (an integer).

backward : bool, optional

When True, search the index from the END, i.e., backward.

Returns :
 

index : int

The index of the Card with the given keyword.

insert(pos, card, useblanks=True)

Insert a Card to the CardList.

Parameters :
 

pos : int

The position (index, keyword name will not be allowed) to insert. The new card will be inserted before it.

card : Card object

The card to be inserted.

useblanks : bool, optional

If useblanks is True, and if there are blank cards directly before END, it will use this space first, instead of appending after these blank cards, so the total space will not increase. When useblanks is False, the card will be appended at the end, even if there are blank cards in front of END.

keys()

Return a list of all keywords from the CardList.

Keywords include field_specifier for RecordValuedKeywordCard objects.

values()

Return a list of the values of all cards in the CardList.

For RecordValuedKeywordCard objects, the value returned is the floating point value, exclusive of the field_specifier.

class pytools.stpyfits.FITS_record(input, row=0, startColumn=0, endColumn=0)

Bases: object

FITS record class.

FITS_record is used to access records of the FITS_rec object. This will allow us to deal with scaled columns. The FITS_record class expects a FITS_rec object as input.

Parameters :
 

input : array

The array to wrap.

row : int, optional

The starting logical row of the array.

startColumn : int, optional

The starting column in the row associated with this object. Used for subsetting the columns of the FITS_rec object.

endColumn : int, optional

The ending column in the row associated with this object. Used for subsetting the columns of the FITS_rec object.

field(fieldName)

Get the field data of the record.

setfield(fieldName, value)

Set the field data of the record.

class pytools.stpyfits.BinTableHDU(data=None, header=None, name=None)

Bases: pyfits.core._TableBaseHDU

Binary table HDU class.

Parameters :
 

data : array

data of the table

header : Header instance

header to be used for the HDU

name : str

the EXTNAME value

tcreate(datafile, cdfile=None, hfile=None, replace=False)

Create a table from the input ASCII files. The input is from up to three separate files, one containing column definitions, one containing header parameters, and one containing column data. The column definition and header parameters files are not required. When absent the column definitions and/or header parameters are taken from the current values in this HDU.

Parameters :
 

datafile : file path, file object or file-like object

Input data file containing the table data in ASCII format.

cdfile : file path, file object, file-like object, optional

Input column definition file containing the names, formats, display formats, physical units, multidimensional array dimensions, undefined values, scale factors, and offsets associated with the columns in the table. If None, the column definitions are taken from the current values in this object.

hfile : file path, file object, file-like object, optional

Input parameter definition file containing the header parameter definitions to be associated with the table. If None, the header parameter definitions are taken from the current values in this objects header.

replace : bool

When True, indicates that the entire header should be replaced with the contents of the ASCII file instead of just updating the current header.

Notes

The primary use for the tcreate method is to allow the input of ASCII data that was edited in a standard text editor of the table data and parameters. The tdump method can be used to create the initial ASCII files.

  • datafile: Each line of the data file represents one row of table data. The data is output one column at a time in column order. If a column contains an array, each element of the column array in the current row is output before moving on to the next column. Each row ends with a new line.

    Integer data is output right-justified in a 21-character field followed by a blank. Floating point data is output right justified using ‘g’ format in a 21-character field with 15 digits of precision, followed by a blank. String data that does not contain whitespace is output left-justified in a field whose width matches the width specified in the TFORM header parameter for the column, followed by a blank. When the string data contains whitespace characters, the string is enclosed in quotation marks (""). For the last data element in a row, the trailing blank in the field is replaced by a new line character.

    For column data containing variable length arrays (‘P’ format), the array data is preceded by the string 'VLA_Length= ' and the integer length of the array for that row, left-justified in a 21-character field, followed by a blank.

    For column data representing a bit field (‘X’ format), each bit value in the field is output right-justified in a 21-character field as 1 (for true) or 0 (for false).

  • cdfile: Each line of the column definitions file provides the definitions for one column in the table. The line is broken up into 8, sixteen-character fields. The first field provides the column name (TTYPEn). The second field provides the column format (TFORMn). The third field provides the display format (TDISPn). The fourth field provides the physical units (TUNITn). The fifth field provides the dimensions for a multidimensional array (TDIMn). The sixth field provides the value that signifies an undefined value (TNULLn). The seventh field provides the scale factor (TSCALn). The eighth field provides the offset value (TZEROn). A field value of "" is used to represent the case where no value is provided.

  • hfile: Each line of the header parameters file provides the definition of a single HDU header card as represented by the card image.

tdump(datafile=None, cdfile=None, hfile=None, clobber=False)

Dump the table HDU to a file in ASCII format. The table may be dumped in three separate files, one containing column definitions, one containing header parameters, and one for table data.

Parameters :
 

datafile : file path, file object or file-like object, optional

Output data file. The default is the root name of the fits file associated with this HDU appended with the extension .txt.

cdfile : file path, file object or file-like object, optional

Output column definitions file. The default is None, no column definitions output is produced.

hfile : file path, file object or file-like object, optional

Output header parameters file. The default is None, no header parameters output is produced.

clobber : bool

Overwrite the output files if they exist.

Notes

The primary use for the tdump method is to allow editing in a standard text editor of the table data and parameters. The tcreate method can be used to reassemble the table from the three ASCII files.

  • datafile: Each line of the data file represents one row of table data. The data is output one column at a time in column order. If a column contains an array, each element of the column array in the current row is output before moving on to the next column. Each row ends with a new line.

    Integer data is output right-justified in a 21-character field followed by a blank. Floating point data is output right justified using ‘g’ format in a 21-character field with 15 digits of precision, followed by a blank. String data that does not contain whitespace is output left-justified in a field whose width matches the width specified in the TFORM header parameter for the column, followed by a blank. When the string data contains whitespace characters, the string is enclosed in quotation marks (""). For the last data element in a row, the trailing blank in the field is replaced by a new line character.

    For column data containing variable length arrays (‘P’ format), the array data is preceded by the string 'VLA_Length= ' and the integer length of the array for that row, left-justified in a 21-character field, followed by a blank.

    For column data representing a bit field (‘X’ format), each bit value in the field is output right-justified in a 21-character field as 1 (for true) or 0 (for false).

  • cdfile: Each line of the column definitions file provides the definitions for one column in the table. The line is broken up into 8, sixteen-character fields. The first field provides the column name (TTYPEn). The second field provides the column format (TFORMn). The third field provides the display format (TDISPn). The fourth field provides the physical units (TUNITn). The fifth field provides the dimensions for a multidimensional array (TDIMn). The sixth field provides the value that signifies an undefined value (TNULLn). The seventh field provides the scale factor (TSCALn). The eighth field provides the offset value (TZEROn). A field value of "" is used to represent the case where no value is provided.

  • hfile: Each line of the header parameters file provides the definition of a single HDU header card as represented by the card image.

pytools.stpyfits.showwarning(message, category, filename, lineno, file=None, line=None)
pytools.stpyfits.createCard(key='', value='', comment='')

Create a card given the input key, value, and comment. If the input key and value qualify for a RecordValuedKeywordCard then that is the object created. Otherwise, a standard Card object is created.

Parameters :
 

key : str, optional

The key

value : str, optional

The value

comment : str, optional

The comment

Returns :
 

card :

Either a RecordValuedKeywordCard or a Card object.

pytools.stpyfits.append(filename, data, header=None, classExtensions={})

Append the header/data to FITS file if filename exists, create if not.

If only data is supplied, a minimal header is created.

Parameters :
 

filename : file path, file object, or file like object

File to write to. If opened, must be opened for update (rb+) unless it is a new file, then it must be opened for append (ab+). A file or GzipFile object opened for update will be closed after return.

data : array, table, or group data object

the new data used for appending

header : Header object, optional

The header associated with data. If None, an appropriate header will be created for the data object supplied.

classExtensions : dictionary, optional

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

checksum : bool, optional

When True adds both DATASUM and CHECKSUM cards to the header of the HDU when written to the file.

verify: bool, optional (True) :

When True, the existing FITS file will be read in to verify it for correctness before appending. When False, content is simply appended to the end of the file. Setting verify to False can be much faster.

pytools.stpyfits.getheader(filename, *ext, **extkeys)

Get the header from an extension of a FITS file.

Parameters :
 

filename : file path, file object, or file like object

File to get header from. If an opened file object, its mode must be one of the following rb, rb+, or ab+).

classExtensions : optional

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

ext :

The rest of the arguments are for extension specification. getdata for explanations/examples.

Returns :
 

header : Header object

pytools.stpyfits.upperKey(key)

classmethod to convert a keyword value that may contain a field-specifier to uppercase. The effect is to raise the key to uppercase and leave the field specifier in its original case.

Parameters :
 

key : int or str

A keyword value that could be an integer, a key, or a key.field-specifier value

Returns :
 

Integer input :

the original integer key

String input :

the converted string

pytools.stpyfits.tdump(fitsFile, datafile=None, cdfile=None, hfile=None, ext=1, clobber=False, classExtensions={})

Dump a table HDU to a file in ASCII format. The table may be dumped in three separate files, one containing column definitions, one containing header parameters, and one for table data.

Parameters :
 

fitsFile : file path, file object or file-like object

Input fits file.

datafile : file path, file object or file-like object, optional

Output data file. The default is the root name of the input fits file appended with an underscore, followed by the extension number (ext), followed by the extension .txt.

cdfile : file path, file object or file-like object, optional

Output column definitions file. The default is None, no column definitions output is produced.

hfile : file path, file object or file-like object, optional

Output header parameters file. The default is None, no header parameters output is produced.

ext : int

The number of the extension containing the table HDU to be dumped.

clobber : bool

Overwrite the output files if they exist.

classExtensions : dict

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

Notes

The primary use for the tdump function is to allow editing in a standard text editor of the table data and parameters. The tcreate function can be used to reassemble the table from the three ASCII files.

  • datafile: Each line of the data file represents one row of table data. The data is output one column at a time in column order. If a column contains an array, each element of the column array in the current row is output before moving on to the next column. Each row ends with a new line.

    Integer data is output right-justified in a 21-character field followed by a blank. Floating point data is output right justified using ‘g’ format in a 21-character field with 15 digits of precision, followed by a blank. String data that does not contain whitespace is output left-justified in a field whose width matches the width specified in the TFORM header parameter for the column, followed by a blank. When the string data contains whitespace characters, the string is enclosed in quotation marks (""). For the last data element in a row, the trailing blank in the field is replaced by a new line character.

    For column data containing variable length arrays (‘P’ format), the array data is preceded by the string 'VLA_Length= ' and the integer length of the array for that row, left-justified in a 21-character field, followed by a blank.

    For column data representing a bit field (‘X’ format), each bit value in the field is output right-justified in a 21-character field as 1 (for true) or 0 (for false).

  • cdfile: Each line of the column definitions file provides the definitions for one column in the table. The line is broken up into 8, sixteen-character fields. The first field provides the column name (TTYPEn). The second field provides the column format (TFORMn). The third field provides the display format (TDISPn). The fourth field provides the physical units (TUNITn). The fifth field provides the dimensions for a multidimensional array (TDIMn). The sixth field provides the value that signifies an undefined value (TNULLn). The seventh field provides the scale factor (TSCALn). The eighth field provides the offset value (TZEROn). A field value of "" is used to represent the case where no value is provided.

  • hfile: Each line of the header parameters file provides the definition of a single HDU header card as represented by the card image.

pytools.stpyfits.writeto(filename, data, header=None, **keys)

Create a new FITS file using the supplied data/header.

Parameters :
 

filename : file path, file object, or file like object

File to write to. If opened, must be opened for append (ab+).

data : array, record array, or groups data object

data to write to the new file

header : Header object, optional

the header associated with data. If None, a header of the appropriate type is created for the supplied data. This argument is optional.

classExtensions : dict, optional

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

clobber : bool, optional

If True, and if filename already exists, it will overwrite the file. Default is False.

checksum : bool, optional

If True, adds both DATASUM and CHECKSUM cards to the headers of all HDU’s written to the file.

pytools.stpyfits.getval(filename, key, *ext, **extkeys)

Get a keyword’s value from a header in a FITS file.

Parameters :
 

filename : file path, file object, or file like object

Name of the FITS file, or file object (if opened, mode must be one of the following rb, rb+, or ab+).

key : str

keyword name

classExtensions : (optional)

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

ext :

The rest of the arguments are for extension specification. See getdata for explanations/examples.

Returns :
 

keyword value : string, integer, or float

pytools.stpyfits.fitsopen(name, mode='copyonwrite', memmap=0, classExtensions={}, **parms)

Factory function to open a FITS file and return an HDUList object.

Parameters :
 

name : file path, file object or file-like object

File to be opened.

mode : str

Open mode, ‘copyonwrite’ (default), ‘readonly’, ‘update’, ‘append’, or ‘ostream’.

If name is a file object that is already opened, mode must match the mode the file was opened with, copyonwrite (rb), readonly (rb), update (rb+), append (ab+), ostream (w)).

memmap : bool

Is memory mapping to be used?

classExtensions : dict

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

parms : dict

optional keyword arguments, possible values are:

  • uint : bool

    Interpret signed integer data where BZERO is the central value and BSCALE == 1 as unsigned integer data. For example, int16 data with BZERO = 32768 and BSCALE = 1 would be treated as uint16 data.

    Note, for backward compatibility, the kwarg uint16 may be used instead. The kwarg was renamed when support was added for integers of any size.

  • ignore_missing_end : bool

    Do not issue an exception when opening a file that is missing an END card in the last header.

  • checksum : bool

    If True, verifies that both DATASUM and CHECKSUM card values (when present in the HDU header) match the header and data of all HDU’s in the file.

  • disable_image_compression : bool

    If True, treates compressed image HDU’s like normal binary table HDU’s.

  • do_not_scale_image_data : bool

    If True, image data is not scaled using BSCALE/BZERO values when read.

Returns :
 

hdulist : an HDUList object

HDUList containing all of the header data units in the file.

pytools.stpyfits.getdata(filename, *ext, **extkeys)

Get the data from an extension of a FITS file (and optionally the header).

Parameters :
 

filename : file path, file object, or file like object

File to get data from. If opened, mode must be one of the following rb, rb+, or ab+.

classExtensions : dict, optional

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

ext :

The rest of the arguments are for extension specification. They are flexible and are best illustrated by examples.

No extra arguments implies the primary header:

>>> getdata('in.fits')

By extension number:

>>> getdata('in.fits', 0)    # the primary header
>>> getdata('in.fits', 2)    # the second extension
>>> getdata('in.fits', ext=2) # the second extension

By name, i.e., EXTNAME value (if unique):

>>> getdata('in.fits', 'sci')
>>> getdata('in.fits', extname='sci') # equivalent

Note EXTNAME values are not case sensitive

By combination of EXTNAME and EXTVER`` as separate arguments or as a tuple:

>>> getdata('in.fits', 'sci', 2) # EXTNAME='SCI' & EXTVER=2
>>> getdata('in.fits', extname='sci', extver=2) # equivalent
>>> getdata('in.fits', ('sci', 2)) # equivalent

Ambiguous or conflicting specifications will raise an exception:

>>> getdata('in.fits', ext=('sci',1), extname='err', extver=2)

lower, upper : bool, optional

If lower or upper are True, the field names in the returned data object will be converted to lower or upper case, respectively.

view : ndarray view class, optional

When given, the data will be turned wrapped in the given view class, by calling:

data.view(view)
Returns :
 

array : array, record array or groups data object

Type depends on the type of the extension being referenced.

If the optional keyword header is set to True, this function will return a (data, header) tuple.

pytools.stpyfits.info(filename, classExtensions={}, **parms)

Print the summary information on a FITS file.

This includes the name, type, length of header, data shape and type for each extension.

Parameters :
 

filename : file path, file object, or file like object

FITS file to obtain info from. If opened, mode must be one of the following: rb, rb+, or ab+.

classExtensions : dict, optional

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

parms : optional keyword arguments

  • uint : bool

    Interpret signed integer data where BZERO is the central value and BSCALE == 1 as unsigned integer data. For example, int16 data with BZERO = 32768 and BSCALE = 1 would be treated as uint16 data.

    Note, for backward compatibility, the kwarg uint16 may be used instead. The kwarg was renamed when support was added for integers of any size.

  • ignore_missing_end : bool

    Do not issue an exception when opening a file that is missing an END card in the last header. Default is True.

pytools.stpyfits.createCardFromString(input)

Create a card given the input string. If the input string can be parsed into a key and value that qualify for a RecordValuedKeywordCard then that is the object created. Otherwise, a standard Card object is created.

Parameters :
 

input : str

The string representing the card

Returns :
 

card :

either a RecordValuedKeywordCard or a Card object

pytools.stpyfits.new_table(input, header=None, nrows=0, fill=False, tbtype='BinTableHDU')

Create a new table from the input column definitions.

Parameters :
 

input : sequence of Column or ColDefs objects

The data to create a table from.

header : Header instance

Header to be used to populate the non-required keywords.

nrows : int

Number of rows in the new table.

fill : bool

If True, will fill all cells with zeros or blanks. If False, copy the data from input, undefined cells will still be filled with zeros/blanks.

tbtype : str

Table type to be created (“BinTableHDU” or “TableHDU”).

pytools.stpyfits.setExtensionNameCaseSensitive(value=True)
pytools.stpyfits.setval(filename, key, value='', comment=None, before=None, after=None, savecomment=False, *ext, **extkeys)

Set a keyword’s value from a header in a FITS file.

If the keyword already exists, it’s value/comment will be updated. If it does not exist, a new card will be created and it will be placed before or after the specified location. If no before or after is specified, it will be appended at the end.

When updating more than one keyword in a file, this convenience function is a much less efficient approach compared with opening the file for update, modifying the header, and closing the file.

Parameters :
 

filename : file path, file object, or file like object

Name of the FITS file, or file object If opened, mode must be update (rb+). An opened file object or GzipFile object will be closed upon return.

key : str

keyword name

value : str, int, float

Keyword value, default = “”

comment : str

Keyword comment, default = None

before : str, int

name of the keyword, or index of the Card before which the new card will be placed. The argument before takes precedence over after if both specified. default=`None`.

after : str, int

name of the keyword, or index of the Card after which the new card will be placed. default=`None`.

savecomment : bool

when True, preserve the current comment for an existing keyword. The argument savecomment takes precedence over comment if both specified. If comment is not specified then the current comment will automatically be preserved. default=`False`

classExtensions : dict, optional

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

ext :

The rest of the arguments are for extension specification. See getdata for explanations/examples.

pytools.stpyfits.tcreate(datafile, cdfile, hfile=None)

Create a table from the input ASCII files. The input is from up to three separate files, one containing column definitions, one containing header parameters, and one containing column data. The header parameters file is not required. When the header parameters file is absent a minimal header is constructed.

Parameters :
 

datafile : file path, file object or file-like object

Input data file containing the table data in ASCII format.

cdfile : file path, file object or file-like object

Input column definition file containing the names, formats, display formats, physical units, multidimensional array dimensions, undefined values, scale factors, and offsets associated with the columns in the table.

hfile : file path, file object or file-like object, optional

Input parameter definition file containing the header parameter definitions to be associated with the table. If None, a minimal header is constructed.

Notes

The primary use for the tcreate function is to allow the input of ASCII data that was edited in a standard text editor of the table data and parameters. The tdump function can be used to create the initial ASCII files.

  • datafile: Each line of the data file represents one row of table data. The data is output one column at a time in column order. If a column contains an array, each element of the column array in the current row is output before moving on to the next column. Each row ends with a new line.

    Integer data is output right-justified in a 21-character field followed by a blank. Floating point data is output right justified using ‘g’ format in a 21-character field with 15 digits of precision, followed by a blank. String data that does not contain whitespace is output left-justified in a field whose width matches the width specified in the TFORM header parameter for the column, followed by a blank. When the string data contains whitespace characters, the string is enclosed in quotation marks (""). For the last data element in a row, the trailing blank in the field is replaced by a new line character.

    For column data containing variable length arrays (‘P’ format), the array data is preceded by the string 'VLA_Length= ' and the integer length of the array for that row, left-justified in a 21-character field, followed by a blank.

    For column data representing a bit field (‘X’ format), each bit value in the field is output right-justified in a 21-character field as 1 (for true) or 0 (for false).

  • cdfile: Each line of the column definitions file provides the definitions for one column in the table. The line is broken up into 8, sixteen-character fields. The first field provides the column name (TTYPEn). The second field provides the column format (TFORMn). The third field provides the display format (TDISPn). The fourth field provides the physical units (TUNITn). The fifth field provides the dimensions for a multidimensional array (TDIMn). The sixth field provides the value that signifies an undefined value (TNULLn). The seventh field provides the scale factor (TSCALn). The eighth field provides the offset value (TZEROn). A field value of "" is used to represent the case where no value is provided.

  • hfile: Each line of the header parameters file provides the definition of a single HDU header card as represented by the card image.

pytools.stpyfits.update(filename, data, *ext, **extkeys)

Update the specified extension with the input data/header.

Parameters :
 

filename : file path, file object, or file like object

File to update. If opened, mode must be update (rb+). An opened file object or GzipFile object will be closed upon return.

data : array, table, or group data object

the new data used for updating

classExtensions : dict, optional

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

ext :

The rest of the arguments are flexible: the 3rd argument can be the header associated with the data. If the 3rd argument is not a Header, it (and other positional arguments) are assumed to be the extension specification(s). Header and extension specs can also be keyword arguments. For example:

>>> update(file, dat, hdr, 'sci')  # update the 'sci' extension
>>> update(file, dat, 3)  # update the 3rd extension
>>> update(file, dat, hdr, 3)  # update the 3rd extension
>>> update(file, dat, 'sci', 2)  # update the 2nd SCI extension
>>> update(file, dat, 3, header=hdr)  # update the 3rd extension
>>> update(file, dat, header=hdr, ext=5)  # update the 5th extension
pytools.stpyfits.delval(filename, key, *ext, **extkeys)

Delete all instances of keyword from a header in a FITS file.

Parameters :
 

filename : file path, file object, or file like object

Name of the FITS file, or file object If opened, mode must be update (rb+). An opened file object or GzipFile object will be closed upon return.

key : str, int

Keyword name or index

classExtensions : optional

A dictionary that maps pyfits classes to extensions of those classes. When present in the dictionary, the extension class will be constructed in place of the pyfits class.

ext :

The rest of the arguments are for extension specification. See getdata for explanations/examples.

pytools.stpyfits.formatwarning(message, category, filename, lineno, line=None)