Reference API

This API reference is auto-generated from the docstrings in the code. It is meant to be a reference for the code, not a tutorial or guide. For more information on how to use the code, see the User Manual. For programming tips using AstroData, see the Programmer’s Manual.

Entry point for the astrodata package.

This package adds an abstraction layer to astronomical data by parsing the information contained in the headers as attributes. To do so, one must subclass astrodata.AstroData and add parse methods accordingly to the TagSet received.

For more information, you can build the documentation locally by running

nox -s docs

and opening the file _build/html/index.html in a browser. Alternatively, you can check the online documentation at the |astrodata| pages site.

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.

__add__(oper)[source]

Performs addition by evaluating self + operand.

Parameters:

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

Return type:

AstroData instance

__annotations__ = {}
__contains__(attribute)[source]

Return True if the attribute is exposed in this instance.

Implements the ability to use the in operator with an AstroData object.

This looks for the attribute in :py:meth:~astrodata.AstroData.exposed.

Parameters:

attribute (str) – An attribute name.

Return type:

bool

__deepcopy__(memo)[source]

Return a new instance of this class.

Parameters:

memo (dict) – See the documentation on deepcopy for an explanation on how this works.

__delattr__(attribute)[source]

Delete an attribute.

__delitem__(idx)[source]

Delete an item using del self[idx].

Supports standard Python syntax (including negative indices).

Parameters:

idx (int) – This index represents the order of the element that you want to remove.

Raises:

IndexError – If idx is out of range.

__getattr__(attribute)[source]

Get the attribute with the specified name.

Called when an attribute lookup has not found the attribute in the usual places (not an instance attribute, and not in the class tree for self).

Parameters:

attribute (str) – The attribute’s name.

Raises:

AttributeError – If the attribute could not be found/computed.

Notes

For more information, see the documentation on the __getattr__ method in the Python documentation.

__getitem__(idx)[source]

Get the item at the specified index.

Returns a sliced view of the instance. It supports the standard Python indexing syntax.

Parameters:

slice (int, slice) – An integer or an instance of a Python standard slice object

Raises:
  • TypeError – If trying to slice an object when it doesn’t make sense (e.g. slicing a single slice)

  • ValueError – If slice does not belong to one of the recognized types

  • IndexError – If an index is out of range

__iadd__(oper)[source]

Performs inplace addition by evaluating self += operand.

Parameters:

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

Return type:

AstroData instance

__imul__(oper)[source]

Performs inplace multiplication by evaluating self *= operand.

Parameters:

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

Return type:

AstroData instance

__init__(nddata=None, tables=None, phu=None, indices=None, is_single=False)[source]
__isub__(oper)[source]

Performs inplace subtraction by evaluating self -= operand.

Parameters:

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

Return type:

AstroData instance

__iter__()[source]

Iterate over the extensions..

This generator yields the AstroData object for each extension.

Notes

This will yield the object, once, if it’s a single slice.

__itruediv__(oper)[source]

Performs inplace division by evaluating self /= operand.

Parameters:

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

Return type:

AstroData instance

__len__()[source]

Return the number of independent extensions stored by the object.

__module__ = 'astrodata.core'
__mul__(oper)[source]

Performs multiplication by evaluating self * operand.

Parameters:

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

Return type:

AstroData instance

__radd__(oper)

Performs addition by evaluating self + operand.

Parameters:

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

Return type:

AstroData instance

__rmul__(oper)

Performs multiplication by evaluating self * operand.

Parameters:

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

Return type:

AstroData instance

__rsub__(oper)[source]

Subtract with the operand on the right, using a copy.

__rtruediv__(oper)[source]

Divide (//) with the operand on the right, using a copy.

__setattr__(attribute, value)[source]

Set the attribute with the specified name to a given value.

Called when an attribute assignment is attempted, instead of the normal mechanism.

Parameters:
  • attribute (str) – The attribute’s name.

  • value (object) – The value to be assigned to the attribute.

__sub__(oper)[source]

Performs subtraction by evaluating self - operand.

Parameters:

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

Return type:

AstroData instance

__truediv__(oper)[source]

Performs division by evaluating self / operand.

Parameters:

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

Return type:

AstroData instance

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.

property 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.

property 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

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

property 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'])
property ext_tables

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

property 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.

property 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.

property header

Return the headers for the PHU and each extension.

Warning

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

property 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]
property indices

Return the extensions indices for sliced objects.

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.

property 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.

classmethod load(source, extname_parser=None)

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

property 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.

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

property 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).

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)  
property orig_filename

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

property 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.

property phu

Return the primary header.

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

property shape

Return the shape of the data array for each extension.

Return type:

list of tuple

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.

property tables

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

property 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.

telescope()[source]

Return the name of the telescope.

property 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.

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

