Measurements: How you put observations to the Toolbox#

To use PDR Toolbox, you need to create a Measurement for each of your observations. A Measurement consists of a value and an error. These can be single-valued or an array of values. In the typical case of an image, the Measurement is a representation of a FITS file with two HDUs, the first HDU is the spatial map of intensity and the 2nd HDU is the spatial map of the errors. It is based on astropy’s CCDData if you are familiar with that. Typical sub-millimeter maps we get from telescopes don’t have the error plane, but PDRT makes it easy for you to create one if you know the magnitude of the error. Typical FITS images will be in intensity units, equivalent to \({\rm erg~s^{-1}~cm^{-2}~sr^{-1}}\), or in \({\rm K~km~s^{-1}}\). For the latter, PDRT will do appropriate conversion as necessary when it uses your images (the original Measurement remains unchanged).

For example how to use Measurements, see the notebook PDRT_Example_Measurements.ipynb.


Manage spectral line or continuum observations

class pdrtpy.measurement.Measurement(*args, **kwargs)[source]#

Bases: CCDData

Measurement represents one or more observations of a given spectral line or continuum. It is made up of a value array, an uncertainty array, units, and a string identifier. It is based on astropy.nddata.CCDData. It can represent a single pixel observation or an image. Mathematical operations using Measurements will correctly propagate errors.

Typically, Measurements will be instantiated from a FITS file by using the the read() or make_measurement() methods. For a list of recognized spectral line identifiers, see supported_lines().

Parameters:
dataarray-like

The actual data. Note that data is saved by reference, so make a copy before passing if needed.

uncertaintyStdDevUncertainty, VarianceUncertainty, InverseVariance, or numpy.ndarray

Uncertainties on the data. If a numpy.ndarray, it is stored as StdDevUncertainty. Required.

unitastropy.units.Unit or str

The units of the data. Required.

identifierstr

A string indicating what this is an observation of, e.g., "CO_10" for CO(1-0).

titlestr, optional

A formatted string (e.g., LaTeX) for plotting. r-strings are accepted, e.g., r'$^{13}$CO(3-2)' gives \(^{13}{\rm CO(3-2)}\).

bmajastropy.units.Quantity, optional

Beam major axis diameter. Converted to degrees for FITS header storage.

bminastropy.units.Quantity, optional

Beam minor axis diameter. Converted to degrees for FITS header storage.

bpaastropy.units.Quantity, optional

Beam position angle. Converted to degrees for FITS header storage.

Attributes:
SN

Return the signal to noise ratio (value/error).

beam

Return the beam parameters as astropy Quantities or None if beam is not set

data

ndarray-like : The stored dataset.

dtype

numpy.dtype of this object’s data.

error

Return the underlying error array.

filename

The FITS file that created this measurement, or None if it didn’t originate from a file.

flags
header
id

Return the string ID of this measurement, e.g., CO_10.

levels
mask

any type : Mask for the dataset, if any.

meta
ndim

integer dimensions of this object’s data.

psf

Image representation of the PSF for the dataset.

shape

shape tuple of this object’s data.

size

integer size of this object’s data.

title

A formatted title (e.g., LaTeX) that can be used in plotting.

uncertainty

any type : Uncertainty in the dataset, if any.

unit

Unit : Unit for the dataset, if any.

value

Return the underlying data array.

wcs

any type : A world coordinate system (WCS) for the dataset, if any.

Methods

add(other)

Add this Measurement to another, propagating errors, units, and updating identifiers.

convert_unit_to(unit[, equivalencies])

Returns a new NDData object whose values have been converted to a new unit.

copy()

Return a copy of the CCDData object.

divide(other)

Divide this Measurement by another, propagating errors, units, and updating identifiers.

from_table(filename[, format, array])

Table file reader for Measurement class.

get(world_x, world_y[, log])

Get the value(s) at the given world coordinates.

get_pixel(world_x, world_y)

Return the nearest pixel coordinates to the input world coordinates.

is_ratio()

Indicate if this Measurement is a ratio.

is_single_pixel()

Is this Measurement a single value?

make_measurement(datafile, error, outfile[, ...])

Create a FITS file with 2 HDUs: the first containing the data, the second containing the uncertainty.

multiply(other)

