# astro.util.darma package¶

## Submodules¶

A bitmask to store flagged pixel information.

class astro.util.darma.bitmask.bitmask(filename=None, extension=0, datatype=None, pmap=None, bit=None, data=None, conserve=False, readonly=0, memmap=1, *args, **kwargs)

A bit mask in which to store up to 32 types of pixelmaps.

add_bitmask(bmask)

add_pixelmap(pmap, bit)

Merge a pixelmap into this bitmask.

pmap: a pixelmap object to create bitmask from
bit: the bit to set for this pixelmap
as_eclipse_pixelmap(mask=None)

Export this bitmask as a proper Eclipse pixelmap.

If mask is None, a logical-OR of all masks is returned, else a pixelmap of the specified mask is returned.

as_pixelmap(mask=None)

Export this bitmask as a pixelmap.

If mask is None, a logical-OR of all masks is returned, else a pixelmap of the specified mask is returned.

bits

number of bits per pixel of the current datatype

count()

Return the number of flagged pixels (non-zero values) in the bitmask.

del_bitmask(bmask)

del_pixelmap(pmap, bit)

Remove a pixelmap from this bitmask.

pmap: a pixelmap object to create bitmask from
bit: the bit of the pixelmap to remove
dtype

a representation of datatype

has_bit(bit=None)

Check this bitmask for a specific bit.

If bit is None, the result of a logical-OR of all masks is returned, else the existence (are any pixels set) of the specified mask is returned.

bit: the bit to test for

load()

THIS SHOULD ONLY BE CALLED BY THE ‘getter’ METHOD.

load_bitmask()

save(filename=None, hdr=None, datatype='int32', clobber=True, update_datamd5=True, option='silentfix')

Save the data to a file.

filename: name of the file (str)

datatype: type of data output to the FITS file

option: option used to verify the output (from PyFITS)
should be one of fix, silentfix, ignore, warn, or exception
which_bits()

Return a list of the bits set in this bitmask.

## astro.util.darma.common module¶

Auxiliary data structures and constants.

exception astro.util.darma.common.DARMAError

Bases: Exception

class astro.util.darma.common.DataStruct(*args, **kwargs)

Bases: object

Abstract base class for image and pixelmap classes containing common methods (mainly arithmetic).

astype(datatype='float32')

Return with the data converted to an arbitrary Array datatype (uint8, float32, etc.).

datatype: Array data type

bin(xbin=2, ybin=2, datatype=None, old=False)

Return with a binned version of the data. Negative binning factors are allowed. If a negative binning factor is used, this has the effect of reversing the axis.

xbin: X-axis binning factor (int) ybin: Y-axis binning factor (int)
datatype: use an alternate datatype for the binning (e.g., to
reduce rounding error)

old: use older, much slower binning algorithm

Note: If the binning factor is not a factor of the length of the

axis, the last axis_len % Nbin elements of the data will be truncated (e.g., a 49x49 pixel image binned 2x2 will be a 24x24 pixel image where where the last column and row of data are eliminated).

Also, if the datatype is not sufficient to handle the binned data dynamic range, it will be truncated.

copy(datatype=None)

Copy the data to a new object.

datatype: return a copy of the specified datatype

data

Attribute to store the data

datatype
display(viewer='skycat', filename=None)

Display this image in an external viewer, saved to filename if filename is not None.

NOTE: The image being saved here is saved to a temporary file in a
temporary directory without a proper header and will be deleted once viewed. To save the file properly, use the save method.
extract_region(x0, y0, x1, y1)

Extract a sub-region from this image/pixelmap

x0, y0: lower lefthand corner x1, y1: upper righthand corner

These coordinates follow FITS coordinates. Hence the x0, y0 = 1,1 is equivalent to the lower left corner of the input image, and the dimension of the resulting image will be (x1-x0)+1 x (y1-y0)+1

flip()

Return a copy with the Y-axis flipped (top to bottom).

flop()

Return a copy with the X-axis flipped (left to right).

get_bitmask()

Return the bitmask for this object if it exists

has_bitmask()

Determine if a bitmask exists for this object and is set.

info()

Show general information on this image/pixelmap.

itemsize

Return the item size (in bytes) of self.data.

load()

Abstract load method. All sub-classes should call their load_…() method from this method.

THIS SHOULD ONLY BE CALLED BY THE ‘getter’ METHOD.

log(msg, level='normal')

Print a log statement

msg: message to print

level: level of log entry (‘normal’, ‘verbose’, ‘debug’)

reshape(shape)

Set the shape of the image’s data array to shape.

shape: a tuple giving the shape

The shape will generally be a tuple of the form (x,y) or (n,).

save(filename=None, hdr=None, datatype='float32', clobber=True, update_datamd5=True, option='silentfix')

Save the data to a file.

filename: name of the file (str)

datatype: type of data output to the FITS file

option: option used to verify the output (from PyFITS)
should be one of fix, silentfix, ignore, warn, or exception
set_val(value=0)

Set all elements of the data in this image to an arbitrary value.

value: any number construct (int, float, imag, nan, etc.)
set_zero()

Set all elements of the data in this image to zero.

shape
size

The total number of elements in the data array.

swapaxes()

Swap NAXIS1 and NAXIS2 inplace.

verbose = 0
xsize()

The length of the x-axis data.

ysize()

The length of the y-axis data.

class astro.util.darma.common.StatStruct(stat_tuple)

Bases: object

A class to hold image statistics.

Each instance has the following attributes min_pix: The minimum value max_pix: The maximum value avg_pix: The average value

median: The median value
stdev: The standard deviation
energy: The total energy
flux: The total flux
absflux: The total absolute flux

min_x: The x-coordinate of the minimum value min_y: The y-coordinate of the minimum value max_x: The x-coordinate of the maximum value max_y: The y-coordinate of the maximum value

npix: The total number of pixels
dump()

Synonym for show().

show()

Print out all statistics values.

astro.util.darma.common.add_blank(hdr, value, before=None, after=None)

value: value of the new blank card

before: keyword of the card before which the BLANK card will be
placed
after: keyword of the card after which the BLANK card will be
placed
astro.util.darma.common.clear_header(hdr)

Remove all card from the header.

astro.util.darma.common.datLoc(hdu)
astro.util.darma.common.datSpan(hdu)
astro.util.darma.common.fits_close(hdulist, output_verify='exception', verbose=False, closed=True, filename='', checksum=False)

Close the associated FITS file and memmap object, if any.

Optionally write a copy to overwrite the original. This is a work- around for some newer versions of PyFITS/Astropy that have a file corruption bug when updating the FITS file under certain circumstances.