property 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.

property wcs

Return the list of WCS objects for each extension.

Warning

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

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.

exception astrodata.AstroDataError[source]

Bases: Exception

Exception raised when there is a problem with the AstroData class.

__annotations__ = {}
__cause__

exception cause

__context__

exception context

__getattribute__(name, /)

Return getattr(self, name).

__init__(*args, **kwargs)
__module__ = 'astrodata.adfactory'
__new__(**kwargs)
__reduce__()

Helper for pickle.

__repr__()

Return repr(self).

__setstate__()
__str__()

Return str(self).

__suppress_context__
__traceback__
add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class astrodata.AstroDataMixin[source]

Bases: object

Mixin with AstroData-like behavior for NDData-like classes.

Mixin for NDData-like classes (such as Spectrum1D) to enable them to behave similarly to AstroData objects.

These behaviors are:
  1. mask attributes are combined with bitwise, not logical, or, since the individual bits are important.

  2. The WCS must be a gwcs.WCS object and slicing results in the model being modified.

  3. There is a settable variance attribute.

  4. Additional attributes such as OBJMASK can be extracted from the .meta[‘other’] dict

__annotations__ = {}
__getattr__(attribute)[source]

Access attributes stored in self.meta[‘other’].

Required to access attributes like AstroData objects. See the documentation for AstroData’s __getattr__ method for more information.

__module__ = 'astrodata.nddata'
property shape

The shape of the data.

property size

The size of the data.

property variance

Access the contents of uncertainty.

property wcs

Return the WCS of the data as a gWCS object.

This is a gWCS object, not a FITS WCS object.

This is returning wcs from an inhertited class, see NDData.wcs for more details.

class astrodata.NDAstroData(data, uncertainty=None, mask=None, wcs=None, meta=None, unit=None, copy=False, variance=None)[source]

Bases: AstroDataMixin, NDArithmeticMixin, NDSlicingMixin, NDData

Primary data class for AstroData objects.

Implements NDData with all Mixins, plus some AstroData specifics.

This class implements an NDData-like container that supports reading and writing as implemented in the astropy.io.registry and also slicing (indexing) and simple arithmetics (add, subtract, divide and multiply).

A very important difference between NDAstroData and NDData is that the former attempts to load all its data lazily. There are also some important differences in the interface (eg. .data lets you reset its contents after initialization).

Documentation is provided where our class differs.

See also

NDData, NDArithmeticMixin, NDSlicingMixin

Examples

The mixins allow operation that are not possible with NDData or NDDataBase, i.e. simple arithmetics:

>>> from astropy.nddata import StdDevUncertainty
>>> import numpy as np
>>> data = np.ones((3,3), dtype=float)
>>> ndd1 = NDAstroData(data, uncertainty=StdDevUncertainty(data))
>>> ndd2 = NDAstroData(data, uncertainty=StdDevUncertainty(data))
>>> ndd3 = ndd1.add(ndd2)
>>> ndd3.data
array([[2., 2., 2.],
    [2., 2., 2.],
    [2., 2., 2.]])
>>> ndd3.uncertainty.array
array([[1.41421356, 1.41421356, 1.41421356],
    [1.41421356, 1.41421356, 1.41421356],
    [1.41421356, 1.41421356, 1.41421356]])

see NDArithmeticMixin for a complete list of all supported arithmetic operations.

But also slicing (indexing) is possible:

>>> ndd4 = ndd3[1,:]
>>> ndd4.data
array([2., 2., 2.])
>>> ndd4.uncertainty.array
array([1.41421356, 1.41421356, 1.41421356])

See NDSlicingMixin for a description how slicing works (which attributes) are sliced.

Initialize an NDAstroData instance.

Parameters:
  • data (array-like) – The actual data. This can be a numpy array, a memmap, or a fits.ImageHDU object.

  • uncertainty (NDUncertainty-like object, optional) – An object that represents the uncertainty of the data. If not specified, the uncertainty will be set to None.

  • mask (array-like, optional) – An array that represents the mask of the data. If not specified, the mask will be set to None.

  • wcs (gwcs.WCS object, optional) – The WCS of the data. If not specified, the WCS will be set to None.

  • meta (dict-like, optional) – A dictionary-like object that holds the meta data. If not specified, the meta data will be set to None.

  • unit (astropy.units.Unit object, optional) – The unit of the data. If not specified, the unit will be set to None.

  • copy (bool, optional) – If True, the data, uncertainty, mask, wcs, meta, and unit will be copied. Otherwise, they will be referenced. Default is False.

  • variance (array-like, optional) – An array that represents the variance of the data. If not specified, the variance will be set to None.

Raises:

ValueError – If uncertainty and variance are both specified.

Notes

The uncertainty and variance parameters are mutually exclusive.

property T

