AstroData

class astrodata.AstroData(nddata=None, tables=None, phu=None, indices=None, is_single=False)[source]

Bases: object

Base class for the AstroData software package.

It provides an interface to manipulate astronomical data sets.

Parameters:
  • nddata (astrodata.NDAstroData or list of astrodata.NDAstroData) – List of NDAstroData objects.

  • tables (dict[name, astropy.table.Table]) – Dict of table objects.

  • phu (astropy.io.fits.Header) – Primary header.

  • indices (list of int) – List of indices mapping the astrodata.NDAstroData objects that this object will access to. This is used when slicing an object, then the sliced AstroData will have the .nddata list from its parent and access the sliced NDAstroData through this list of indices.

Warning

This class is not meant to be instantiated directly. Instead, use the factory method astrodata.from_file() to create an instance of this class using a file. Alternatively, use the astrodata.create() function to create a new instance from scratch.

The documentation here is meant for developers who want to extend the functionality of this class.

Registering an AstroData subclass

To create a new subclass of AstroData, you need to register it with the factory. This is done by creating a new subclass and using AstroDataFactory.add_class():

from astrodata import AstroData, factory

class MyAstroData(AstroData):
    @classmethod
    def _matches_data(cls):
        '''Trivial match for now.'''
        return True

factory.add_class(MyAstroData)

Once the class is registered, the factory will be able to create instances of it when reading files. It will also be able to create instances of it when using the astrodata.create() function. It uses the special, required method _matches_data() to determine if the class matches the data in the file. If there are multiple matches, the factory will try to find one that has the most specific match and is a subclass of the other candidates.

If There is no match or multiple matches, the factory will raise an exception. See AstroDataFactory.get_astro_data() for more information.

Attributes Summary

data

Create a list of arrays corresponding to data in extensions.

descriptors

Return a sequence of names for descriptor methods.

exposed

Return a set of attribute names that can be accessed directly.

ext_tables

Return names of the extensions' astropy.table.Table objects.

filename

Return the filename.

hdr

Return all headers, as a astrodata.fits.FitsHeaderCollection.

header

Return the headers for the PHU and each extension.

id

Return the extension identifier.

indices

Return the extensions indices for sliced objects.

is_sliced

Return True if this object is a slice of a dataset.

mask

Return a list of the mask arrays for each extension.

nddata

Return the list of astrodata.NDAstroData objects.

orig_filename

Return the original file name (before it was modified).

path

Return the file path, if generated from or saved to a file.

phu

Return the primary header.

shape

Return the shape of the data array for each extension.

tables

Return the names of the associated astropy.table.Table objects.

tags

Return a set of strings that represent the class' tags.

uncertainty

Create a list of the uncertainty objects for each extension.

variance

Return a list of variance arrays for each extension.

wcs

Return the list of WCS objects for each extension.

Methods Summary

add(oper)

Performs inplace addition by evaluating self += operand.

append(ext[, name, header])

Add a new top-level extension.

crop(x1, y1, x2, y2)

Crop the NDData objects given indices.

divide(oper)

Performs inplace division by evaluating self /= operand.

info()

Print out information about the contents of this instance.

instrument()

Return the name of the instrument making the observation.

is_settable(attr)

Return True if the attribute is meant to be modified.

load(source[, extname_parser])

Read from a file, file object, HDUList, etc.

matches_data(source)

Return True if the class can handle the data in the source.

multiply(oper)

Performs inplace multiplication by evaluating self *= operand.

object()

Return the name of the object being observed.

operate(operator, *args, **kwargs)

Apply a function to the data in each extension.

read(source[, extname_parser])

Read from a file, file object, HDUList, etc.

reset(data[, mask, variance, check])

Reset the data, and optionally mask and variance of an extension.

subtract(oper)

Performs inplace subtraction by evaluating self -= operand.

table()

Return a dictionary of astropy.table.Table objects.

telescope()

Return the name of the telescope.

update_filename([prefix, suffix, strip])

Update the "filename" attribute of the AstroData object.

write([filename, overwrite])

Write the object to a file.

Attributes Documentation

data

Create a list of arrays corresponding to data in extensions.

This may be a single array, if the data is a single slice.

If set, it expects the value to be something with a shape, such as a numpy array.

Notes

The result will always be a list, even if it’s a single slice.

descriptors

Return a sequence of names for descriptor methods.

These are the methods that are decorated with the astro_data_descriptor() decorator.

This checks for the existence of the descriptor_method attribute in the class members, so anything with that attribute (regardless of the attribute’s value) will be interpreted as a descriptor.

Return type:

tuple of str

exposed