hdulist : fits.HDUList
PyFITS/Astropy HDUList to close
output_verify : str
Output verification option. Must be one of "fix", "silentfix", "ignore", "warn", or "exception". May also be any combination of "fix" or "silentfix" with "+ignore", +warn, or +exception" (e.g. "fix+warn"). See verify for more info.
verbose : bool
When True, print out verbose messages.
closed : bool
When True, close the underlying file object.
filename : file path, file object or file-like object
File to write to. If a file object, must be opened in a writeable mode. When provided, a copy is first made, then this copy overwrites the original (implies clobber=True).
checksum : bool
When True adds both DATASUM and CHECKSUM cards to the headers of all HDU’s written to the file.
astro.util.darma.common.fits_open(name, mode='readonly', memmap=None, save_backup=False, cache=True, **kwargs)
Wrapper around fits.open() method to allow arbitrary extra arguments common to all open commands, e.g., ignore_missing_end.

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

name : file path, file object, file-like object or pathlib.Path object
File to be opened.
mode : str, optional

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

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

memmap : bool, optional
Is memory mapping to be used?
save_backup : bool, optional
If the file was opened in update or append mode, this ensures that a backup of the original file is saved before any changes are flushed. The backup has the same name as the original file with “.bak” appended. If “file.bak” already exists then “file.bak.1” is used, and so on.
cache : bool, optional
If the file name is a URL, ~astropy.utils.data.download_file is used to open the file. This specifies whether or not to save the file locally in Astropy’s download cache (default: True).
kwargs : dict, optional

additional 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. This is enabled by default so that the pseudo-unsigned integer convention is assumed.

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, str

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. Updates to a file that already has a checksum will preserve and update the existing checksums unless this argument is given a value of ‘remove’, in which case the CHECKSUM and DATASUM values are not checked, and are removed when saving changes to the file.

• disable_image_compression : bool

If True, treats 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.

• ignore_blank : bool

If True, the BLANK keyword is ignored if present.

• scale_back : bool

If True, when saving changes to a file that contained scaled image data, restore the data to the original type and reapply the original BSCALE/BZERO values. This could lead to loss of accuracy if scaling back to integer values after performing floating point operations on the data.

hdulist : an HDUList object
HDUList containing all of the header data units in the file.
astro.util.darma.common.fold_string(string, num=80, char='', newline='\n')

Fold the given string string at num characters if len(string) > num. If char is specified, prefer splitting after nearest previous occurrance of char. The newline character can also be specified.

string: any string to be split
num: number of characters to split at

char: prefer to split after specific character in string

newline: newline character

astro.util.darma.common.get_cardimage(card)

Return a fits.Card instance image

card: a fits.Card instance
astro.util.darma.common.get_cards(hdr)

Return the card list (dictionary-like object, actually) of a fits.Header instance.

astro.util.darma.common.get_coldefs(hdu)
astro.util.darma.common.get_comment(hdr)

Return a list of all COMMENT card contents

astro.util.darma.common.get_history(hdr)

Return a list of all HISTORY card contents

astro.util.darma.common.get_keyword(card)

Return the keyword of a fits.Card instance.

card: a fits.Card instance
astro.util.darma.common.get_number_of_extensions(name)

Obtain the number of extensions in a Multi-Extension FITS file.

astro.util.darma.common.get_tmpbase(suffix='', prefix='tmp', dir=None)

Return a basename for a temporary filename.

Loosely follows tempfile.mktemp syntax, but constructs a name based on the current time (seconds since 00:00:00 1970-01-01 UTC) with microsecond precision followed by a 6 character random string. This should virtually guarantee temp-name uniqueness. The returned string has the following form:

‘<dir>/<prefix><seconds.microseconds>.<random_string>.<suffix>’

If dir is not None, it will be supplied with a trailing ‘/’ if one is not given. If suffix is not ‘’, it will be preceeded by a ‘.’ if one is not given.

dir: pathname to prepend to file (None means the same as ‘’)
NOTE: If dir is given, it will be checked for, and an Exception raised
if it does not exist.
astro.util.darma.common.get_value(hdr, keyword, default=None)

Return the value of a keyword/index in a fits.Header instance

keyword: the keyword/index for which to get the value default: the value to return when the keyword/index is missing

astro.util.darma.common.getdata(filename, *args, **kwargs)

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

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+.
ext, extname, extver

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)

If True, return the data and the header of the specified HDU as a tuple.
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, optional

When given, the data will be returned wrapped in the given ndarray subclass by calling:

data.view(view)

kwargs
Any additional keyword arguments to be passed to fits.open.
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.

astro.util.darma.common.getheader(filename, *args, **kwargs)

Get the header from an extension of a FITS file.

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+).
ext, extname, extver
The rest of the arguments are for extension specification. See the getdata documentation for explanations/examples.
kwargs
Any additional keyword arguments to be passed to pyfits.open.

astro.util.darma.common.is_hierarch(card)

Return if a fits.Card instance is a HIERARCH card.

card: a fits.Card instance
class astro.util.darma.common.long

Bases: int

astro.util.darma.common.new_table(columns=[], hdr=None, nrows=0, fill=False, tbtype='BinTableHDU')

In PyFITS >= 3.3 pyfits.new_table() is deprecated. Use pyfits.BinTableHDU.from_columns() for new BINARY tables or pyfits.TableHDU.from_columns() for new ASCII tables instead. Similarly, in AstroPy >=0.4 astropy.io.fits.new_table() is deprecated. Use from_columns() methods from astropy.io.fits.BinTableHDU and astropy.io.fits.TableHDU.

Create a new table from the input column definitions.

columns: sequence of Column or ColDefs objects to create a
table from
hdr: a fits.Header instance to be used to populate the non-
required keywords
nrows: number of rows in the new table
fill: fill all cells with zeros or blanks

tbtype: table type to be created (“BinTableHDU” or “TableHDU”)

astro.util.darma.common.rename_keyword(hdr, oldkeyword, newkeyword)

Rename a card’s keyword in the header.

oldkeyword: old keyword or card index newkeyword: new keyword

class astro.util.darma.common.unicode

Bases: str

astro.util.darma.common.update_header(hdr, keyword, value, comment=None, before=None, after=None, savecomment=False)

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.

keyword: keyword of the card to be updated
value: value to be used for updating
comment: comment to be used for updating
before: keyword name/index of the card before which the new
card will be placed (the argument before takes precedence over after if both specified)
after: keyword name/index of the card after which the new
card will be placed
savecomment: preserve the current comment for an existing
keyword (takes precedence over comment if both specified)

## astro.util.darma.cube module¶

A list of images or pixelmaps with methods that process stacks of them.

astro.util.darma.cube.average_with_sigma_clip(data_cube, errors, threshold, niter=1)

Unimplemented

class astro.util.darma.cube.cube(filename=None, extension=0, data=None, image_list=None, index=0, readonly=0, memmap=1, datatype='float32', *args, **kwargs)