Transpose the data. This is not a copy of the data.

__abstractmethods__ = frozenset({})
__annotations__ = {}
__deepcopy__(memo)[source]

Implement the deepcopy protocol for this class.

This implementation accounts for the lazy-loading of the data and uncertainty attributes. It also avoids recursion when copying the uncertainty attribute.

__getattr__(attribute)

Access attributes stored in self.meta[‘other’].

Required to access attributes like AstroData objects. See the documentation for AstroData’s __getattr__ method for more information.

__getitem__(item)
__init__(data, uncertainty=None, mask=None, wcs=None, meta=None, unit=None, copy=False, variance=None)[source]

Initialize an NDAstroData instance.

Parameters:
  • data (array-like) – The actual data. This can be a numpy array, a memmap, or a fits.ImageHDU object.

  • uncertainty (NDUncertainty-like object, optional) – An object that represents the uncertainty of the data. If not specified, the uncertainty will be set to None.

  • mask (array-like, optional) – An array that represents the mask of the data. If not specified, the mask will be set to None.

  • wcs (gwcs.WCS object, optional) – The WCS of the data. If not specified, the WCS will be set to None.

  • meta (dict-like, optional) – A dictionary-like object that holds the meta data. If not specified, the meta data will be set to None.

  • unit (astropy.units.Unit object, optional) – The unit of the data. If not specified, the unit will be set to None.

  • copy (bool, optional) – If True, the data, uncertainty, mask, wcs, meta, and unit will be copied. Otherwise, they will be referenced. Default is False.

  • variance (array-like, optional) – An array that represents the variance of the data. If not specified, the variance will be set to None.

Raises:

ValueError – If uncertainty and variance are both specified.

Notes

The uncertainty and variance parameters are mutually exclusive.

__module__ = 'astrodata.nddata'
__repr__()[source]

Return a string representation of the object.

If the data is lazy-loaded, the string representation will include the class name and the string “(Memmapped)”, representing that this memory may not have been loaded in yet.

__str__()

Return str(self).

classmethod add(operand, operand2=None, **kwargs)

Performs addition by evaluating self + operand.

Parameters:
  • operand (NDData-like instance) – If operand2 is None or not given it will perform the operation self + operand. If operand2 is given it will perform operand + operand2. If the method was called on a class rather than on the instance operand2 must be given.

  • operand2 (NDData-like instance) – If operand2 is None or not given it will perform the operation self + operand. If operand2 is given it will perform operand + operand2. If the method was called on a class rather than on the instance operand2 must be given.

  • propagate_uncertainties (bool or None, optional) –

    If None the result will have no uncertainty. If False the result will have a copied version of the first operand that has an uncertainty. If True the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default is True.

    Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated. None was added as valid parameter value.

  • handle_mask (callable, 'first_found' or None, optional) –

    If None the result will have no mask. If 'first_found' the result will have a copied version of the first operand that has a mask). If it is a callable then the specified callable must create the results mask and if necessary provide a copy. Default is numpy.logical_or.

    Added in version 1.2.

  • handle_meta (callable, 'first_found' or None, optional) –

    If None the result will have no meta. If 'first_found' the result will have a copied version of the first operand that has a (not empty) meta. If it is a callable then the specified callable must create the results meta and if necessary provide a copy. Default is None.

    Added in version 1.2.

  • compare_wcs (callable, 'first_found' or None, optional) –

    If None the result will have no wcs and no comparison between the wcs of the operands is made. If 'first_found' the result will have a copied version of the first operand that has a wcs. If it is a callable then the specified callable must compare the wcs. The resulting wcs will be like if False was given otherwise it raises a ValueError if the comparison was not successful. Default is 'first_found'.

    Added in version 1.2.

  • uncertainty_correlation (number or ~numpy.ndarray, optional) –

    The correlation between the two operands is used for correct error propagation for correlated data as given in: https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas Default is 0.

    Added in version 1.2.

kwargs :

Any other parameter that should be passed to the callables used.

Returns:

result – The resulting dataset

Return type:

~astropy.nddata.NDData-like

Notes

If a callable is used for mask, wcs or meta the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined as kwargs and must start with "wcs_" (for wcs callable) or "meta_" (for meta callable). This startstring is removed before the callable is called.

"first_found" can also be abbreviated with "ff".

property data

Access the data stored in this instance. It implements a setter.

classmethod divide(operand, operand2=None, **kwargs)

Performs division by evaluating self / operand.