Multiply this Measurement by another, propagating errors, units, and updating identifiers.

subtract(other)

Subtract another Measurement from this one, propagating errors, units, and updating identifiers.

to(unit[, equivalencies])

Returns a new Measurement object whose values and uncertainties have been converted to a new unit

to_hdu([hdu_mask, hdu_uncertainty, ...])

Creates an HDUList object from a CCDData object.

write(filename, **kwargs)

Write this Measurement to a FITS file with value in 1st HDU and error in 2nd HDU.

max

mean

min

read

sum

Raises:
TypeError

If beam parameters are not Quantities.

Note

Measurements can also be instantiated by the read(*args, **kwargs) method, to create an Measurement instance based on a FITS file. This method uses fits_measurement_reader() with the provided parameters. Example usage:

from pdrtpy.measurement import Measurement

my_obs = Measurement.read("file.fits",identifier="CII_158")
my_other_obs = Measurement.read("file2.fits",identifier="CO2_1",
                                 unit="K km/s",
                                 bmaj=9.3*u.arcsec,
                                 bmin=14.1*u.arcsec,
                                 bpa=23.2*u.degrees)

By default image axes with only a single dimension are removed on read. If you do not want this behavior, used read(squeeze=False). See also: astropy.nddata.CCDData.

property SN#

Return the signal to noise ratio (value/error).

Returns:
numpy.ndarray
add(other)[source]#

Add this Measurement to another, propagating errors, units, and updating identifiers. Masks are logically or’d.

Parameters:
otherMeasurement or number

A Measurement or number to add.

property beam#

Return the beam parameters as astropy Quantities or None if beam is not set

divide(other)[source]#

Divide this Measurement by another, propagating errors, units, and updating identifiers. Masks are logically or’d.

Parameters:
otherMeasurement or number

A Measurement or number to divide by.

property error#

Return the underlying error array.

Returns:
numpy.ndarray
property filename#

The FITS file that created this measurement, or None if it didn’t originate from a file.

Returns:
str or None
static from_table(filename, format='ipac', array=False)[source]#

Table file reader for Measurement class. Create one or more Measurements from a table. The input table header must contain the columns:

data - the data value

uncertainty - the error on the data, can be absolute error or percent. If percent, the header unit row entry for this column must be “%”

identifier - the identifier of this Measurement which should match a model in the ModelSet you are using, e.g., “CII_158” for [C II] 158 $\mu$m

The following columns are optional:

bmaj - beam major axis size

bmin - beam minor axis size

bpa - beam position angle

The table must specify the units of each column, e.g. a unit row in the header for IPAC format. Leave column entry blank if unitless. Units of value and error should be the same or conformable. Units must be transformable to a valid astropy.unit.Unit.

Parameters:
filenamestr

Name of table file.

formatstr, optional

Astropy Table format, e.g., ascii, ipac, votable. Default is IPAC format.

arraybool, optional

If True, one Measurement is created per table row and a list is returned. If False, one Measurement containing all data points is returned, using the identifier and beam parameters of the first row. For phasespace(), use array=False. Default: False.

Returns:
Measurement or list of Measurement
get(world_x, world_y, log=False)[source]#

Get the value(s) at the given world coordinates.

Parameters:
world_xfloat or array-like

The x value in world units of naxis1.

world_yfloat or array-like

The y value in world units of naxis2.

logbool, optional

True if the input coords are logarithmic. Default: False.

Returns:
float

The value(s) of the Measurement at input coordinates.

get_pixel(world_x, world_y)[source]#

Return the nearest pixel coordinates to the input world coordinates.

Parameters:
world_xfloat

The horizontal world coordinate.

world_yfloat

The vertical world coordinate.

property id#

Return the string ID of this measurement, e.g., CO_10.

Returns:
str
is_ratio()[source]#

Indicate if this Measurement is a ratio.

Looks for '/' past the first character of the identifier, e.g. "CII_158/CO_32". See also is_ratio().

Returns:
bool

True if the Measurement is a ratio, False otherwise.

is_single_pixel()[source]#

Is this Measurement a single value?

Returns:
bool

True if a single value (pixel).

property levels#
static make_measurement(datafile, error, outfile, rms=None, masknan=True, overwrite=False, unit='adu')[source]#