cubes are stacks of images or pixelmaps (3-dimensional arrays) that can be manipulated in similar fashions to images or pixelmaps. Normal arithmetic (addition, subtraction, multiplication, division, etc.) is performed on all members of the stack in turn (i1*constant, i2*constant, etc.), but other operations, such as statistics, are performed on sets of pixels in the z’ direction of the stack.

It is assumed that all members of a cube are the same shape, type, and datatype.

The functionality of a cube is very similar to that of an image or a pixelmap, except that the operations are typically broadcasted over all planes of the cube, while others condense the members of the cube to an image or a pixelmap.

as_image_list()

Return a list of individual image objects, each corresponding to planes in the data cube. This replicates the way Eclipse stored cube data.

as_pixelmap_list()

Return a list of individual pixelmap objects, each corresponding to planes in the data cube. This replicates the way Eclipse stored cube data.

average()

Do a straight average of all images in the cube.

average_with_rejection(low_reject, high_reject)

Unimplemented

average_with_sigma_clip(n_cycle, nmin, bias, scaling, thresh, badval, rn, gain)

Unimplemented

copy()

Copy the data to a new object.

load()

load_cube()

Load the images from a file, data or from the given image_list.

median()

Do a median average of all images in the cube.

buffer_size: number of rows to median at a time (no buffering if
buffer_size is 0)

This method is buffered to reduce memory usage and increase performance.

normalize_absolute_flux(pixmap=None, pixrange=None, zone=None, scale=1.0)

Normalize the images to an absolute flux of 1.0.

The absolute flux can be computed in a restricted area. This function modifies the image in-place.

pixmap: map of valid pixelsd (default=None)
pixrange: a range of valid values [low, high] (default=None)
zone: a valid zone [x0, y0, x1, y1]

scale: normalize to a different scale (default=1.0)

normalize_flux(pixmap=None, pixrange=None, zone=None, scale=1.0)

Normalize each plane to a flux of 1.0.

The flux can be computed in a restricted area. This function modifies each plane in-place.

pixmap: map of valid pixels (default=None)
pixrange: a range of valid values [low, high] (default=None)
zone: a valid zone [x0, y0, x1, y1]

scale: normalize to a different scale (default=1.0)

normalize_mean(pixmap=None, pixrange=None, zone=None, scale=1.0)

Normalize each plane to a mean of 1.0.

The mean can be computed in a restricted area. This function modifies each plane in-place.

pixmap: map of valid pixels (default=None)
pixrange: a range of valid values [low, high] (default=None)
zone: a valid zone [x0, y0, x1, y1]

scale: normalize to a different scale (default=1.0)

normalize_median(pixmap=None, pixrange=None, zone=None, scale=1.0)

Normalize each plane to a median of 1.0.

The median can be computed in a restricted area. This function modifies each plane in-place.

pixmap: map of valid pixels (default=None)
pixrange: a range of valid values [low, high] (default=None)
zone: a valid zone [x0, y0, x1, y1]

scale: normalize to a different scale (default=1.0)

normalize_range(pixmap=None, pixrange=None, zone=None, scale=1.0)

Normalize the images to a range of values between 0.0 and 1.0.

The range can be computed in a restricted area. This function modifies the image in-place.

pixmap: map of valid pixels (default=None)
pixrange: a range of valid values [low, high] (default=None)
zone: a valid zone [x0, y0, x1, y1]

scale: normalize to a different maximum (default=1.0)

save(filename=None, hdr=None, extension=None, datatype='float32', clobber=True, update_datamd5=True)

Save the data to a file.

filename: name of the file
extension: A FITS extension number
datatype: type of data output to the FITS file
clobber: overwrite an existing file

stdev(mean=None)

Compute the standard deviation of each pixel in the z direction.

Arguments:
mean – An image to be used for the average (default=None)

This procedure computes the mean deviation from a mean image. The mean image can be passed as an optional parameter. If no parameter is passed, the mean is computed first.

Try buffering to improve performance.

sum()

Sum all images in the cube to a single image.

xsize()

The length of the x-axis data of the cube members.

ysize()

The length of the y-axis data of the cube members.

zsize()

The length of the z-axis data of the cube members.

astro.util.darma.cube.make_cube(xsize, ysize, zsize, datatype='float32', value=None)

Generate a new cube.

xsize : the X dimension of the cube ysize : the Y dimension of the cube zsize : the Z dimension of the cube value : optional value to initialize pixel values to datatype: type of the image pixel data

NOTE: Associated data array is zero initialized.

A FITS header object resembling a dictionary.

astro.util.darma.header.fromstring(cardstring, verify='silentfix')

Return a new card from a <=80 character card string:

“KEYWORD = ‘value ‘ / standard FITS card comment ” “HIERAERCH ESO card = ‘value’ ” ” blank card ” “COMMENT card ” “HISTORY card ” “CONTINUE ‘card’ “

A standard card has the form of no more than 8 capital letters, numbers, or underscores, a padding of spaces, = at the 9th column, a space followed by a value, a ‘ / ‘, then the comment. A standard card string will have exactly 80 columns (padded by the parser if necessary). Other types of cards are shown above below the standard card.

Astonishingly, no version of either PyFITS or Astropy raises an exception upon parsing the cardstring or verifying the resultant card with option ‘exception’ when not following one of these forms! At best, a warning is given. Therefore, this function attempts to determine poor formatting and raises an exception when the cardstring does not match the criteria for any known card format.

astro.util.darma.header.get_headers(filename=None, cardlist=None)

The sole purpose of this factory function is to return a list of headers from the headers in the FITS file specified in filename or the ASCII file specified in cardlist. If the FITS file is single- extension, this is a list of one header. If the FITS file is multi- extension, this is a list of N+1 headers, where N is the number of extensions. For the cardlist, the list length is equal to the number of END cards or 1, whichever is less.

If both filename and cardlist are specified, the headers found in filename preceed those found in cardlist.

N.B. If there are multiple headers in a cardlist, each MUST be
ended with an END card. If there is no END card found, it is assumed that there is only one header in the cardlist.
filename : str
name of a valid FITS file, single- or multi-extension
cardlist : list, str
a list of header cards (80 character strings, NULL terminated), a list of fits.Card instances, or the name of a text file containing the header cards
list
a list of DARMA header instances, one per header found in the input
astro.util.darma.header.getval(filename, keyword, default=None, ext=0, use_fits=False)

Get a keyword value from an extension of a FITS image, single- or multi-extension.

filename: filename to get the keyword value from

keyword: keyword string default: the value to return when the keyword is missing

ext: extension number
use_fits: use FITS-handler’s getval function instead of simple
Python file access method
NOTE: The FITS-handler’s methods tend to be slower for extension
0/1 access, but may be faster for extension > 1 access.
class astro.util.darma.header.header(filename=None, extension=0, cardlist=None, option='silentfix')