Parameters:
  • operand (NDData-like instance) – If operand2 is None or not given it will perform the operation self / operand. If operand2 is given it will perform operand / operand2. If the method was called on a class rather than on the instance operand2 must be given.

  • operand2 (NDData-like instance) – If operand2 is None or not given it will perform the operation self / operand. If operand2 is given it will perform operand / operand2. If the method was called on a class rather than on the instance operand2 must be given.

  • propagate_uncertainties (bool or None, optional) –

    If None the result will have no uncertainty. If False the result will have a copied version of the first operand that has an uncertainty. If True the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default is True.

    Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated. None was added as valid parameter value.

  • handle_mask (callable, 'first_found' or None, optional) –

    If None the result will have no mask. If 'first_found' the result will have a copied version of the first operand that has a mask). If it is a callable then the specified callable must create the results mask and if necessary provide a copy. Default is numpy.logical_or.

    Added in version 1.2.

  • handle_meta (callable, 'first_found' or None, optional) –

    If None the result will have no meta. If 'first_found' the result will have a copied version of the first operand that has a (not empty) meta. If it is a callable then the specified callable must create the results meta and if necessary provide a copy. Default is None.

    Added in version 1.2.

  • compare_wcs (callable, 'first_found' or None, optional) –

    If None the result will have no wcs and no comparison between the wcs of the operands is made. If 'first_found' the result will have a copied version of the first operand that has a wcs. If it is a callable then the specified callable must compare the wcs. The resulting wcs will be like if False was given otherwise it raises a ValueError if the comparison was not successful. Default is 'first_found'.

    Added in version 1.2.

  • uncertainty_correlation (number or ~numpy.ndarray, optional) –

    The correlation between the two operands is used for correct error propagation for correlated data as given in: https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas Default is 0.

    Added in version 1.2.

kwargs :

Any other parameter that should be passed to the callables used.

Returns:

result – The resulting dataset

Return type:

~astropy.nddata.NDData-like

Notes

If a callable is used for mask, wcs or meta the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined as kwargs and must start with "wcs_" (for wcs callable) or "meta_" (for meta callable). This startstring is removed before the callable is called.

"first_found" can also be abbreviated with "ff".

property mask

Get or set the mask of the data.

classmethod max(**kwargs)
classmethod mean(**kwargs)
meta = None
classmethod min(**kwargs)
classmethod multiply(operand, operand2=None, **kwargs)

Performs multiplication by evaluating self * operand.

Parameters:
  • operand (NDData-like instance) – If operand2 is None or not given it will perform the operation self * operand. If operand2 is given it will perform operand * operand2. If the method was called on a class rather than on the instance operand2 must be given.

  • operand2 (NDData-like instance) – If operand2 is None or not given it will perform the operation self * operand. If operand2 is given it will perform operand * operand2. If the method was called on a class rather than on the instance operand2 must be given.

  • propagate_uncertainties (bool or None, optional) –

    If None the result will have no uncertainty. If False the result will have a copied version of the first operand that has an uncertainty. If True the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default is True.

    Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated. None was added as valid parameter value.

  • handle_mask (callable, 'first_found' or None, optional) –

    If None the result will have no mask. If 'first_found' the result will have a copied version of the first operand that has a mask). If it is a callable then the specified callable must create the results mask and if necessary provide a copy. Default is numpy.logical_or.

    Added in version 1.2.

  • handle_meta (callable, 'first_found' or None, optional) –

    If None the result will have no meta. If 'first_found' the result will have a copied version of the first operand that has a (not empty) meta. If it is a callable then the specified callable must create the results meta and if necessary provide a copy. Default is None.

    Added in version 1.2.

  • compare_wcs (callable, 'first_found' or None, optional) –

    If None the result will have no wcs and no comparison between the wcs of the operands is made. If 'first_found' the result will have a copied version of the first operand that has a wcs. If it is a callable then the specified callable must compare the wcs. The resulting wcs will be like if False was given otherwise it raises a ValueError if the comparison was not successful. Default is 'first_found'.

    Added in version 1.2.

  • uncertainty_correlation (number or ~numpy.ndarray, optional) –

    The correlation between the two operands is used for correct error propagation for correlated data as given in: https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas Default is 0.

    Added in version 1.2.

kwargs :

Any other parameter that should be passed to the callables used.

Returns:

result – The resulting dataset

Return type:

~astropy.nddata.NDData-like

Notes

If a callable is used for mask, wcs or meta the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined as kwargs and must start with "wcs_" (for wcs callable) or "meta_" (for meta callable). This startstring is removed before the callable is called.

"first_found" can also be abbreviated with "ff".

property psf

Image representation of the PSF for the dataset.

Should be ndarray-like.

set_section(section, input_data)[source]

Set a section of the data to the input data.

Sets only a section of the data. This method is meant to prevent fragmentation in the Python heap, by reusing the internal structures instead of replacing them with new ones.

Parameters:
  • section (slice) – The area that will be replaced

  • input_data (NDData-like instance) – This object needs to implement at least data, uncertainty, and mask. Their entire contents will replace the data in the area defined by section.