Create a FITS file with 2 HDUs: the first containing the data, the second containing the uncertainty.

This format allows the resulting file to be read by the underlying CCDData class.

Example:

# example with percentage error
Measurement.make_measurement("my_infile.fits",error='10%',outfile="my_outfile.fits")

# example with measurement in units of K km/s and error
# indicated by RMS keyword in input file.
Measurement.make_measurement("my_infile.fits", error='rms',
                             outfile="my_outfile.fits", unit="K km/s",overwrite=True)
Parameters:
datafilestr

The FITS file containing the data as a function of spatial coordinates.

errorstr

The errors on the data. Possible values:

  • a filename with the same shape as datafile containing per-pixel errors

  • a percentage string 'XX%' (must include the % symbol)

  • 'rms': use the rms parameter if given, otherwise look for the RMS keyword in the FITS header

outfilestr

The output FITS file to write the result to.

rmsfloat or astropy.units.Unit, optional

If error == 'rms', the rms value in the same units as the data (e.g. 'erg s-1 cm-2 sr-1').

masknanbool, optional

Whether to mask any pixel where the data or error is NaN. Default: True.

overwritebool, optional

If True, overwrite the output file if it exists. Default: False.

unitastropy.units.Unit or str, optional

Intensity unit for the data; overrides BUNIT in the header if present.

Raises:
Exception

On various FITS header issues.

OSError

If overwrite is False and the output file exists.

multiply(other)[source]#

Multiply this Measurement by another, propagating errors, units, and updating identifiers. Masks are logically or’d.

Parameters:
otherMeasurement or number

A Measurement or number to multiply.

subtract(other)[source]#

Subtract another Measurement from this one, propagating errors, units, and updating identifiers. Masks are logically or’d.

Parameters:
otherMeasurement or number

A Measurement or number to subtract.

property title#

A formatted title (e.g., LaTeX) that can be used in plotting.

Returns:
str or None
to(unit: str | Unit, equivalencies: list | None = None)[source]#

Returns a new Measurement object whose values and uncertainties have been converted to a new unit

Parameters:
unitUnit or str

The unit to convert to

equivalencieslist

A list of equivalence pairs in case the unit is not directly convertible. See Equivalencies

Returns:
Measurement

The converted measurement

Raises:
UnitConversionError

If the Measurement can’t be converted to the given unit.

property value#

Return the underlying data array.

Returns:
numpy.ndarray
write(filename, **kwargs)[source]#

Write this Measurement to a FITS file with value in 1st HDU and error in 2nd HDU.

See astropy.nddata.CCDData.write().

Parameters:
filenamestr

Name of file.

**kwargs

All additional keywords are passed to astropy.io.fits.

The available built-in formats are:
====== ==== ===== =============
Format Read Write Auto-identify
====== ==== ===== =============
====== ==== ===== =============
pdrtpy.measurement.fits_measurement_reader(filename, hdu=0, unit=None, hdu_mask='MASK', hdu_flags=None, key_uncertainty_type='UTYPE', **kwargs)[source]#

FITS file reader for Measurement class, called by Measurement.read().

Parameters:
filenamestr

Name of FITS file.

identifierstr, optional

String indicating what this is an observation of, e.g., "CO_10" for CO(1-0).

squeezebool, optional

If True, remove single dimension axes from the input image. Default: True.

hduint, optional

FITS extension from which Measurement should be initialized. If zero and no data in the primary extension, searches for the first extension with data. Default: 0.

unitastropy.units.Unit, optional

Units of the image data. If provided and BUNIT is in the header, this argument takes precedence. Default: None.

hdu_uncertaintystr or None, optional

FITS extension from which the uncertainty should be initialized. If the extension does not exist, uncertainty is None. Default: 'UNCERT'.

hdu_maskstr or None, optional

FITS extension from which the mask should be initialized. If the extension does not exist, mask is None. Default: 'MASK'.

hdu_flagsstr or None, optional

Currently not implemented. Default: None.

key_uncertainty_typestr, optional

Header key name where the uncertainty class name is stored. Default: 'UTYPE'.

**kwargs

Additional keyword parameters passed to the FITS reader in astropy.io.fits.

Raises:
TypeError

If the conversion from CCDData to Measurement fails.