Bases: object

A header object stores the information obtained from a FITS file header, a text file containing header cards one per line, a list of header card strings, or a list of fits.Card instances.

The header object also includes value and format validation through an on-demand implementation of the Astropy/PyFITS output verification mechanism. This guarantees that the header and its cards will always have the proper form. See:

http://archive.stsci.edu/fits/fits_standard/

for FITS standard documentation.

BLANK__

Attribute to return the list of BLANK cards

COMMENT

Attribute to return the list of COMMENT cards

HISTORY

Attribute to return the list of HISTORY cards

add(keyword, value, comment=None)

Synonym for append().

add_after(after, keyword, value, comment=None)

Add a new keyword-value-comment tuple after an existing keyword.

after: existing keyword to add after
keyword: keyword string
value: value

comment: comment string

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

value: Text to be added (folds at 72 characters)
before: keyword to place blank before
after: keyword to place blank after
add_comment(value, before=None, after=None)

value: comment text to be added (folds at 72 characters)
before: keyword to place comment before
after: keyword to place comment after
add_history(value, before=None, after=None)

value: history text to be added (folds at 72 characters)
before: keyword to place history before
after: keyword to place history after
append(keyword, value, comment=None, force=False)

Append a new keyword-value-comment card to the end of the header. If the keyword exists, it is overwritten.

keyword: keyword string
value: value
comment: comment string
force: force appending to end of header
NOTE: By default, Astropy/PyFITS group BLANK, COMMENT and

then HISTORY cards at the end of a header, appending normal card at the bottom, before these special cards.

Force overrides this behavior and appends any card to the end of the header.

as_eclipse_header()

block_size()

Length of a header data block written to a file (hard-coded to 2880 bytes or 36 80-byte header items)

cards

Attribute to store the list of cards for the header

comments() → a list of comments of H
copy()

Make a copy of the header.

Returns a new header object containing the same values as this header object.

default(type='primary')

type: type of header (primary or image)

A default header defines the keywords SIMPLE for a primary header, XTENSION for an image extension header, BITPIX, NAXIS (END will be added upon pairing with data when written to a file and cannot be added manually). Also, the random groups PCOUNT and GCOUNT keywords will be added for image-type headers upon automatic verification.

NOTE: primary-type headers are always the first and sometimes only
type of header in a FITS file. image-type headers always have a primary-type header at the begining of the FITS file and cannot be the only header in the FITS file.
dump()

Dump the contents of the header to the screen (less the END card and padding blank cards).

fromstring(cardstring)

Append a new standard card from a 80 character card string overwriting when the same named card.keyword exists:

‘SIMPLE = T / conforms to FITS standard…’

A standard card has the form of no more than 8 capital letters, numbers, or underscores, a padding of spaces, = at the 9th column, a space followed by a value, a ‘ / ‘, then the comment. A standard card string will have exactly 80 columns.

An attempt is made to standardize the cardstring by padding appropriately and truncating the comment when necessary. No attempt is made to correct the keyword and value beyond capitalizing the keyword.

get_all_headers()

The sole purpose of this method is to call the factory function get_headers that creates a list of headers from the headers in the file that the current header is loaded from (self.filename). If the file is single-extension or the filename is not specified, this is a list of one header, a copy of the current header. If the file is multi-extension, this is a list of one primary header and N extension headers, where N is the number of extensions.

get_blank()

Get all blank cards as a list of string texts.

get_blank_cards()

Get all blank card values as a list of header cards where applicable (i.e., if no proper header cards exist in the blank card values, the returned card list is empty).

get_comment()

Get all comments as a list of string texts.

get_comment_cards()

Get all comments as a list of header cards where applicable (i.e., if no proper header cards exist in the comments, the returned card list is empty).

get_history()

Get all histories as a list of string texts.

get_history_cards()

Get all histories as a list of header cards where applicable (i.e., if no proper header cards exist in the histories, the returned card list is empty).

hdr

index(keyword)

Return the integer index of the keyword in this header.

keyword: a string keyword value
info()

Show general information on this header.

item_size()

Length of a header item (hard-coded to 80 characters)

items() → a list of (keyword, value, comment) or

(keyword, value) items of H

itercards() → an iterator over the cards in H
itercomments() → an iterator over the comments of H
iteritems() -> an iterator over the (keyword, value, comment)

or (keyword, value) items of H

iterkeys() → an iterator over the keywords of H

Synonym for __iter__()

iterkeywords() → an iterator over the keywords of H

Synonym for __iter__()

itervalues() → an iterator over the values of H
keys() → a list of keywords of H
keywords() → a list of keywords of H

Synonym for keys()

load()

THIS SHOULD ONLY BE CALLED BY THE ‘getter’ METHOD.

load_header()

Load a header from a FITS file, or an ordinary text file or list. The attributes filename, extension, and cardlist must either be set during construction or set manually before this method is called.

The method attempts to load cards from a file if cardlist is a string, or directly from cardlist if it is a list. If cardlist is not defined, the header is loaded from the FITS file filename. Cards are assumed to be in the format:

keyword = value / comment

Cards should not exceed 80 characters unless they are COMMENT cards. Cards less than 80 characters will be padded as needed.

NOTE: Cards should not contain newlines.

merge(other, clobber=True)

other: header to merge into this one

clobber: overwrite existing keywords in this header

merge_into_file(filename, clobber=True)

Merge this header directly into the primary header of an existing file.

filename: name of file in which to merge this header
clobber: overwrite existing keywords in file
modify(keyword, value, comment=None)

Modify the value and/or comment of an existing keyword. If the keyword does not exist, it is appended to the end of the header.

Synonym for update without the before and after options.

new()

Create a new empty header object.

It is preferable to use default() to create a new header as the minimum keywords (see WARNING below) required to make a valid header will be provided automatically in the new header. Also, these minimum values will be overwritten automatically when the header is paired with data anyway.

WARNING: A minimum of SIMPLE or XTENSION, in addition to BITPIX and
NAXIS must be appended to this header object before it is valid.

> h = darma.header.header() > h = h.new() > h[‘SIMPLE’] = True > h[‘BITPIX’] = 8 > h[‘NAXIS’] = 0 > h.cards SIMPLE = T / conforms to FITS standard BITPIX = 8 / array data type NAXIS = 0 / number of array dimensions

rename_key(oldkey, newkey)

Synonym for rename_keyowrd()

Rename a card’s keyword in the header.

oldkey: old keyword, can be a name or index. newkey: new keyword, must be a string.

rename_keyword(oldkeyword, newkeyword)

Rename a card’s keyword in the header.

oldkeyword: old keyword, can be a name or index. newkeyword: new keyword, must be a string.