Examples

>>> def setup():
...     sec = NDData(np.zeros((100,100)))
...     ad[0].nddata.set_section(
...         (slice(None,100),slice(None,100)),
...         sec
...     )
...
>>> setup()  
property shape

The shape of the data.

property size

The size of the data.

classmethod subtract(operand, operand2=None, **kwargs)

Performs subtraction by evaluating self - operand.

Parameters:
  • operand (NDData-like instance) – If operand2 is None or not given it will perform the operation self - operand. If operand2 is given it will perform operand - operand2. If the method was called on a class rather than on the instance operand2 must be given.

  • operand2 (NDData-like instance) – If operand2 is None or not given it will perform the operation self - operand. If operand2 is given it will perform operand - operand2. If the method was called on a class rather than on the instance operand2 must be given.

  • propagate_uncertainties (bool or None, optional) –

    If None the result will have no uncertainty. If False the result will have a copied version of the first operand that has an uncertainty. If True the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default is True.

    Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated. None was added as valid parameter value.

  • handle_mask (callable, 'first_found' or None, optional) –

    If None the result will have no mask. If 'first_found' the result will have a copied version of the first operand that has a mask). If it is a callable then the specified callable must create the results mask and if necessary provide a copy. Default is numpy.logical_or.

    Added in version 1.2.

  • handle_meta (callable, 'first_found' or None, optional) –

    If None the result will have no meta. If 'first_found' the result will have a copied version of the first operand that has a (not empty) meta. If it is a callable then the specified callable must create the results meta and if necessary provide a copy. Default is None.

    Added in version 1.2.

  • compare_wcs (callable, 'first_found' or None, optional) –

    If None the result will have no wcs and no comparison between the wcs of the operands is made. If 'first_found' the result will have a copied version of the first operand that has a wcs. If it is a callable then the specified callable must compare the wcs. The resulting wcs will be like if False was given otherwise it raises a ValueError if the comparison was not successful. Default is 'first_found'.

    Added in version 1.2.

  • uncertainty_correlation (number or ~numpy.ndarray, optional) –

    The correlation between the two operands is used for correct error propagation for correlated data as given in: https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas Default is 0.

    Added in version 1.2.

kwargs :

Any other parameter that should be passed to the callables used.

Returns:

result – The resulting dataset

Return type:

~astropy.nddata.NDData-like

Notes

If a callable is used for mask, wcs or meta the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined as kwargs and must start with "wcs_" (for wcs callable) or "meta_" (for meta callable). This startstring is removed before the callable is called.

"first_found" can also be abbreviated with "ff".

classmethod sum(**kwargs)
transpose()[source]

Transpose the data. This is not a copy of the data.

property uncertainty

Get or set the uncertainty of the data.

property unit

Unit for the dataset, if any.

Type:

~astropy.units.Unit

property variance

Get and aset the variance of the data.

A convenience property to access the contents of uncertainty, squared (as the uncertainty data is stored as standard deviation).

property wcs

Return the WCS of the data as a gWCS object.

This is a gWCS object, not a FITS WCS object.

This is returning wcs from an inhertited class, see NDData.wcs for more details.

property window

Access a slice of the data.

Interface to access a section of the data, using lazy access whenever possible.

Returns:

  • An instance of NDWindowing, which provides __getitem__,

  • to allow the use of square brackets when specifying the window.

  • Ultimately, an NDWindowingAstrodata instance is returned.

Examples

>>> ad[0].nddata.window[100:200, 100:200]  
<NDWindowingAstrodata .....>
class astrodata.Section(*args, **kwargs)[source]

Bases: tuple

A class to handle n-dimensional sections.

Instantiate a new Section object.

Expects a sequence of pairs of start and end coordinates for each axis. This can be passed in order of axis (e.g., x1, x2, y1, y2) or as a set of keyword arguments (e.g., x1=0, x2=10, y1=0, y2=10).

Parameters:
  • x1 (int) –

    The start and end coordinates for each axis. If passed as positional arguments, they should be in order of axis. Otherwise, they can be passed as keyword arguments, such as:

    section = Section(x1=0, x2=10, y1=0, y2=10)
    

  • x2 (int) –

    The start and end coordinates for each axis. If passed as positional arguments, they should be in order of axis. Otherwise, they can be passed as keyword arguments, such as:

    section = Section(x1=0, x2=10, y1=0, y2=10)
    

  • y1 (int) –

    The start and end coordinates for each axis. If passed as positional arguments, they should be in order of axis. Otherwise, they can be passed as keyword arguments, such as:

    section = Section(x1=0, x2=10, y1=0, y2=10)
    

  • y2 (int) –

    The start and end coordinates for each axis. If passed as positional arguments, they should be in order of axis. Otherwise, they can be passed as keyword arguments, such as:

    section = Section(x1=0, x2=10, y1=0, y2=10)
    

  • ... (int) –

    The start and end coordinates for each axis. If passed as positional arguments, they should be in order of axis. Otherwise, they can be passed as keyword arguments, such as:

    section = Section(x1=0, x2=10, y1=0, y2=10)
    