Return a set of attribute names that can be accessed directly.

A collection of strings with the names of objects that can be accessed directly by name as attributes of this instance, and that are not part of its standard interface (i.e. data objects that have been added dynamically).

Examples

>>> ad[0].exposed  
set(['OBJMASK', 'OBJCAT'])
ext_tables

Return names of the extensions’ astropy.table.Table objects.

filename

Return the filename. This is the basename of the path, or None.

If the filename is set, the path will be updated automatically.

If the filename is set to an absolute path, a ValueError will be raised.

hdr

Return all headers, as a astrodata.fits.FitsHeaderCollection.

If this is a single-slice object, the header will be returned as a single Header object. Otherwise, it will be returned as a astrodata.fits.FitsHeaderCollection object.

header

Return the headers for the PHU and each extension.

Warning

This property is deprecated and will be removed in the future.

id

Return the extension identifier.

The identifier is a 1-based extension number for objects with single slices.

For objects that are not single slices, a ValueError will be raised.

Notes

To get all the id values, use the indices property and add 1 to each value:

ids = [i + 1 for i in ad.indices]
indices

Return the extensions indices for sliced objects.

is_sliced

Return True if this object is a slice of a dataset.

If this data provider instance represents a whole dataset, return False. If it represents a slice out of a whole, return True.

It does this by checking if the _indices private attribute is set.

mask

Return a list of the mask arrays for each extension.

Returns a list of the mask arrays (or a single array, if this is a single slice) attached to the science data, for each extension.

For objects that miss a mask, None will be provided instead.

Notes

The result will always be a list, even if it’s a single slice.

nddata

Return the list of astrodata.NDAstroData objects.

If the AstroData object is sliced, this returns only the NDData objects of the sliced extensions. And if this is a single extension object, the NDData object is returned directly (i.e. not a list).

orig_filename

Return the original file name (before it was modified).

path

Return the file path, if generated from or saved to a file.

If this is set to a file path, the filename will be updated automatically. The original filename will be stored in the orig_filename property.

phu

Return the primary header.

shape

Return the shape of the data array for each extension.

Return type:

list of tuple

tables

Return the names of the associated astropy.table.Table objects.

tags

Return a set of strings that represent the class’ tags.

It collects the tags from the methods decorated with the astro_data_tag() decorator.

uncertainty

Create a list of the uncertainty objects for each extension.

The objects are instances of AstroPy’s astropy.nddata.NDUncertainty, or None where no information is available.

See also

variance

The actual array supporting the uncertainty object.

Notes

The result will always be a list, even if it’s a single slice.

variance

Return a list of variance arrays for each extension.

A list of the variance arrays (or a single array, if this is a single slice) attached to the science data, for each extension.

For objects that miss uncertainty information, None will be provided instead.

See also

uncertainty

The uncertainty objects used under the hood.

Notes

The result will always be a list, even if it’s a single slice.

wcs

Return the list of WCS objects for each extension.

Warning

This is what is returned by the astropy.nddata.NDData.wcs property.

Methods Documentation

add(oper)

Performs inplace addition by evaluating self += operand.

Parameters:

oper (number or object) – The operand to perform the operation self += operand.

Return type:

AstroData instance

append(ext, name=None, header=None)[source]

Add a new top-level extension.

Parameters:
  • ext (array, astropy.nddata.NDData, astropy.table.Table, other) – The contents for the new extension. The exact accepted types depend on the class implementing this interface. Implementations specific to certain data formats may accept specialized types (eg. a FITS provider will accept an astropy.io.fits.ImageHDU and extract the array out of it).

  • name (str, optional) – A name that may be used to access the new object, as an attribute of the provider. The name is typically ignored for top-level (global) objects, and required for the others. If the name cannot be derived from the metadata associated to ext, you will have to provider one. It can consist in a combination of numbers and letters, with the restriction that the letters have to be all capital, and the first character cannot be a number (“[A-Z][A-Z0-9]*”).

Returns:

  • The same object, or a new one, if it was necessary to convert it to

  • a more suitable format for internal use.

Raises:
  • TypeError – If adding the object in an invalid situation (eg. name is None when adding to a single slice).

  • ValueError – Raised if the extension is of a proper type, but its value is illegal somehow.

crop(x1, y1, x2, y2)[source]

Crop the NDData objects given indices.

Parameters:
  • x1 (int) – Minimum and maximum indices for the x and y axis.

  • y1 (int) – Minimum and maximum indices for the x and y axis.

  • x2 (int) – Minimum and maximum indices for the x and y axis.

  • y2 (int) – Minimum and maximum indices for the x and y axis.