save(filename, raw=True, mode='clobber', dataless=False)

Save header to a text file. The contents of filename will be overwritten if mode=’clobber’.

filename: mandatory name of the file to be written
raw: write file as a raw, FITS-compatible file in binary
mode with 2880 byte blocks (if False, write a text file)
mode: clobber (default) overwrites the file and append
appends a new header onto the existing file
dataless: if true, remove NAXISn from output and set BITPIX
to 8 and NAXIS to 0 (prevents data size warnings when loading this dataless header from file)
update(keyword, value, comment=None, before=None, after=None)

Update a header keyword. If the keyword doews not exists, it will be appended.

values() → a list of values of H
verify(option='silentfix')

Verify the card order and validity of card values in the current header.

option: option used to verify the header (from PyFITS) should be
one of fix, silentfix, ignore, warn, or exception (ignore disables on-demand verification)
NOTE: As this is a dataless header, the BITPIX, NAXIS, and NAXISn
values are preserved from the original source, but are only for informational purposes. Once this header is paired with data, these values will be overwritten with data-specific values and may not match the original values.
astro.util.darma.header.update_header_in_file(filename, keywords=[], values=[], comments=[], ext=0, cards=[], option='silentfix', empty=False)

This is a utility function to update a header of a file “in place”.

When the FITS file is very large, rewriting the whole thing to update some header items is very inefficient. This function updates the header directly in the file. If there is appropriate space for new header items, this occurs with the minimum of disk I/O.

filename: name of FITS file containing the header to update keywords: matched list of header keywords

values: matched list of values
ext: extension to update
cards: replace keywords, values, comments with a list of
fits.Card instances (overrides components if set)
option: option used to verify the header (from Astropy/PyFITS)
should be one of fix, silentfix, ignore, warn, or exception

empty: first empty the header of any optional keywords

NOTE: This function assumes that any existing keyword values will
be overwritten.

## astro.util.darma.image module¶

Implements the image object with methods to process a 2D FITS image.

astro.util.darma.image.convert(filename, bitpix=16)

Convert data contained in filename to datatype bitpix. The file can be a single- or multi-extension FITS image.

filename: name of FITS file to convert
bitpix: BITPIX to convert data to (one of 8, 16, 32, -32, -64)
WARNING: This function is not completely robust for data whose
range is greater than 2**|bitpix| ADU and is primarily intended to overcome PyFITS insistance to use a float representation for all data, even when saving.
astro.util.darma.image.fft(real, imaginary=None, direction=-1)

Do a Fast Fourier Transorm (not currently using FFTW)

real: An image containing the real values

imaginary: An image containing the imaginary values (default=None) direction: -1 (forward) or 1 (inverse)

Returns a tuple of images representing the real and imaginary part of the fourier transformed data.

astro.util.darma.image.filter_nonnumbers(data, nanmask=None, filter=False)

Returns a 1-dimensional array with non-numbers (NaN, Inf, etc.) filtered out. All members of the input array are considered regardless of array rank (number of dimensions).

data: input data array of arbitrary rank
nanmask: a pixel mask where finite pixel values in data are 1
filter: filter out non-numbers (NaN, Inf, etc.)
class astro.util.darma.image.image(filename=None, extension=0, plane=0, readonly=0, memmap=1, data=None, datatype=None, bmask=None, bit=0, *args, **kwargs)

A 2D FITS image

This is the basic object used to manipulate FITS images. This object interfaces Array objects to provide a far greater range of image manipulation and direct access to the data.

NOTE: All interfaces through the image object have the axes in the

expected order: x,y (or NAXIS1,NAXIS2) with a unity-index access to the data (FITS standard), but the PyFITS interface returns an Array object with them in a swapped format due to row-major to column-major conversion: (y,x) assigned to the data attribute of the image object that is zero-indexed. This is due to the way Array counts axes slow to fast. Logically, data is stored in the array as a list of lists, where the first axis refers to individual lists, and the second refers to the list elements: rows then columns respectively (or NAXIS2 index then NAXIS1 index respectively in FITS terms). Data in a FITS file is stored in exactly this same way making the loading and unloading of data arrays most efficient if this convention is used.

When accessing array elements through the data attribute directly, be aware of these inconsistencies. Also, if manually creating a data array for inclusion into an image, the shape should be (NAXIS2, NAXIS1). For example:

img = image() img.data = Array.array((NAXIS2, NAXIS1), dtype=’float32’)

or preferably

img = img(data=Array.array((NAXIS2, NAXIS1)))

The image object provides several classes of operations:

The data of the image can be accessed directly from the image object itself in the typical Python way. Regardless of whether the index is a slice, coordinate tuple, or single coordinate, an image containing the requested data is returned. This means that accessing one data element is possible, but a one element image is returned. To get the value of that one element, it is a simple matter to access the data Array directly:

> number = img[x,y].data[()] > print number <value at FITS coordinates (x,y)>

Note: A single element (scalar) array results from the above operation.
The index ‘()’ is used to ‘extract’ that scalar in it’s native format (using data[0] will not work). The scalar array can also be cast into any other Python data-type or be used directly in arithmetic operations. In the latter case, a scalar array results from the operation.
Note: As mentioned above, data access directly from the image object