__add__(value, /)

Return self+value.

__annotations__ = {}
__class_getitem__()

See PEP 585

__contains__(key, /)

Return bool(key in self).

__eq__(value, /)

Return self==value.

__ge__(value, /)

Return self>=value.

__getattr__(attr)[source]

Check for attrs in the axis_dict (axis names).

__getattribute__(name, /)

Return getattr(self, name).

__getitem__(key, /)

Return self[key].

__getnewargs__()[source]

Return arguments needed to create an equivalent Section instance.

__gt__(value, /)

Return self>value.

__hash__()

Return hash(self).

__iter__()

Implement iter(self).

__le__(value, /)

Return self<=value.

__len__()

Return len(self).

__lt__(value, /)

Return self<value.

__module__ = 'astrodata.utils'
__mul__(value, /)

Return self*value.

__ne__(value, /)

Return self!=value.

static __new__(cls, *args, **kwargs)[source]

Instantiate a new Section object.

Expects a sequence of pairs of start and end coordinates for each axis. This can be passed in order of axis (e.g., x1, x2, y1, y2) or as a set of keyword arguments (e.g., x1=0, x2=10, y1=0, y2=10).

Parameters:
  • x1 (int) –

    The start and end coordinates for each axis. If passed as positional arguments, they should be in order of axis. Otherwise, they can be passed as keyword arguments, such as:

    section = Section(x1=0, x2=10, y1=0, y2=10)
    

  • x2 (int) –

    The start and end coordinates for each axis. If passed as positional arguments, they should be in order of axis. Otherwise, they can be passed as keyword arguments, such as:

    section = Section(x1=0, x2=10, y1=0, y2=10)
    

  • y1 (int) –

    The start and end coordinates for each axis. If passed as positional arguments, they should be in order of axis. Otherwise, they can be passed as keyword arguments, such as:

    section = Section(x1=0, x2=10, y1=0, y2=10)
    

  • y2 (int) –

    The start and end coordinates for each axis. If passed as positional arguments, they should be in order of axis. Otherwise, they can be passed as keyword arguments, such as:

    section = Section(x1=0, x2=10, y1=0, y2=10)
    

  • ... (int) –

    The start and end coordinates for each axis. If passed as positional arguments, they should be in order of axis. Otherwise, they can be passed as keyword arguments, such as:

    section = Section(x1=0, x2=10, y1=0, y2=10)
    

__repr__()[source]

Return a string representation of the Section object.

__rmul__(value, /)

Return value*self.

asIRAFsection()[source]

Produce string with ‘[x1:x2,y1:y2]’ 1-indexed and end-inclusive.

Deprecated, see as_iraf_section().

as_iraf_section()[source]

Produce string with ‘[x1:x2,y1:y2]’ 1-indexed and end-inclusive.

This is the format used by IRAF for sections.

For example, >>> Section(0, 10, 0, 10).as_iraf_section() ‘[1:10,1:10]’

asslice(add_dims=0)[source]

Return the Section object as a slice/list of slices.

Higher dimensionality can be achieved with the add_dims parameter.

Parameters:

add_dims (int) – The number of dimensions to add to the slice.

property axis_dict

Return a dictionary with the axis names as keys.

contains(section)[source]

Return True if the section is entirely within this Section.

Parameters:

section (Section) – The Section to check for containment.

Returns:

True if the Section is entirely within this Section, otherwise False.

Return type:

bool

Raises:

ValueError – If the Sections have different dimensionality.

Examples

>>> Section(0, 10, 0, 10).contains(Section(1, 9, 1, 9))
True
>>> Section(0, 10, 0, 10).contains(Section(1, 11, 1, 9))
False
>>> Section(0, 10, 0, 10).contains(Section(1, 9, 1, 11))
False
>>> Section(0, 10, 0, 10).contains(Section(1, 3, 1, 7))
True
>>> Section(0, 10, 0, 10).contains(Section(1, 3, 1, 11))
False
count(value, /)

Return number of occurrences of value.

static from_shape(value)[source]

Produce a Section object defining a given shape.

Examples

>>> Section.from_shape((10, 10))
Section(x1=0, x2=10, y1=0, y2=10)
>>> Section.from_shape((10, 10, 10))
Section(x1=0, x2=10, y1=0, y2=10, z1=0, z2=10)
static from_string(value)[source]

Produce a Section object from a string.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

is_same_size(section)[source]

Return True if the Sections are the same size, otherwise False.