divide(oper)

Performs inplace division by evaluating self /= operand.

Parameters:

oper (number or object) – The operand to perform the operation self /= operand.

Return type:

AstroData instance

info()[source]

Print out information about the contents of this instance.

instrument()[source]

Return the name of the instrument making the observation.

is_settable(attr)[source]

Return True if the attribute is meant to be modified.

classmethod load(source, extname_parser=None)

Read from a file, file object, HDUList, etc.

classmethod matches_data(source) bool[source]

Return True if the class can handle the data in the source.

Parameters:

source (list of astropy.io.fits.HDUList) – The FITS file to be read.

Returns:

True if the class can handle the data in the source.

Return type:

bool

Note

Typically, this method is implemented by the static method Astrodata._matches_data or by a class method with the same signature for subclasses.

If you are implementing a subclass, you should override _matches_data instead, which is a static method that takes a single argument, the source data, and returns a boolean.

If that method is not overridden, this method will call it with the source data as argument.

For more information, see the documentation for the _matches_data() and the Developer Guide.

multiply(oper)

Performs inplace multiplication by evaluating self *= operand.

Parameters:

oper (number or object) – The operand to perform the operation self *= operand.

Return type:

AstroData instance

object()[source]

Return the name of the object being observed.

operate(operator, *args, **kwargs)[source]

Apply a function to the data in each extension.

Applies a function to the main data array on each extension, replacing the data with the result. The data will be passed as the first argument to the function.

It will be applied to the mask and variance of each extension, too, if they exist.

This is a convenience method, which is equivalent to:

for ext in ad:
    ext.data = operator(ext.data, *args, **kwargs)
    if ext.mask is not None:
        ext.mask = operator(ext.mask, *args, **kwargs)
    if ext.variance is not None:
        ext.variance = operator(ext.variance, *args, **kwargs)

with the additional advantage that it will work on single slices, too.

Parameters:
  • operator (callable) – A function that takes an array (and, maybe, other arguments) and returns an array.

  • args (optional) – Additional arguments to be passed to the operator.

  • kwargs (optional) – Additional arguments to be passed to the operator.

Examples

>>> import numpy as np
>>> ad.operate(np.squeeze)  
classmethod read(source, extname_parser=None)[source]

Read from a file, file object, HDUList, etc.

reset(data, mask=<object object>, variance=<object object>, check=True)[source]

Reset the data, and optionally mask and variance of an extension.

Sets the .data, and optionally .mask and .variance attributes of a single-extension AstroData slice. This function will optionally check whether these attributes have the same shape.

Parameters:
  • data (ndarray) – The array to assign to the .data attribute (“SCI”).

  • mask (ndarray, optional) – The array to assign to the .mask attribute (“DQ”).

  • variance (ndarray, optional) – The array to assign to the .variance attribute (“VAR”).

  • check (bool) – If set, then the function will check that the mask and variance arrays have the same shape as the data array.

Raises:
  • TypeError – if an attempt is made to set the .mask or .variance attributes with something other than an array

  • ValueError – if the .mask or .variance attributes don’t have the same shape as .data, OR if this is called on an AD instance that isn’t a single extension slice

subtract(oper)

Performs inplace subtraction by evaluating self -= operand.

Parameters:

oper (number or object) – The operand to perform the operation self -= operand.

Return type:

AstroData instance

table()[source]

Return a dictionary of astropy.table.Table objects.

Notes

This returns a _copy_ of the tables, so modifying them will not affect the original ones.

telescope()[source]

Return the name of the telescope.

update_filename(prefix=None, suffix=None, strip=False)[source]

Update the “filename” attribute of the AstroData object.

A prefix and/or suffix can be specified. If strip=True, these will replace the existing prefix/suffix; if strip=False, they will simply be prepended/appended.

The current filename is broken down into its existing prefix, root, and suffix using the ORIGNAME phu keyword, if it exists and is contained within the current filename. Otherwise, the filename is split at the last underscore and the part before is assigned as the root and the underscore and part after the suffix. No prefix is assigned.

Note that, if strip=True, a prefix or suffix will only be stripped if ‘’ is specified.

Parameters:
  • prefix (str, optional) – New prefix (None => leave alone)

  • suffix (str, optional) – New suffix (None => leave alone)

  • strip (bool, optional) – Strip existing prefixes and suffixes if new ones are given?

Raises:

ValueError – If the filename cannot be determined

write(filename=None, overwrite=False)[source]

Write the object to a file.

Parameters:
  • filename (str, optional) – If the filename is not given, self.path is used.

  • overwrite (bool) – If True, overwrites existing file.