follows FITS convention (unity-indexed [NAXIS1, NAXIS2). Attempting to access the [0,0] element of an image will results in an error:

> img[0,0] DARMAError, Index [%d, _] not in FITS convention! Index [0, _] not in FITS convention!

Positive indexes go from 1…n, negative indexes are supported and mimic the standard Python conventions (e.g., -1 is the last element).

Slices work a little differently from Python standard. A little thought on the index behavior will reveal that a blank initial index means start at index 1, blank terminal index means stop at and include index n, and the range of the slice is terminal_index - initial_index + 1. Normal Python behavior says stop at and include n-1. For example:

> img = image.make_image(20, 20) > img.shape (20, 20) > img[1:10, :].shape (10, 20) > img.data[:, 1:10].shape (20, 9)

Note the data Array is stored with the axes in reversed order as is the PyFITS standard.

>>> xsize, ysize = img.xsize(), img.ysize()


Given two images, one can:

>>> newima = ima1 + ima2    # add them
>>> newima = ima1 - ima2    # subtract them
>>> newima = ima1 * ima2    # multiply them
>>> newima = ima1 / ima2    # divide them


One can also use constants in arithmetic operations:

>>> newima = ima + 2.5
>>> newima = ima - 3.2
>>> newima = ima * 1.7
>>> newima = ima / 1.11111
>>> newima = ima ** 2       # squared image


Note that arithmetic operations copy results. It might be more efficient to perform in-place operations:

>>> ima1 += ima2
>>> ima1 **= 0.5            # a sqrt image


However, in-place operations cannot be performed on images that are read-only.

One can use

>>> newima = ima.extract_region(x0, y0, x1, y1)


to extract a sub region from ima, or use a slice directly:

>>> newima = ima[x0:x1, y0:y1]


A number of operations allow one to obtain statstics for an image or some specified part of an image

>>> img.stat(domedian=1)


is used to obtain a common.StatStruct object (q.v.) containg statistics values (a.o.: mean, median, minimum, and maximum)

>>> img.get_mean()
>>> img.get_median()


return just the mean and median respectively

>>> img.stat_opts(...)


allows one to specify a pixelmap of valid pixels and/or an area of valid data and/or a range of valid pixel values to specify which data should be included when computing statistics

>>> img.filter_mean(xsize, ysize)
>>> img.filter_median(xsize, ysize)


Can be used to produce mean and median filters using rectangular kernels of arbitrary size (in both cases the default size is 3x3). In addition a number of named filters can be used: filter_dx(), filter_dy(), filter_dx2(), filter_dy2() filter_contour1(), filter_contour2(), filter_contour3(), and filter_contrast1()

Using the stat method and in_place multiplication, a number of normalization methods have been defined.

>>> img.normalize_mean()
>>> img.normalize_median()
>>> img.normalize_flux()
>>> img.normalize_absolute_flux()


normalize the image to a mean, median, flux or absolute flux of 1 (other scales are possible too). It is possible to specify relevant regions the same way as in image.stat_opts()

as_pixelmap()

Return a pixelmap object constructed from this image object. Values are converted to a boolean array (i.e., 0 ? 0 : 1)

clean_bad_pixels(pixmap, boxsize)

Interpolate the bad pixels in an image.

boxsize: width of interpolation region

NOTE: THIS METHOD CURRENTLY DOES NOT WORK!

count_nonnumbers()

Return the number of nonnumbers in the image.

filter_contour1()

Unimplemented

filter_contour2()

Unimplemented

filter_contour3()

Unimplemented

filter_contrast1()

Unimplemented

filter_dx()

Unimplemented

filter_dx2()

Unimplemented

filter_dy()

Unimplemented

filter_dy2()

Unimplemented

filter_mean(xsize=3, ysize=3)

Unimplemented

filter_median(xsize=3, ysize=3)

Unimplemented

get_max(filter=False)

Return the maximum value of this image.

get_mean(filter=False)

Return the mean value of this image.

get_median(sorted=False, filter=False)

Return the median value of this image.

sorted: is the data already sorted

get_min(filter=False)

Return the minumum value of this image.

get_rms(filter=False)

Return the rms (root mean square) value of this image.

get_stdev(filter=False)

Return the sample standard deviation value of this image.

has_nonnumbers()

Determine if non-numbers (NaN, Inf, etc.) exist in the data.

hough_transform(threshold)

Make a Hough transform of the image.

inverse_hough_transform(threshold, lx, ly)

Make an Inverse Hough transform of the image.

Unimplemented

iter_stat(max_iter=5, threshold=5.0, domedian=True, filter=False)

Compute the statistics iteratively.

max_iter: maximum number of iterations
threshold: rejection threshold (relative to stdev)
domedian: compute median
filter: filter out non-numbers (NaN, Inf, etc.)

Iteratively approximate the image statistics by rejecting outliers from the interval [median-threshold*stdev, median+thresold*stdev]

NOTE: If either max_iter or threshold is set to None or if domedian
is set to False, the iterative behavior is disabled as all are required for the iterations.

Returns a StatStruct object. Adds an attribute ‘convergence’ to the StatStruct object. The value of this attribute is 1 if the iteration converged, 0 otherwise. The number of iterations is also added under the ‘iterations’ attribute.

iter_stat_opts(pixmap=None, pixrange=None, zone=None, max_iter=5, threshold=5.0, domedian=True, filter=False)

Compute the statistics iteratively, using a pixmap and/or a pixrange and/or a zone to define included pixels.

pixmap: pixelmap object of same shape as self (0=bad, 1=good)
pixrange: a range of valid values (low, high)
zone: a tuple defining the valid zone (x0, y0, x1, y1)

max_iter: maximum number of iterations

threshold: rejection threshold (relative to stdev)
domedian: compute median
filter: filter out non-numbers (NaN, Inf, etc.)

Iteratively approximate the image statistics by rejecting outliers from the interval [median-threshold*stdev, median+thresold*stdev]

NOTE: If either max_iter or threshold is set to None or if domedian
is set to False, the iterative behavior is disabled as all are required for the iterations.

Returns a StatStruct object. Adds an attribute ‘convergence’ to the StatStruct object. The value of this attribute is 1 if the iteration converged, 0 otherwise. The number of iterations is also added under the ‘iterations’ attribute.

load()

THIS SHOULD ONLY BE CALLED BY THE ‘getter’ METHOD.

load_image()

Load the image from the given data Array or from filename. If there is no data and no filename, the image data is set to None.

map_nonnumbers()

Return a pixelmap with nonnumbers in the image marked as bad.

mirror_edges(xedge, yedge)

Mirror the edges of the image to create a new image

xedge: The size of the sides to be mirrored yedge: The size of the top/bottom to be mirrored

normalize_absolute_flux(pixmap=None, pixrange=None, zone=None, scale=1.0)

Normalize the image to an absolute flux of 1.0.

The absolute flux can be computed in a restricted area. This function modifies the image in-place

pixmap: map of valid pixels (default=None)
pixrange: a range of valid values [low, high] (default=None)
zone: a valid zone [xmin, ymin, xmax, ymax]

scale: normalize to a different scale (default=1.0)

normalize_flux(pixmap=None, pixrange=None, zone=None, scale=1.0)

Normalize the image to a flux of 1.0.

The flux can be computed in a restricted area. This function modifies the image in-place

pixmap: map of valid pixels (default=None)
pixrange: a range of valid values [low, high] (default=None)
zone: a valid zone [xmin, ymin, xmax, ymax]

scale: normalize to a different scale (default=1.0)

normalize_mean(pixmap=None, pixrange=None, zone=None, scale=1.0)

Normalize the image to a mean of 1.0.

The mean can be computed in a restricted area. This function modifies the image in-place.

pixmap: map of valid pixels (default=None)
pixrange: a range of valid values [low, high] (default=None)
zone: a valid zone [xmin, ymin, xmax, ymax]

scale: normalize to a different scale (default=1.0)

normalize_median(pixmap=None, pixrange=None, zone=None, scale=1.0)

Normalize the image to a median of 1.0.

The median can be computed in a restricted area. This function modifies the image in-place.

pixmap: map of valid pixels (default=None)
pixrange: a range of valid values [low, high] (default=None)
zone: a valid zone [xmin, ymin, xmax, ymax]

scale: normalize to a different scale (default=1.0)

normalize_range(pixmap=None, pixrange=None, zone=None, scale=1.0)

Normalize the image to a range of values between 0.0 and 1.0.

The range can be computed in a restricted area. This function modifies the image in-place

pixmap: map of valid pixels (default=None)
pixrange: a range of valid values [low, high] (default=None)
zone: a valid zone [xmin, ymin, xmax, ymax]

scale: normalize to a different scale (default=1.0)

run_counttest(Threshold)

Unimplemented

run_flatfittingtest(nwx, nwy, nfwx, nfwy)

Quality control tool for Twilight.

It can be used on flat images to see if there is a gradient, works in two steps, before use the bicubic spline interpolation to produce an image and after split this image in a number of subwindows; then for each subwindows compute the root means square and return the max rms value.

Arguments

nwx - number of subwindows in x nwy - number of subwindows in y nfwx - number of subwindows in x for fitting nfwy - number of subwindows in y for fitting

Returns a quality index.

Unimplemented

run_flattest(nwx, nwy)

Quality control tool for Dome.

This test works an flat-fielded images.

The image is normalised by its median value.The medians of a number of sub-windows of the normalized image are determined. The minimum median is subtracted from the maximum median and the result is given as output.

Arguments

nwx - number of subwindows in x nwy - number of subwindows in y

Returns a quality index.

Unimplemented

run_imsurfit(nwx, nwy)

Unimplemented

run_signtest(nwx, nwy, Threshold=5)
stat(domedian=True, filter=False)

Compute the statistics.

domedian: compute median
filter: filter out non-numbers (NaN, Inf, etc.)

Returns a StatStruct object. Adds an attribute ‘convergence’ to the StatStruct object. The value of this attribute is 1 if the iteration converged, 0 otherwise. The number of iterations is also added under the ‘iterations’ attribute.

stat_opts(pixmap=None, pixrange=None, zone=None, domedian=True, filter=False)

Compute the statistics, using a pixmap and/or a pixrange and/or a zone to define included pixels.

pixmap: boolean array of same shape as self.data (0=bad, 1=good)
pixrange: a range of valid values (low, high)
zone: a tuple defining the valid zone (x0, y0, x1, y1)
domedian: compute median
filter: filter out non-numbers (NaN, Inf, etc.)

Returns a StatStruct object. Adds an attribute ‘convergence’ to the StatStruct object. The value of this attribute is 1 if the iteration converged, 0 otherwise. The number of iterations is also added under the ‘iterations’ attribute.

subtract_oscan_columns(y0, y1, zone, smooth=0)

Subtract mean of overscan columns.

y0, y1: start and end row of overscan region zone: a tuple defining the zone to subtract mean from in

(x0, y0, x1, y1) form

smooth: size of rectangular box smoothing function

subtract_oscan_rows(x0, x1, zone=None, smooth=0)

Subtract mean of overscan rows.

x0, x1: start and end column of overscan region zone: a tuple defining the zone to subtract mean from in

(x0, y0, x1, y1) form

smooth: size of rectangular box smoothing function

thresh_to_pixmap(lo_cut=None, hi_cut=None)

Produce a pixelmap mapping pixels with values between low_cut and hi_cut.

threshold(lv, hv, sl, sh)

Unimplemented

astro.util.darma.image.make_image(xsize, ysize, datatype='float32', value=None)

Generate a new image.

xsize : the X dimension of the image ysize : the Y dimension of the image value : optional value to initialize pixel values to datatype: type of the image pixel data

NOTE: Associated data array is zero initialized.

astro.util.darma.image.max(data, nanmask=None, filter=False)

Return the maximum value of the dataset data. All members of the input array are considered regardless of array rank (number of dimensions).

data: input data array of arbitrary rank
nanmask: a pixel mask where finite pixel values in data are 1
filter: filter out non-numbers (NaN, Inf, etc.)
astro.util.darma.image.mean(data, nanmask=None, filter=False)

Return the mean of a sequence of the dataset data. All members of the input array are considered regardless of array rank (number of dimensions).

data: input data array of arbitrary rank
nanmask: a pixel mask where finite pixel values in data are 1
filter: filter out non-numbers (NaN, Inf, etc.)
astro.util.darma.image.median(data, nanmask=None, sorted=False, filter=False)

Return the median of the dataset data. All members of the input array are considered regardless of array rank (number of dimensions).

data: input data array of arbitrary rank
nanmask: a pixel mask where finite pixel values in data are 1
sorted: the input data array is already sorted filter: filter out non-numbers (NaN, Inf, etc.)
astro.util.darma.image.min(data, nanmask=None, filter=False)

Return the minimum value of teh dataset data. All members of the input array are considered regardless of array rank (number of dimensions).

data: input data array of arbitrary rank
nanmask: a pixel mask where finite pixel values in data are 1
filter: filter out non-numbers (NaN, Inf, etc.)
astro.util.darma.image.rms(data, nanmask=None, filter=False)

Return the root-mean-square (RMS) of the values of the dataset data. All members of the input array are considered regardless of array rank (number of dimensions).

data: input data array of arbitrary rank
nanmask: a pixel mask where finite pixel values in data are 1
filter: filter out non-numbers (NaN, Inf, etc.)
astro.util.darma.image.stdev(data, nanmask=None, filter=False)

Return the sample standard deviation of a the dataset data. All members of the input array are considered regardless of array rank (number of dimensions).

data: input data array of arbitrary rank
nanmask: a pixel mask where finite pixel values in data are 1
filter: filter out non-numbers (NaN, Inf, etc.)
astro.util.darma.image.uniform_filter1d(array, filter_size, mode=None, copy=False)

Filter data in a one dimmensional array, in place, averaging over 2*filtersize+1.

array: input Array object
filter_size: filter box = 2*filter_size+1
mode: mode of the endpoints treatment copy: modify and return a copy of array

The only current endpoint treatment modes are “reflect” and None. Only one dimensional arrays are supported at this time.

## astro.util.darma.image_generator module¶

Genenerate artificial data.

class astro.util.darma.image_generator.image_generator(xsize, ysize)

Bases: object

Provides object capable of producing artificially generated data with various properties.

generate_gauss2d(amplitude=1.0, x_pos=None, y_pos=None, sigma_x=1.0, sigma_y=1.0, param_dict=None)

Generate an image from a 2d Gaussian function.

ima(x,y) = amplitude*exp{-0.5*[((x-x_pos)/sigma_x)**2 +
((y-y_pos)/sigma_y)**2]}

If x_pos or y_pos are not given, they default to center of the respective axis.

An arbitrary number of Gaussian functions can be plotted at once using a parameter dictionary. If param_dict is given, it overrides all other parameters and should specify one or more Gaussian function paramter sets. All keys MUST exist in the dictionary and all values MUST be same length iterable (list or tuple), where the length indicates the number of functions desired. The param_dict has this structure:

param_dict = {‘amplitude’ : [],
‘x_pos’ : [], ‘y_pos’ : [], ‘sigma_x’ : [], ‘sigma_y’ : []}
generate_lorentz2d(amplitude=1.0, x_pos=None, y_pos=None, sigma_x=1.0, sigma_y=1.0, param_dict=None)

Generate an image from a 2d Lorentzian function.

ima(x,y) = amplitude*((sigx/((x-xpos-1)**2+sigx**2)) *
(sigy/((y-ypos-1)**2+sigy**2)))

If x_pos or y_pos are not given, they default to center of the respective axis.

An arbitrary number of Lorentzian functions can be plotted at once using a parameter dictionary. If param_dict is given, it overrides all other parameters and should specify one or more Lorentzian function paramter sets. All keys MUST exist in the dictionary and all values MUST be same length iterable (list or tuple), where the length indicates the number of functions desired. The param_dict has this structure:

param_dict = {‘amplitude’ : [],
‘x_pos’ : [], ‘y_pos’ : [], ‘sigma_x’ : [], ‘sigma_y’ : []}
generate_lowpass(sigma_x=1.0, sigma_y=1.0)

Generate a low-pass filter image. Construct a 2-Dim Gaussian function and move the center to the corners.

generate_poly2d(c=0.0, c_x=0.0, c_y=0.0, c_xx=0.0, c_xy=0.0, c_yy=0.0)

Generate an image from a 2d polynomial.

ima(x,y) = c+c_x*x+c_y*y+c_xx*x*x+c_xy*x*y+c_yy*y*y

generate_random_F(dfn=10, dfd=10)

Generate an image with noise in an F distribution with dfn degrees of freedom in the numerator and dfd degrees of freedom in the denominator.

generate_random_beta(a=1.0, b=1.0)

Generate an image with noise in a Beta distribution with parameters alpha (a) and beta (b). alpha or beta should not be 0.

generate_random_binomial(trials=10, p=0.1)

Generate an image with binomially distributed noise.

generate_random_chi_square(df=10)

Generate an image with noise in a chi^2 distribution with df degrees of freedom.

generate_random_exponential(mean=10.0)

Generate an image with noise exponentially distributed around a mean.

generate_random_floats()

Generate an image with noise uniformly distributed between min_pix and max_pix.

generate_random_gamma(a=0.0, r=1)

Generate an image with noise in a beta distribution with location parameter a and distribution shape parameter r.

generate_random_gauss(dispersion=1.0, mean=0.0)

Generate an image with noise distributed normally around mean, with rms dispersion.

generate_random_ints(min_pix=0, max_pix=10)

Generate an image with noise uniformly distributed between min_pix and max_pix.

generate_random_lorentz(dispersion=1.0, mean=0.0)

Generate an image with lorentzian distributed noise.

generate_random_poisson(mean=10.0)

Generate an image with noise Poisson distributed around a mean

generate_random_uniform(min_pix=0.0, max_pix=1.0)

Generate an image with noise uniformly distributed between min_pix and max_pix.

## astro.util.darma.pixelmap module¶

A map of boolean pixelvalues.

class astro.util.darma.pixelmap.pixelmap(filename=None, data=None, extension=0, plane=0, readonly=0, memmap=1, *args, **kwargs)

A class mimicing image(), but for boolean arrays indicating good (1) and bad (0) pixels.

All arithmetic operation on images can be used on pixelmaps. See the image() class for this and other details.

as_eclipse_pixelmap()

Return an Eclipse pixelmap object based on this pixelmap.

as_image()

Return an image object constructed from this pixelmap object.

bin_not()

Synonym for __invert__().

bin_xor(other)

Synonym for __ixor__

count()

Return the number of good pixels (non-zero values) in the pixelmap.

dump_pixelmap(filename)

A basic save() to filename.

load()

THIS SHOULD ONLY BE CALLED BY THE ‘getter’ METHOD.

load_pixelmap()

Load the pixelmap from a file or from the given data Array.

save(filename=None, hdr=None, datatype='uint8', clobber=True, update_datamd5=True)

Save the data to a file.

filename: name of the file (str)

datatype: type of data output to the FITS file

NOTE: pixelmaps are Boolean arrays and cannot be saved to FITS as
images with this datatype. The smallest datatype possible is unsigned 8-bit integer (the default datatype here.)
set_val(value=0)

Set all elements of the data in this image to an arbitrary value.

value: any number construct (int, float, imag, nan, etc.)

datatype: Array data type

## astro.util.darma.tables module¶

Implements the table object with methods to manipulate a FITS table.

class astro.util.darma.tables.columns(filename=None, name=None, datatype='binary', readonly=1, memmap=0)

Bases: object

A container object housing a list of columns, a table.

info()

load()

THIS SHOULD ONLY BE CALLED BY THE ‘getter’ METHOD.

load_columns()

Load a list of columns (a table) from the given filename. If there is no filename, table is set to None.

name

Name of the table holding the columns.

names

List of names of columns in the table.

class astro.util.darma.tables.tables(filename=None, table_ids=[], indexes=[], datatype='binary', readonly=1, memmap=0)

Bases: list

info()
load()

THIS SHOULD ONLY BE CALLED BY THE ‘getter’ METHOD.

load_tables()

Load a list of tables from the given filename. If there is no filename, tables is set to None.

names
tables`

## Module contents¶

A Data Access, Representation, and MAnipulation interface using AstroPy/PyFITS for FITS input/ouput and NumPy for Array manipulation, adapted from ESO’s Eclipse library Python interface and some of its C-code (http://www.eso.org/eclipse/).

Merriam-Webster’s Online Dictionary defines the progenitor term ‘dharma’ from Hinduism & Buddhism as:

2a: the basic principles of cosmic or individual existence

Thus, DARMA objects access, represent, and manipulate the most basic form of information that the data can take.

Author: John P. McFarland <mcfarland@astro.rug.nl>

This package provides a number of modules currently interfacing with the AstroPy.io.fits/PyFITS module to represent many forms of FITS data. The PyFITS module was developed by Space Telescope Science Institute (STScI) and provides an interface between FITS images and NumPy arrays. The AstroPy.io.fits module is a port of the PyFITS module by the AstroPy project. NumPy was also developed by STScI.

This package provides the following modules:

image: implements the image object with methods to process 2D
FITS image data
with an image
cube: a cube object is list of images with methods that
process stacks of images

pixelmap: a map of boolean pixel values indicating good/bad (1/0)
data

common: auxiliary data structures and constants

image_generator: Genenerate artificial data

Planned modules:

table: a representation of a binary FITS table and associated
methods
mosaic: a mosaic object is a set of images linked by a common
spatial layout (e.g., astrometry)