Examples

>>> Section(0, 10, 0, 10).is_same_size(Section(0, 10, 0, 10))
True
>>> Section(0, 10, 0, 10).is_same_size(Section(0, 10, 0, 11))
False
property ndim

The number of dimensions in the section.

overlap(section)[source]

Return the overlap between two sections, or None if no overlap.

Determine whether the two sections overlap. If so, the Section common to both is returned, otherwise None.

Examples

>>> Section(0, 10, 0, 10).overlap(Section(1, 9, 1, 9))
Section(x1=1, x2=9, y1=1, y2=9)
>>> Section(0, 10, 0, 10).overlap(Section(1, 11, 1, 9))
Section(x1=1, x2=10, y1=1, y2=9)
>>> Section(0, 10, 0, 10).overlap(Section(1, 9, 1, 11))
Section(x1=1, x2=9, y1=1, y2=10)
>>> Section(0, 10, 0, 10).overlap(Section(1, 3, 1, 7))
Section(x1=1, x2=3, y1=1, y2=7)
>>> Section(4, 6, 4, 6).overlap(Section(1, 3, 1, 2))
None
Raises:

ValueError – If the Sections have different dimensionality.

Notes

If sections do not overlap, a warning is logged when None is returned. This is to help with debugging, as it is often not an error condition.

shift(*shifts)[source]

Shift a section in each direction by the specified amount.

Parameters:

shifts (positional arguments) – The amount to shift the section in each direction.

Returns:

The shifted section.

Return type:

Section

Raises:

ValueError – If the number of shifts is not equal to the number of dimensions.

Examples

>>> Section(0, 10, 0, 10).shift(1, 1)
Section(x1=1, x2=11, y1=1, y2=11)
>>> Section(0, 10, 0, 10).shift(1, 1, 1)
Traceback (most recent call last):
...
ValueError: Number of shifts 3 incompatible with dimensionality 2
class astrodata.TagSet(add=None, remove=None, blocked_by=None, blocks=None, if_present=None)[source]

Bases: TagSet

A named tuple of sets of tag strings.

Named tuple that is used by tag methods to return which actions should be performed on a tag set.

All the attributes are optional, and any combination of them can be used, allowing to create complex tag structures. Read the documentation on the tag-generating algorithm if you want to better understand the interactions.

The simplest TagSet, though, tends to just add tags to the global set.

It can be initialized by position, like any other tuple (the order of the arguments is the one in which the attributes are listed below). It can also be initialized by name.

add

Tags to be added to the global set

Type:

set of str, optional

remove

Tags to be removed from the global set

Type:

set of str, optional

blocked_by

Tags that will prevent this TagSet from being applied

Type:

set of str, optional

blocks

Other TagSets containing these won’t be applied

Type:

set of str, optional

if_present

This TagSet will be applied only all of these tags are present

Type:

set of str, optional

Examples

>>> TagSet()  
TagSet(
    add=set(),
    remove=set(),
    blocked_by=set(),
    blocks=set(),
    if_present=set()
)
>>> TagSet({'BIAS', 'CAL'})  
TagSet(
    add={'BIAS', 'CAL'}, # These tags are added to the global set
    remove=set(),
    blocked_by=set(),
    blocks=set(),
    if_present=set()
)
>>> TagSet(remove={'BIAS', 'CAL'}) 
TagSet(
    add=set(),
    remove={'BIAS', 'CAL'}, # These tags are removed from the global set
    blocked_by=set(),
    blocks=set(),
    if_present=set()
)

Notes

If arguments are not provided, the default is an empty set.

These arguments are not applied within the object, instead they are used when tags are being applied to an AstroData object.

Instantiate a new TagSet object.

__add__(value, /)

Return self+value.

__annotations__ = {}
__class_getitem__()

See PEP 585

__contains__(key, /)

Return bool(key in self).

__eq__(value, /)

Return self==value.

__ge__(value, /)

Return self>=value.

__getattribute__(name, /)

Return getattr(self, name).

__getitem__(key, /)

Return self[key].

__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__gt__(value, /)

Return self>value.

__hash__()

Return hash(self).

__iter__()

Implement iter(self).

__le__(value, /)

Return self<=value.

__len__()

Return len(self).

__lt__(value, /)

Return self<value.

__match_args__ = ('add', 'remove', 'blocked_by', 'blocks', 'if_present')
__module__ = 'astrodata.utils'
__mul__(value, /)

Return self*value.

__ne__(value, /)

Return self!=value.

static __new__(cls, add=None, remove=None, blocked_by=None, blocks=None, if_present=None)[source]

Instantiate a new TagSet object.

__repr__()

Return a nicely formatted representation string

__rmul__(value, /)

Return value*self.

__slots__ = ()
add

Alias for field number 0

blocked_by

Alias for field number 2

blocks

Alias for field number 3

count(value, /)

Return number of occurrences of value.

if_present

Alias for field number 4

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

remove

Alias for field number 1

astrodata.add_header_to_table(table)[source]

Add a FITS header to a table’s metadata. Deprecated.

This does not modify the table itself, but adds the header to the table’s metadata. If a header is already present in the table’s metadata, it will ensure it’s up to date with the table’s columns.

Warning

This function is deprecated and will be removed in a future version. Its functionality is covered by Tables.

Parameters:

table (astropy.table.Table) – The table to add the header to.

Returns:

header – The header to add to the table

Return type:

astropy.io.fits.Header

astrodata.astro_data_descriptor(fn)[source]

Mark a class method as an AstroData descriptor.

Parameters:

fn (method) – The method to be decorated

Return type:

The tagged method (not a wrapper)

Warning

If used in combination with other decorators, this one must be the one on the top (i.e., the last one being applied). It doesn’t modify the method in any other way.

e.g.,

@astro_data_descriptor # This must be above returns_list
@returns_list
def my_descriptor_method(self):
    pass

Notes

This decorator is exactly equivalent to:

class MyClass:
    def my_descriptor_method(self):
        pass

    my_descriptor_method.descriptor_method = True

It is used to mark descriptors for collective operations, such as listing out the descriptors an AstroData object has or applying them to a set of extensions. See the documentation for descriptors() for an example.

astrodata.astro_data_tag(fn)[source]

Mark a method as a tag-producing method.

Parameters:

fn (method) – The method to be decorated

Return type:

A wrapper function

Notes

Decorator that marks methods of an AstroData derived class as part of the tag-producing system.

It wraps the method around a function that will ensure a consistent return value: the wrapped method can return any sequence of sequences of strings, and they will be converted to a TagSet. If the wrapped method returns None, it will be turned into an empty TagSet.

Example

class MyAstroData(AstroData):
    @astro_data_tag
    def my_tag_method(self):
        # Below are the tags generated by this method based on whether
        # the instrument is GMOS or not.
        if self.phu.get('INSTRUME') == 'GMOS':
            return {'GMOS'}

        return {'NOT_GMOS'}
astrodata.create(*args, **kwargs)[source]

Return an AstroData object from data.

Parameters:
  • phu (fits.PrimaryHDU or fits.Header or dict or list) – FITS primary HDU or header, or something that can be used to create a fits.Header (a dict, a list of “cards”).

  • extensions (list of HDUs) – List of HDU objects.

Returns:

An AstroData instance.

Return type:

astrodata.AstroData

Raises:

ValueError – If phu is not a valid object.

Example

>>> from astrodata import create
>>> ad = create(phu=fits.PrimaryHDU(), extensions=[fits.ImageHDU()])
astrodata.from_file(*args, **kwargs)[source]

Return an AstroData object from a file.

Parameters:

source (str, os.PathLike or HDUList) – The path to the file or the HDUList object. If a string is passed, it will be treated as a path to a file.

Returns:

An instantiated object. It will be a subclass of AstroData.

Return type:

AstroData

Notes

For implementation details, see get_astro_data().

This function is a wrapper around the factory method get_astro_data(), and uses the default factory instance at factory. If you want to override the default factory, you can create a new instance of AstroDataFactory and use its methods directly, or assign it to factory.

Example

>>> from astrodata import from_file
>>> ad = from_file("path/to/file.fits")

Alternatively, you can use an HDUList object:

>>> from astropy.io import fits
>>> hdulist = fits.open("path/to/file.fits")
>>> ad = from_file(hdulist)

Which can be useful for inspecting input before creating the AstroData object. This will not use the normal AstroData lazy-loading mechanism, however.

astrodata.open(*args, **kwargs)[source]

Return an AstroData object from a file.

Warning

This function is deprecated and will be removed in a future version. Use from_file() instead.

astrodata.returns_list(fn)[source]

Ensure a function returns a list.

Decorator to ensure that descriptors returning a list (of one value per extension) only returns single values when operating on single slices; and vice versa.

This is a common case, and you can use the decorator to simplify the logic of your descriptors.

Parameters:

fn (Callable) – The method to be decorated

Returns:

A function

Return type:

Callable

Example

from astrodata import (
    AstroData,
    astro_data_descriptor,
    returns_list,
    NDAstroData
)

class MyAstroData(AstroData):
    @astro_data_descriptor
    @returns_list
    def my_descriptor(self):
        return 1

# Create an instance of the class with slices
ad = MyAstroData([NDAstroData([1, 2, 3]), NDAstroData([4, 5, 6])])

# This will print [1, 1] to stdout
print(ad.my_descriptor())
astrodata.version()[source]

Return the version of astrodata.