AegeanTools modules

angle_tools

Tools for manipulating angles on the surface of a sphere - distance - bearing between two points - translation along a path - paths are either great circles or rhumb lines

also angle <-> string conversion tools for Aegean

AegeanTools.angle_tools.bear(ra1, dec1, ra2, dec2)[source]

Calculate the bearing of point 2 from point 1 along a great circle. The bearing is East of North and is in [0, 360), whereas position angle is also East of North but (-180,180]

Parameters:
ra1, dec1, ra2, dec2 : float

The sky coordinates (degrees) of the two points.

Returns:
bear : float

The bearing of point 2 from point 1 (degrees).

AegeanTools.angle_tools.bear_rhumb(ra1, dec1, ra2, dec2)[source]

Calculate the bearing of point 2 from point 1 along a Rhumb line. The bearing is East of North and is in [0, 360), whereas position angle is also East of North but (-180,180]

Parameters:
ra1, dec1, ra2, dec2 : float

The sky coordinates (degrees) of the two points.

Returns:
dist : float

The bearing of point 2 from point 1 along a Rhumb line (degrees).

AegeanTools.angle_tools.dec2dec(dec)[source]

Convert sexegessimal RA string into a float in degrees.

Parameters:
dec : string

A string separated representing the Dec. Expected format is [+- ]hh:mm[:ss.s] Colons can be replaced with any whit space character.

Returns:
dec : float

The Dec in degrees.

AegeanTools.angle_tools.dec2dms(x)[source]

Convert decimal degrees into a sexagessimal string in degrees.

Parameters:
x : float

Angle in degrees

Returns:
dms : string

String of format [+-]DD:MM:SS.SS or XX:XX:XX.XX if x is not finite.

AegeanTools.angle_tools.dec2hms(x)[source]

Convert decimal degrees into a sexagessimal string in hours.

Parameters:
x : float

Angle in degrees

Returns:
dms : string

String of format HH:MM:SS.SS or XX:XX:XX.XX if x is not finite.

AegeanTools.angle_tools.dist_rhumb(ra1, dec1, ra2, dec2)[source]

Calculate the Rhumb line distance between two points [1]. A Rhumb line between two points is one which follows a constant bearing.

Parameters:
ra1, dec1, ra2, dec2 : float

The position of the two points (degrees).

Returns:
dist : float

The distance between the two points along a line of constant bearing.

Notes

[1]Rhumb line
AegeanTools.angle_tools.gcd(ra1, dec1, ra2, dec2)[source]

Calculate the great circle distance between to points using the haversine formula [1].

Parameters:
ra1, dec1, ra2, dec2 : float

The coordinates of the two points of interest. Units are in degrees.

Returns:
dist : float

The distance between the two points in degrees.

Notes

This duplicates the functionality of astropy but is faster as there is no creation of SkyCoords objects.

[1]Haversine formula
AegeanTools.angle_tools.ra2dec(ra)[source]

Convert sexegessimal RA string into a float in degrees.

Parameters:
ra : string

A string separated representing the RA. Expected format is hh:mm[:ss.s] Colons can be replaced with any whit space character.

Returns:
ra : float

The RA in degrees.

AegeanTools.angle_tools.translate(ra, dec, r, theta)[source]

Translate a given point a distance r in the (initial) direction theta, along a great circle.

Parameters:
ra, dec : float

The initial point of interest (degrees).

r, theta : float

The distance and initial direction to translate (degrees).

Returns:
ra, dec : float

The translated position (degrees).

AegeanTools.angle_tools.translate_rhumb(ra, dec, r, theta)[source]

Translate a given point a distance r in the (initial) direction theta, along a Rhumb line.

Parameters:
ra, dec : float

The initial point of interest (degrees).

r, theta : float

The distance and initial direction to translate (degrees).

Returns:
ra, dec : float

The translated position (degrees).

BANE

This module contains all of the BANE specific code The function filter_image should be imported from elsewhere and run as is.

AegeanTools.BANE.barrier(events, sid, kind='neighbour')[source]

act as a multiprocessing barrier

AegeanTools.BANE.filter_image(im_name, out_base, step_size=None, box_size=None, twopass=False, cores=None, mask=True, compressed=False, nslice=None)[source]

Create a background and noise image from an input image. Resulting images are written to outbase_bkg.fits and outbase_rms.fits

Parameters:
im_name : str or HDUList

Image to filter. Either a string filename or an astropy.io.fits.HDUList.

out_base : str

The output filename base. Will be modified to make _bkg and _rms files.

step_size : (int,int)

Tuple of the x,y step size in pixels

box_size : (int,int)

The size of the box in piexls

twopass : bool

Perform a second pass calculation to ensure that the noise is not contaminated by the background. Default = False

cores : int

Number of CPU corse to use. Default = all available

nslice : int

The image will be divided into this many horizontal stripes for processing. Default = None = equal to cores

mask : bool

Mask the output array to contain np.nna wherever the input array is nan or not finite. Default = true

compressed : bool

Return a compressed version of the background/noise images. Default = False

Returns:
None
AegeanTools.BANE.filter_mc_sharemem(filename, step_size, box_size, cores, shape, nslice=None, domask=True)[source]

Calculate the background and noise images corresponding to the input file. The calculation is done via a box-car approach and uses multiple cores and shared memory.

Parameters:
filename : str

Filename to be filtered.

step_size : (int, int)

Step size for the filter.

box_size : (int, int)

Box size for the filter.

cores : int

Number of cores to use. If None then use all available.

nslice : int

The image will be divided into this many horizontal stripes for processing. Default = None = equal to cores

shape : (int, int)

The shape of the image in the given file.

domask : bool

True(Default) = copy data mask to output.

Returns:
bkg, rms : numpy.ndarray

The interpolated background and noise images.

AegeanTools.BANE.sigma_filter(filename, region, step_size, box_size, shape, domask, sid)[source]

Calculate the background and rms for a sub region of an image. The results are written to shared memory - irms and ibkg.

Parameters:
filename : string

Fits file to open

region : list

Region within the fits file that is to be processed. (row_min, row_max).

step_size : (int, int)

The filtering step size

box_size : (int, int)

The size of the box over which the filter is applied (each step).

shape : tuple

The shape of the fits image

domask : bool

If true then copy the data mask to the output.

sid : int

The stripe number

Returns:
None
AegeanTools.BANE.sigmaclip(arr, lo, hi, reps=3)[source]

Perform sigma clipping on an array, ignoring non finite values.

During each iteration return an array whose elements c obey: mean -std*lo < c < mean + std*hi

where mean/std are the mean std of the input array.

Parameters:
arr : iterable

An iterable array of numeric types.

lo : float

The negative clipping level.

hi : float

The positive clipping level.

reps : int

The number of iterations to perform. Default = 3.

Returns:
mean : float

The mean of the array, possibly nan

std : float

The std of the array, possibly nan

Notes

Scipy v0.16 now contains a comparable method that will ignore nan/inf values.

AegeanTools.BANE.write_fits(data, header, file_name)[source]

Combine data and a fits header to write a fits file.

Parameters:
data : numpy.ndarray

The data to be written.

header : astropy.io.fits.hduheader

The header for the fits file.

file_name : string

The file to write

Returns:
None

catalogs

Module for reading at writing catalogs

AegeanTools.catalogs.check_table_formats(files)[source]

Determine whether a list of files are of a recognizable output type.

Parameters:
files : str

A list of file names

Returns:
result : bool

True if all the file names are supported

AegeanTools.catalogs.get_table_formats()[source]

Create a list of file extensions that are supported for writing.

Returns:
fmts : list

A list of file name extensions that are supported.

AegeanTools.catalogs.load_catalog(filename)[source]

Load a catalogue and extract the source positions (only)

Parameters:
filename : str

Filename to read. Supported types are csv, tab, tex, vo, vot, and xml.

Returns:
catalogue : list

A list of [ (ra, dec), …]

AegeanTools.catalogs.load_table(filename)[source]

Load a table from a given file.

Supports csv, tab, tex, vo, vot, xml, fits, and hdf5.

Parameters:
filename : str

File to read

Returns:
table : Table

Table of data.

AegeanTools.catalogs.nulls(x)[source]

Convert values of -1 into None.

Parameters:
x : float or int

Value to convert

Returns:
val : [x, None]
AegeanTools.catalogs.save_catalog(filename, catalog, meta=None, prefix=None)[source]

Save a catalogue of sources using filename as a model. Meta data can be written to some file types (fits, votable).

Each type of source will be in a separate file:

Where filename = base.ext

Parameters:
filename : str

Name of file to write, format is determined by extension.

catalog : list

A list of sources to write. Sources must be of type AegeanTools.models.OutputSource, AegeanTools.models.SimpleSource, or AegeanTools.models.IslandSource.

prefix : str

Prepend each column name with “prefix_”. Default is to prepend nothing.

meta : dict

Meta data to be written to the output file. Support for metadata depends on file type.

Returns:
None
AegeanTools.catalogs.show_formats()[source]

Print a list of all the file formats that are supported for writing. The file formats are determined by their extensions.

Returns:
None
AegeanTools.catalogs.table_to_source_list(table, src_type=<class 'AegeanTools.models.OutputSource'>)[source]

Convert a table of data into a list of sources.

A single table must have consistent source types given by src_type. src_type should be one of AegeanTools.models.OutputSource, AegeanTools.models.SimpleSource, or AegeanTools.models.IslandSource.

Parameters:
table : Table

Table of sources

src_type : class

Sources must be of type AegeanTools.models.OutputSource, AegeanTools.models.SimpleSource, or AegeanTools.models.IslandSource.

Returns:
sources : list

A list of objects of the given type.

AegeanTools.catalogs.update_meta_data(meta=None)[source]

Modify the metadata dictionary. DATE, PROGRAM, and PROGVER are added/modified.

Parameters:
meta : dict

The dictionary to be modified, default = None (empty)

Returns:
An updated dictionary.
AegeanTools.catalogs.writeAnn(filename, catalog, fmt)[source]

Write an annotation file that can be read by Kvis (.ann) or DS9 (.reg). Uses ra/dec from catalog. Draws ellipses if bmaj/bmin/pa are in catalog. Draws 30” circles otherwise.

Only AegeanTools.models.OutputSource will appear in the annotation file unless there are none, in which case AegeanTools.models.SimpleSource (if present) will be written. If any AegeanTools.models.IslandSource objects are present then an island contours file will be written.

Parameters:
filename : str

Output filename base.

catalog : list

List of sources.

fmt : [‘ann’, ‘reg’]

Output file type.

Returns:
None
AegeanTools.catalogs.writeDB(filename, catalog, meta=None)[source]

Output an sqlite3 database containing one table for each source type

Parameters:
filename : str

Output filename

catalog : list

List of sources of type AegeanTools.models.OutputSource, AegeanTools.models.SimpleSource, or AegeanTools.models.IslandSource.

meta : dict

Meta data to be written to table meta

Returns:
None
AegeanTools.catalogs.writeFITSTable(filename, table)[source]

Convert a table into a FITSTable and then write to disk.

Parameters:
filename : str

Filename to write.

table : Table

Table to write.

Returns:
None

Notes

Due to a bug in numpy, int32 and float32 are converted to int64 and float64 before writing.

AegeanTools.catalogs.writeIslandBoxes(filename, catalog, fmt)[source]

Write an output file in ds9 .reg, or kvis .ann format that contains bounding boxes for all the islands.

Parameters:
filename : str

Filename to write.

catalog : list

List of sources. Only those of type AegeanTools.models.IslandSource will have contours drawn.

fmt : str

Output format type. Currently only ‘reg’ and ‘ann’ are supported. Default = ‘reg’.

Returns:
None
AegeanTools.catalogs.writeIslandContours(filename, catalog, fmt='reg')[source]

Write an output file in ds9 .reg format that outlines the boundaries of each island.

Parameters:
filename : str

Filename to write.

catalog : list

List of sources. Only those of type AegeanTools.models.IslandSource will have contours drawn.

fmt : str

Output format type. Currently only ‘reg’ is supported (default)

Returns:
None
AegeanTools.catalogs.write_catalog(filename, catalog, fmt=None, meta=None, prefix=None)[source]

Write a catalog (list of sources) to a file with format determined by extension.

Sources must be of type AegeanTools.models.OutputSource, AegeanTools.models.SimpleSource, or AegeanTools.models.IslandSource.

Parameters:
filename : str

Base name for file to write. _simp, _comp, or _isle will be added to differentiate the different types of sources that are being written.

catalog : list

A list of source objects. Sources must be of type AegeanTools.models.OutputSource, AegeanTools.models.SimpleSource, or AegeanTools.models.IslandSource.

fmt : str

The file format extension.

prefix : str

Prepend each column name with “prefix_”. Default is to prepend nothing.

meta : dict

A dictionary to be used as metadata for some file types (fits, VOTable).

Returns:
None
AegeanTools.catalogs.write_table(table, filename)[source]

Write a table to a file.

Parameters:
table : Table

Table to be written

filename : str

Destination for saving table.

Returns:
None

cluster

Cluster and crossmatch tools and analysis functions.

Includes: - DBSCAN clustering

AegeanTools.cluster.norm_dist(src1, src2)[source]

Calculate the normalised distance between two sources. Sources are elliptical Gaussians.

The normalised distance is calculated as the GCD distance between the centers, divided by quadrature sum of the radius of each ellipse along a line joining the two ellipses.

For ellipses that touch at a single point, the normalized distance will be 1/sqrt(2).

Parameters:
src1, src2 : object

The two positions to compare. Objects must have the following parameters: (ra, dec, a, b, pa).

Returns:
dist: float

The normalised distance.

AegeanTools.cluster.pairwise_ellpitical_binary(sources, eps, far=None)[source]

Do a pairwise comparison of all sources and determine if they have a normalized distance within eps.

Form this into a matrix of shape NxN.

Parameters:
sources : list

A list of sources (objects with parameters: ra,dec,a,b,pa)

eps : float

Normalised distance constraint.

far : float

If sources have a dec that differs by more than this amount then they are considered to be not matched. This is a short-cut around performing GCD calculations.

Returns:
prob : numpy.ndarray

A 2d array of True/False.

AegeanTools.cluster.regroup(catalog, eps, far=None, dist=<function norm_dist>)[source]

Regroup the islands of a catalog according to their normalised distance. Return a list of island groups. Sources have their (island,source) parameters relabeled.

Parameters:
catalog : str or object

Either a filename to read into a source list, or a list of objects with the following properties[units]: ra[deg],dec[deg], a[arcsec],b[arcsec],pa[deg], peak_flux[any]

eps : float

maximum normalised distance within which sources are considered to be grouped

far : float

(degrees) sources that are further than this distance appart will not be grouped, and will not be tested. Default = None.

dist : func

a function that calculates the distance between two sources must accept two SimpleSource objects. Default = AegeanTools.cluster.norm_dist()

Returns:
islands : list

A list of islands. Each island is a list of sources.

AegeanTools.cluster.regroup_vectorized(srccat, eps, far=None, dist=<function norm_dist>)[source]

Regroup the islands of a catalog according to their normalised distance.

Assumes srccat is recarray-like for efficiency. Return a list of island groups.

Parameters:
srccat : np.rec.arry or pd.DataFrame

Should have the following fields[units]: ra[deg],dec[deg], a[arcsec],b[arcsec],pa[deg], peak_flux[any]

eps : float

maximum normalised distance within which sources are considered to be grouped

far : float

(degrees) sources that are further than this distance apart will not be grouped, and will not be tested. Default = 0.5.

dist : func

a function that calculates the distance between a source and each element of an array of sources. Default = AegeanTools.cluster.norm_dist()

Returns:
islands : list of lists

Each island contians integer indices for members from srccat (in descending dec order).

AegeanTools.cluster.sky_dist(src1, src2)[source]

Great circle distance between two sources. A check is made to determine if the two sources are the same object, in this case the distance is zero.

Parameters:
src1, src2 : object

Two sources to check. Objects must have parameters (ra,dec) in degrees.

Returns:
distance : float

The distance between the two sources.

fits_image

Tools for interacting with fits images (HUDLists)

class AegeanTools.fits_image.Beam(a, b, pa, pixa=None, pixb=None)[source]

Small class to hold the properties of the beam. Properties are a,b,pa. No assumptions are made as to the units, but both a and b have to be >0.

class AegeanTools.fits_image.FitsImage(filename=None, hdu_index=0, beam=None, cube_index=None)[source]

An object that handles the loading and manipulation of a fits file.

get_background_rms()[source]

Calculate the rms of the image. The rms is calculated from the interqurtile range (IQR), to reduce bias from source pixels.

Returns:
rms : float

The image rms.

Notes

The rms value is cached after first calculation.

get_hdu_header()[source]

Get the image header.

get_pixels()[source]

Get the image data.

Returns:
pixels : numpy.ndarray

2d Array of image pixels.

pix2sky(pixel)[source]

Get the sky coordinates for a given image pixel.

Parameters:
pixel : (float, float)

Image coordinates.

Returns:
ra,dec : float

Sky coordinates (degrees)

set_pixels(pixels)[source]

Set the image data. Will not work if the new image has a different shape than the current image.

Parameters:
pixels : numpy.ndarray

New image data

Returns:
None
sky2pix(skypos)[source]

Get the pixel coordinates for a given sky position (degrees).

Parameters:
skypos : (float,float)

ra,dec position in degrees.

Returns:
x,y : float

Pixel coordinates.

AegeanTools.fits_image.fix_aips_header(header)[source]

Search through an image header. If the keywords BMAJ/BMIN/BPA are not set, but there are AIPS history cards, then we can populate the BMAJ/BMIN/BPA. Fix the header if possible, otherwise don’t. Either way, don’t complain.

Parameters:
header : HDUHeader

Fits header which may or may not have AIPS history cards.

Returns:
header : HDUHeader

A header which has BMAJ, BMIN, and BPA keys, as well as a new HISTORY card.

AegeanTools.fits_image.get_beam(header)[source]

Create a AegeanTools.fits_image.Beam object from a fits header.

BPA may be missing but will be assumed to be zero.

if BMAJ or BMIN are missing then return None instead of a beam object.

Parameters:
header : HDUHeader

The fits header.

Returns:
beam : AegeanTools.fits_image.Beam

Beam object, with a, b, and pa in degrees.

AegeanTools.fits_image.get_pixinfo(header)[source]

Return some pixel information based on the given hdu header pixarea - the area of a single pixel in deg2 pixscale - the side lengths of a pixel (assuming they are square)

Parameters:
header : HDUHeader or dict

FITS header information

Returns:
pixarea : float

The are of a single pixel at the reference location, in square degrees.

pixscale : (float, float)

The pixel scale in degrees, at the reference location.

Notes

The reference location is not always at the image center, and the pixel scale/area may change over the image, depending on the projection.

fits_interp

A module to allow fits files to be shrunk in size using decimation, and to be grown in size using interpolation.

AegeanTools.fits_interp.compress(datafile, factor, outfile=None)[source]

Compress a file using decimation.

Parameters:
datafile : str or HDUList

Input data to be loaded. (HDUList will be modified if passed).

factor : int

Decimation factor.

outfile : str

File to be written. Default = None, which means don’t write a file.

Returns:
hdulist : HDUList

A decimated HDUList

AegeanTools.fits_interp.expand(datafile, outfile=None)[source]

Expand and interpolate the given data file using the given method. Datafile can be a filename or an HDUList

It is assumed that the file has been compressed and that there are BN_? keywords in the fits header that describe how the compression was done.

Parameters:
datafile : str or HDUList

filename or HDUList of file to work on

outfile : str

filename to write to (default = None)

Returns:
hdulist : HDUList

HDUList of the expanded data.

AegeanTools.fits_interp.load_file_or_hdu(filename)[source]

Load a file from disk and return an HDUList If filename is already an HDUList return that instead

Parameters:
filename : str or HDUList

File or HDU to be loaded

Returns:
hdulist : HDUList

fitting

Provide fitting routines and helper fucntions to Aegean

AegeanTools.fitting.Bmatrix(C)[source]

Calculate a matrix which is effectively the square root of the correlation matrix C

Parameters:
C : 2d array

A covariance matrix

Returns:
B : 2d array

A matrix B such the B.dot(B’) = inv(C)

AegeanTools.fitting.Cmatrix(x, y, sx, sy, theta)[source]

Construct a correlation matrix corresponding to the data. The matrix assumes a gaussian correlation function.

Parameters:
x, y : array-like

locations at which to evaluate the correlation matirx

sx, sy : float

major/minor axes of the gaussian correlation function (sigmas)

theta : float

position angle of the gaussian correlation function (degrees)

Returns:
data : array-like

The C-matrix.

AegeanTools.fitting.RB_bias(data, pars, ita=None, acf=None)[source]

Calculate the expected bias on each of the parameters in the model pars. Only parameters that are allowed to vary will have a bias. Calculation follows the description of Refrieger & Brown 1998 (cite).

Parameters:
data : 2d-array

data that was fit

pars : lmfit.Parameters

The model

ita : 2d-array

The ita matrix (optional).

acf : 2d-array

The acf for the data.

Returns:
bias : array

The bias on each of the parameters

AegeanTools.fitting.bias_correct(params, data, acf=None)[source]

Calculate and apply a bias correction to the given fit parameters

Parameters:
params : lmfit.Parameters

The model parameters. These will be modified.

data : 2d-array

The data which was used in the fitting

acf : 2d-array

ACF of the data. Default = None.

Returns:
None
AegeanTools.fitting.condon_errors(source, theta_n, psf=None)[source]

Calculate the parameter errors for a fitted source using the description of Condon‘97 All parameters are assigned errors, assuming that all params were fit. If some params were held fixed then these errors are overestimated.

Parameters:
source : AegeanTools.models.SimpleSource

The source which was fit.

theta_n : float or None

A measure of the beam sampling. (See Condon‘97).

psf : AegeanTools.fits_image.Beam

The psf at the location of the source.

Returns:
None
AegeanTools.fitting.covar_errors(params, data, errs, B, C=None)[source]

Take a set of parameters that were fit with lmfit, and replace the errors with the 1sigma errors calculated using the covariance matrix.

Parameters:
params : lmfit.Parameters

Model

data : 2d-array

Image data

errs : 2d-array ?

Image noise.

B : 2d-array

B matrix.

C : 2d-array

C matrix. Optional. If supplied then Bmatrix will not be used.

Returns:
params : lmfit.Parameters

Modified model.

AegeanTools.fitting.do_lmfit(data, params, B=None, errs=None, dojac=True)[source]

Fit the model to the data data may contain ‘flagged’ or ‘masked’ data with the value of np.NaN

Parameters:
data : 2d-array

Image data

params : lmfit.Parameters

Initial model guess.

B : 2d-array

B matrix to be used in residual calculations. Default = None.

errs : 1d-array
dojac : bool

If true then an analytic jacobian will be passed to the fitting routine.

Returns:
result : ?

lmfit.minimize result.

params : lmfit.Params

Fitted model.

AegeanTools.fitting.elliptical_gaussian(x, y, amp, xo, yo, sx, sy, theta)[source]

Generate a model 2d Gaussian with the given parameters. Evaluate this model at the given locations x,y.

Parameters:
x, y : numeric or array-like

locations at which to evaluate the gaussian

amp : float

Peak value.

xo, yo : float

Center of the gaussian.

sx, sy : float

major/minor axes in sigmas

theta : float

position angle (degrees) CCW from x-axis

Returns:
data : numeric or array-like

Gaussian function evaluated at the x,y locations.

AegeanTools.fitting.emp_hessian(pars, x, y)[source]

Calculate the hessian matrix empirically. Create a hessian matrix corresponding to the source model ‘pars’ Only parameters that vary will contribute to the hessian. Thus there will be a total of nvar x nvar entries, each of which is a len(x) x len(y) array.

Parameters:
pars : lmfit.Parameters

The model

x, y : list

locations at which to evaluate the Hessian

Returns:
h : np.array

Hessian. Shape will be (nvar, nvar, len(x), len(y))

Notes

Uses AegeanTools.fitting.emp_jacobian() to calculate the first order derivatives.

AegeanTools.fitting.emp_jacobian(pars, x, y)[source]

An empirical calculation of the Jacobian Will work for a model that contains multiple Gaussians, and for which some components are not being fit (don’t vary).

Parameters:
pars : lmfit.Model

The model parameters

x, y : list

Locations at which the jacobian is being evaluated

Returns:
j : 2d array

The Jacobian.

AegeanTools.fitting.errors(source, model, wcshelper)[source]

Convert pixel based errors into sky coord errors

Parameters:
source : AegeanTools.models.SimpleSource

The source which was fit.

model : lmfit.Parameters

The model which was fit.

wcshelper : AegeanTools.wcs_helpers.WCSHelper

WCS information.

Returns:
source : AegeanTools.models.SimpleSource

The modified source obejct.

AegeanTools.fitting.hessian(pars, x, y)[source]

Create a hessian matrix corresponding to the source model ‘pars’ Only parameters that vary will contribute to the hessian. Thus there will be a total of nvar x nvar entries, each of which is a len(x) x len(y) array.

Parameters:
pars : lmfit.Parameters

The model

x, y : list

locations at which to evaluate the Hessian

Returns:
h : np.array

Hessian. Shape will be (nvar, nvar, len(x), len(y))

AegeanTools.fitting.jacobian(pars, x, y)[source]

Analytical calculation of the Jacobian for an elliptical gaussian Will work for a model that contains multiple Gaussians, and for which some components are not being fit (don’t vary).

Parameters:
pars : lmfit.Model

The model parameters

x, y : list

Locations at which the jacobian is being evaluated

Returns:
j : 2d array

The Jacobian.

AegeanTools.fitting.lmfit_jacobian(pars, x, y, errs=None, B=None, emp=False)[source]

Wrapper around AegeanTools.fitting.jacobian() and AegeanTools.fitting.emp_jacobian() which gives the output in a format that is required for lmfit.

Parameters:
pars : lmfit.Model

The model parameters

x, y : list

Locations at which the jacobian is being evaluated

errs : list

a vector of 1sigma errors (optional). Default = None

B : 2d-array

a B-matrix (optional) see AegeanTools.fitting.Bmatrix()

emp : bool

If true the use the empirical Jacobian, otherwise use the analytical one. Default = False.

Returns:
j : 2d-array

A Jacobian.

AegeanTools.fitting.make_ita(noise, acf=None)[source]

Create the matrix ita of the noise where the noise may be a masked array where ita(x,y) is the correlation between pixel pairs that have the same separation as x and y.

Parameters:
noise : 2d-array

The noise image

acf : 2d-array

The autocorrelation matrix. (None = calculate from data). Default = None.

Returns:
ita : 2d-array

The matrix ita

AegeanTools.fitting.nan_acf(noise)[source]

Calculate the autocorrelation function of the noise where the noise is a 2d array that may contain nans

Parameters:
noise : 2d-array

Noise image.

Returns:
acf : 2d-array

The ACF.

AegeanTools.fitting.new_errors(source, model, wcshelper)[source]

Convert pixel based errors into sky coord errors Uses covariance matrix for ra/dec errors and calculus approach to a/b/pa errors

Parameters:
source : AegeanTools.models.SimpleSource

The source which was fit.

model : lmfit.Parameters

The model which was fit.

wcshelper : AegeanTools.wcs_helpers.WCSHelper

WCS information.

Returns:
source : AegeanTools.models.SimpleSource

The modified source obejct.

AegeanTools.fitting.ntwodgaussian_lmfit(params)[source]

Convert an lmfit.Parameters object into a function which calculates the model.

Parameters:
params : lmfit.Parameters

Model parameters, can have multiple components.

Returns:
model : func

A function f(x,y) that will compute the model.

flags

Flag constants for use by Aegean.

MIMAS

MIMAS - The Multi-resolution Image Mask for Aegean Software

TODO: Write an in/out reader for MOC formats described by http://arxiv.org/abs/1505.02937

class AegeanTools.MIMAS.Dummy(maxdepth=8)[source]

A state storage class for MIMAS to work with.

Attributes:
add_region : list

List of AegeanTools.MIMAS.Region to be added.

rem_region : list

List of AegeanTools.MIMAS.Region to be subtracted.

include_circles : [[ra, dec, radius],…]

List of circles to be added to the region, units are degrees.

exclude_circles : [[ra, dec, radius], …]

List of circles to be subtracted from the region, units are degrees.

include_polygons : [[ra,dec, …], …]

List of polygons to be added to the region, units are degrees.

exclude_polygons : [[ra,dec, …], …]

List of polygons to be subtracted from the region, units are degrees.

maxdepth : int

Depth or resolution of the region for HEALPix. There are 4*2**maxdepth pixels at the deepest layer. Default = 8.

galactic: bool

If true then all ra/dec coordinates will be interpreted as if they were in galactic lat/lon (degrees)

AegeanTools.MIMAS.box2poly(line)[source]

Convert a string that describes a box in ds9 format, into a polygon that is given by the corners of the box

Parameters:
line : str

A string containing a DS9 region command for a box.

Returns:
poly : [ra, dec, …]

The corners of the box in clockwise order from top left.

AegeanTools.MIMAS.circle2circle(line)[source]

Parse a string that describes a circle in ds9 format.

Parameters:
line : str

A string containing a DS9 region command for a circle.

Returns:
circle : [ra, dec, radius]

The center and radius of the circle.

AegeanTools.MIMAS.combine_regions(container)[source]

Return a region that is the combination of those specified in the container. The container is typically a results instance that comes from argparse.

Order of construction is: add regions, subtract regions, add circles, subtract circles, add polygons, subtract polygons.

Parameters:
container : AegeanTools.MIMAS.Dummy

The regions to be combined.

Returns:
region : AegeanTools.regions.Region

The constructed region.

AegeanTools.MIMAS.galactic2fk5(l, b)[source]

Convert galactic l/b to fk5 ra/dec

Parameters:
l, b : float

Galactic coordinates in radians.

Returns:
ra, dec : float

FK5 ecliptic coordinates in radians.

AegeanTools.MIMAS.intersect_regions(flist)[source]

Construct a region which is the intersection of all regions described in the given list of file names.

Parameters:
flist : list

A list of region filenames.

Returns:
region : AegeanTools.regions.Region

The intersection of all regions, possibly empty.

AegeanTools.MIMAS.mask_catalog(regionfile, infile, outfile, negate=False, racol='ra', deccol='dec')[source]

Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region If negate=False then remove the rows with ra/dec outside the region.

Parameters:
regionfile : str

A file which can be loaded as a AegeanTools.regions.Region. The catalogue will be masked according to this region.

infile : str

Input catalogue.

outfile : str

Output catalogue.

negate : bool

If True then pixels outside the region are masked. Default = False.

racol, deccol : str

The name of the columns in table that should be interpreted as ra and dec. Default = ‘ra’, ‘dec’

AegeanTools.MIMAS.mask_file(regionfile, infile, outfile, negate=False)[source]

Created a masked version of file, using a region.

Parameters:
regionfile : str

A file which can be loaded as a AegeanTools.regions.Region. The image will be masked according to this region.

infile : str

Input FITS image.

outfile : str

Output FITS image.

negate : bool

If True then pixels outside the region are masked. Default = False.

AegeanTools.MIMAS.mask_plane(data, wcs, region, negate=False)[source]

Mask a 2d image (data) such that pixels within ‘region’ are set to nan.

Parameters:
data : 2d-array

Image array.

wcs : astropy.wcs.WCS

WCS for the image in question.

region : AegeanTools.regions.Region

A region within which the image pixels will be masked.

negate : bool

If True then pixels outside the region are masked. Default = False.

Returns:
masked : 2d-array

The original array, but masked as required.

AegeanTools.MIMAS.mask_table(region, table, negate=False, racol='ra', deccol='dec')[source]

Apply a given mask (region) to the table, removing all the rows with ra/dec inside the region If negate=False then remove the rows with ra/dec outside the region.

Parameters:
region : AegeanTools.regions.Region

Region to mask.

table : Astropy.table.Table

Table to be masked.

negate : bool

If True then pixels outside the region are masked. Default = False.

racol, deccol : str

The name of the columns in table that should be interpreted as ra and dec. Default = ‘ra’, ‘dec’

Returns:
masked : Astropy.table.Table

A view of the given table which has been masked.

AegeanTools.MIMAS.mim2fits(mimfile, fitsfile)[source]

Convert a MIMAS region (.mim) file into a MOC region (.fits) file.

Parameters:
mimfile : str

Input file in MIMAS format.

fitsfile : str

Output file.

AegeanTools.MIMAS.mim2reg(mimfile, regfile)[source]

Convert a MIMAS region (.mim) file into a DS9 region (.reg) file.

Parameters:
mimfile : str

Input file in MIMAS format.

regfile : str

Output file.

AegeanTools.MIMAS.poly2poly(line)[source]

Parse a string of text containing a DS9 description of a polygon.

This function works but is not very robust due to the constraints of healpy.

Parameters:
line : str

A string containing a DS9 region command for a polygon.

Returns:
poly : [ra, dec, …]

The coordinates of the polygon.

AegeanTools.MIMAS.reg2mim(regfile, mimfile, maxdepth)[source]

Parse a DS9 region file and write a MIMAS region (.mim) file.

Parameters:
regfile : str

DS9 region (.reg) file.

mimfile : str

MIMAS region (.mim) file.

maxdepth : str

Depth/resolution of the region file.

AegeanTools.MIMAS.save_as_image(region, filename)[source]

Convert a MIMAS region (.mim) file into a image (eg .png)

Parameters:
region : AegeanTools.regions.Region

Region of interest.

filename : str

Output filename.

AegeanTools.MIMAS.save_region(region, filename)[source]

Save the given region to a file

Parameters:
region : AegeanTools.regions.Region

A region.

filename : str

Output file name.

models

Different types of sources that Aegean is able to fit

class AegeanTools.models.DummyLM[source]

A dummy copy of the lmfit results, for use when no fitting was done.

Attributes:
residual : [np.nan, np.nan]

The residual background and rms.

success: bool

False - the fitting has failed.

class AegeanTools.models.GlobalFittingData[source]

A class to hold the properties associated with an image. [ These were once in the global scope of a monolithic script, hence the name]. (should be) Read-only once created. Used by island fitting subprocesses.

Attributes:
img : AegeanTools.fits_image.FitsImage

Image that is being analysed, aka the input image.

dcurve : 2d-array

Image of +1,0,-1 representing the curvature of the input image.

rmsimg, bkgimg : 2d-array

The noise and background of the input image.

hdu_header : HDUHeader

FITS header for the input image.

beam : AegeanTools.fits_image.Beam

The synthesized beam of the input image.

data_pix : 2d-array

A link to the data array that is contained within the img.

dtype : {np.float32, np.float64}

The data type for the input image. Will be enforced upon writing.

region : AegeanTools.regions.Region

The region that will be used to limit the source finding of Aegean.

wcshelper : AegeanTools.wcs_helpers.WCSHelper

A helper object for WCS operations, created from hdu_header.

psfhelper : AegeanTools.wcs_helpers.PSFHelper

A helper objects for tracking the changes in PSF over the image.

blank : bool

If true, then the input image will be blanked at the location of each of the measured islands.

class AegeanTools.models.IslandFittingData(isle_num=0, i=None, scalars=None, offsets=(0, 0, 1, 1), doislandflux=False)[source]

All the data required to fit a single island. Instances are pickled and passed to the fitting subprocesses

Attributes:
isle_num : int

island number

i : 2d-array

a 2D numpy array of pixel values

scalars : (innerclip, outerclip, max_summits)

Inner and outer clipping limits (sigma), and the maximum number of components that should be fit.

offsets : (xmin, xmax, ymin, ymax)

The offset between the boundaries of the island i, within the larger image.

doislandflux : boolean

If true then also measure properties of the island.

class AegeanTools.models.IslandSource[source]

An island of pixels.

Attributes:
island: int

The island identification number

components : int

The number of components that make up this island.

background, local_rms : float

Background and local noise level in the image at the location of this source.

ra, dec : float

Sky location of the brightest pixel in this island. Decimal degrees.

ra_str, dec_str : str

Sky location in HH:MM:SS.SS +DD:MM:SS.SS format.

galactic : bool

If true then ra,dec are interpreted as glat,glon instead. Default = False. This is a class attribute, not an instance attribute.

peak_flux, peak_pixel : float

Value of the brightest pixel for this source.

int_flux, err_int_flux : float

Integrated flux and associated uncertainty.

x_width, y_width : int

The extent of the island in pixel space. The width is of the smallest bounding box.

max_angular_size : float

The maximum angular size of the island in sky coordinates (degrees).

pa : float

Position angle for the line representing the maximum angular size.

pixels : int

The number of pixels covered by this island.

area : float

The area of this island in sky coordinates (square degrees).

beam_area : float

The area of the synthesized beam of the image at the location of the brightest pixel. (square degrees).

eta : float

A factor that accounts for the difference between the integrated flux counted by summing pixels, and the integrated flux that would be produced by integrating an appropriately sized Gaussian.

extent : float
contour : list

A list of pixel coordinates that mark the pixel boundaries for this island of pixels.

max_angular_size_anchors : [x1, y1, x2, y2]

The end points of the vector that describes the maximum angular size of this island.

flags : int

Flags. See :module:`AegeanTools.flags`.

uuid : str

Unique ID for this source. This is random and not dependent on the source properties.

class AegeanTools.models.OutputSource[source]

A Gaussian component, aka a source, that was measured by Aegean.

Attributes:
island : int

The island which this component is part of.

source : int

The source number within the island.

background, local_rms : float

Background and local noise level in the image at the location of this source.

ra, err_ra, dec, err-dec : float

Sky location of the source including uncertainties. Decimal degrees.

ra_str, dec_str : str

Sky location in HH:MM:SS.SS +DD:MM:SS.SS format.

galactic : bool

If true then ra,dec are interpreted as glat,glon instead. Default = False. This is a class attribute, not an instance attribute.

peak_flux, err_peak_flux : float

The peak flux and associated uncertainty.

int_flux, err_int_flux : float

Integrated flux and associated uncertainty.

a, err_a, b, err_b, pa, err_pa: float

Shape parameters for this source and associated uncertainties. a/b are in arcsec, pa is in degrees East of North.

residual_mean, residual_std : float

The mean and standard deviation of the model-data for this island of pixels.

psf_a, psf_b, psf_pa : float

The shape parameters for the point spread function (degrees).

flags : int

Flags. See :module:`AegeanTools.flags`.

uuid : str

Unique ID for this source. This is random and not dependent on the source properties.

class AegeanTools.models.SimpleSource[source]

The base source class for an elliptical Gaussian.

Attributes:
background, local_rms : float

Background and local noise level in the image at the location of this source.

ra, dec : float

Sky location of this source. Decimal degrees.

galactic : bool

If true then ra,dec are interpreted as glat,glon instead. Default = False. This is a class attribute, not an instance attribute.

peak_flux, err_peak_flux : float

The peak flux value and associated uncertainty.

peak_pixel : float

Value of the brightest pixel for this source.

flags : int

Flags. See :module:`AegeanTools.flags`.

a, b, pa : float

Shape parameters for this source.

uuid : str

Unique ID for this source. This is random and not dependent on the source properties.

as_list()[source]

Return an ordered list of the source attributes

AegeanTools.models.classify_catalog(catalog)[source]

Look at a list of sources and split them according to their class.

Parameters:
catalog : iterable

A list or iterable object of {SimpleSource, IslandSource, OutputSource} objects, possibly mixed. Any other objects will be silently ignored.

Returns:
components : list

List of sources of type OutputSource

islands : list

List of sources of type IslandSource

simples : list

List of source of type SimpleSource

AegeanTools.models.island_itergen(catalog)[source]

Iterate over a catalog of sources, and return an island worth of sources at a time. Yields a list of components, one island at a time

Parameters:
catalog : iterable

A list or iterable of AegeanTools.models.OutputSource objects.

Yields:
group : list

A list of all sources within an island, one island at a time.

msq2

Provie a class which performs the marching squares algorithm on an image. The desired output is a set of regions / contours.

class AegeanTools.msq2.MarchingSquares(data)[source]

Implementation of a marching squares algorithm. With reference to http://devblog.phillipspiess.com/2010/02/23/better-know-an-algorithm-1-marching-squares/ but written in python

do_march()[source]

March about and trace the outline of our object

Returns:
perimeter : list

The pixels on the perimeter of the region [[x1, y1], …]

do_march_all()[source]

Recursive march in the case that we have a fragmented shape.

Returns:
perimeters : [perimeter1, …]

The perimeters of all the regions in the image.

find_start_point()[source]

Find the first location in our array that is not empty

solid(x, y)[source]

Determine whether the pixel x,y is nonzero

Parameters:
x, y : int

The pixel of interest.

Returns:
solid : bool

True if the pixel is not zero.

step(x, y)[source]

Move from the current location to the next

Parameters:
x, y : int

The current location

walk_perimeter(startx, starty)[source]

Starting at a point on the perimeter of a region, ‘walk’ the perimeter to return to the starting point. Record the path taken.

Parameters:
startx, starty : int

The starting location. Assumed to be on the perimeter of a region.

Returns:
perimeter : list

A list of pixel coordinates [ [x1,y1], …] that constitute the perimeter of the region.

regions

Describe sky areas as a collection of HEALPix pixels

class AegeanTools.regions.Region(maxdepth=11)[source]

A Region object represents a footprint on the sky. This is done in a way similar to a MOC. The region is stored as a list of healpix pixels, allowing for binary set-like operations.

Attributes:
maxdepth : int

The depth or resolution of the region. At the deepest level there will be 4*2**maxdepth pixels on the sky. Default = 11

pixeldict : dict

A dictionary of sets, each set containing the pixels within the region. The sets are indexed by their layer number.

demoted : set

A representation of this region at the deepest layer.

add_circles(ra_cen, dec_cen, radius, depth=None)[source]

Add one or more circles to this region

Parameters:
ra_cen, dec_cen, radius : float or list

The center and radius of the circle or circles to add to this region.

depth : int

The depth at which the given circles will be inserted.

add_pixels(pix, depth)[source]

Add one or more HEALPix pixels to this region.

Parameters:
pix : int or iterable

The pixels to be added

depth : int

The depth at which the pixels are added.

add_poly(positions, depth=None)[source]

Add a single polygon to this region.

Parameters:
positions : [[ra, dec], …]

Positions for the vertices of the polygon. The polygon needs to be convex and non-intersecting.

depth : int

The deepth at which the polygon will be inserted.

get_area(degrees=True)[source]

Calculate the total area represented by this region.

Parameters:
degrees : bool

If True then return the area in square degrees, otherwise use steradians. Default = True.

Returns:
area : float

The area of the region.

get_demoted()[source]

Get a representation of this region at the deepest level.

Returns:
demoted : set

A set of pixels, at the highest resolution.

intersect(other)[source]

Combine with another Region by performing intersection on their pixlists.

Requires both regions to have the same maxdepth.

Parameters:
other : AegeanTools.regions.Region

The region to be combined.

classmethod load(mimfile)[source]

Create a region object from the given file.

Parameters:
mimfile : str

File to load.

Returns:
region : AegeanTools.regions.Region

A region object

static radec2sky(ra, dec)[source]

Convert [ra], [dec] to [(ra[0], dec[0]),….] and also ra,dec to [(ra,dec)] if ra/dec are not iterable

Parameters:
ra, dec : float or iterable

Sky coordinates

Returns:
sky : numpy.array

array of (ra,dec) coordinates.

save(mimfile)[source]

Save this region to a file

Parameters:
mimfile : str

File to write

static sky2ang(sky)[source]

Convert ra,dec coordinates to theta,phi coordinates ra -> phi dec -> theta

Parameters:
sky : numpy.array

Array of (ra,dec) coordinates. See AegeanTools.regions.Region.radec2sky()

Returns:
theta_phi : numpy.array

Array of (theta,phi) coordinates.

classmethod sky2vec(sky)[source]

Convert sky positions in to 3d-vectors on the unit sphere.

Parameters:
sky : numpy.array

Sky coordinates as an array of (ra,dec)

Returns:
vec : numpy.array

Unit vectors as an array of (x,y,z)

sky_within(ra, dec, degin=False)[source]

Test whether a sky position is within this region

Parameters:
ra, dec : float

Sky position.

degin : bool

If True the ra/dec is interpreted as degrees, otherwise as radians. Default = False.

Returns:
within : bool

True if the given position is within one of the region’s pixels.

symmetric_difference(other)[source]

Combine with another Region by performing the symmetric difference of their pixlists.

Requires both regions to have the same maxdepth.

Parameters:
other : AegeanTools.regions.Region

The region to be combined.

union(other, renorm=True)[source]

Add another Region by performing union on their pixlists.

Parameters:
other : AegeanTools.regions.Region

The region to be combined.

renorm : bool

Perform renormalisation after the operation? Default = True.

classmethod vec2sky(vec, degrees=False)[source]

Convert [x,y,z] vectors into sky coordinates ra,dec

Parameters:
vec : numpy.array

Unit vectors as an array of (x,y,z)

degrees
Returns:
sky : numpy.array

Sky coordinates as an array of (ra,dec)

without(other)[source]

Subtract another Region by performing a difference operation on their pixlists.

Requires both regions to have the same maxdepth.

Parameters:
other : AegeanTools.regions.Region

The region to be combined.

write_fits(filename, moctool='')[source]

Write a fits file representing the MOC of this region.

Parameters:
filename : str

File to write

moctool : str

String to be written to fits header with key “MOCTOOL”. Default = ‘’

write_reg(filename)[source]

Write a ds9 region file that represents this region as a set of diamonds.

Parameters:
filename : str

File to write

source_finder

The Aegean source finding program.

class AegeanTools.source_finder.SourceFinder(**kwargs)[source]

The Aegean source finding algorithm

Attributes:
global_data : AegeanTools.models.GlobalFittingData

State holder for properties.

sources : list

List of sources that have been found/measured.

log : logging.log

Logger to use. Default = None

estimate_lmfit_parinfo(data, rmsimg, curve, beam, innerclip, outerclip=None, offsets=(0, 0), max_summits=None)[source]

Estimates the number of sources in an island and returns initial parameters for the fit as well as limits on those parameters.

Parameters:
data : 2d-array

(sub) image of flux values. Background should be subtracted.

rmsimg : 2d-array

Image of 1sigma values

curve : 2d-array

Image of curvature values [-1,0,+1]

beam : AegeanTools.fits_image.Beam

The beam information for the image.

innerclip, outerclip : float

Inerr and outer level for clipping (sigmas).

offsets : (int, int)

The (x,y) offset of data within it’s parent image

max_summits : int

If not None, only this many summits/components will be fit. More components may be present in the island, but subsequent components will not have free parameters.

Returns:
model : lmfit.Parameters

The initial estimate of parameters for the components within this island.

find_sources_in_image(filename, hdu_index=0, outfile=None, rms=None, bkg=None, max_summits=None, innerclip=5, outerclip=4, cores=None, rmsin=None, bkgin=None, beam=None, doislandflux=False, nopositive=False, nonegative=False, mask=None, lat=None, imgpsf=None, blank=False, docov=True, cube_index=None)[source]

Run the Aegean source finder.

Parameters:
filename : str or HDUList

Image filename or HDUList.

hdu_index : int

The index of the FITS HDU (extension).

outfile : str

file for printing catalog (NOT a table, just a text file of my own design)

rms : float

Use this rms for the entire image (will also assume that background is 0)

max_summits : int

Fit up to this many components to each island (extras are included but not fit)

innerclip, outerclip : float

The seed (inner) and flood (outer) clipping level (sigmas).

cores : int

Number of CPU cores to use. None means all cores.

rmsin, bkgin : str or HDUList

Filename or HDUList for the noise and background images. If either are None, then it will be calculated internally.

beam : (major, minor, pa)

Floats representing the synthesised beam (degrees). Replaces whatever is given in the FITS header. If the FITS header has no BMAJ/BMIN then this is required.

doislandflux : bool

If True then each island will also be characterized.

nopositive, nonegative : bool

Whether to return positive or negative sources. Default nopositive=False, nonegative=True.

mask : str

The filename of a region file created by MIMAS. Islands outside of this region will be ignored.

lat : float

The latitude of the telescope (declination of zenith).

imgpsf : str or HDUList

Filename or HDUList for a psf image.

blank : bool

Cause the output image to be blanked where islands are found.

docov : bool

If True then include covariance matrix in the fitting process. (default=True)

cube_index : int

For image cubes, cube_index determines which slice is used.

Returns:
sources : list

List of sources found.

load_globals(filename, hdu_index=0, bkgin=None, rmsin=None, beam=None, verb=False, rms=None, bkg=None, cores=1, do_curve=True, mask=None, lat=None, psf=None, blank=False, docov=True, cube_index=None)[source]

Populate the global_data object by loading or calculating the various components

Parameters:
filename : str or HDUList

Main image which source finding is run on

hdu_index : int

HDU index of the image within the fits file, default is 0 (first)

bkgin, rmsin : str or HDUList

background and noise image filename or HDUList

beam : AegeanTools.fits_image.Beam

Beam object representing the synthsized beam. Will replace what is in the FITS header.

verb : bool

Verbose. Write extra lines to INFO level log.

rms, bkg : float

A float that represents a constant rms/bkg levels for the entire image. Default = None, which causes the rms/bkg to be loaded or calculated.

cores : int

Number of cores to use if different from what is autodetected.

do_curve : bool

If True a curvature map will be created, default=True.

mask : str or AegeanTools.regions.Region

filename or Region object

lat : float

Latitude of the observing telescope (declination of zenith)

psf : str or HDUList

Filename or HDUList of a psf image

blank : bool

True = blank output image where islands are found. Default = False.

docov : bool

True = use covariance matrix in fitting. Default = True.

cube_index : int

For an image cube, which slice to use.

priorized_fit_islands(filename, catalogue, hdu_index=0, outfile=None, bkgin=None, rmsin=None, cores=1, rms=None, bkg=None, beam=None, lat=None, imgpsf=None, catpsf=None, stage=3, ratio=None, outerclip=3, doregroup=True, docov=True, cube_index=None)[source]

Take an input catalog, and image, and optional background/noise images fit the flux and ra/dec for each of the given sources, keeping the morphology fixed

if doregroup is true the groups will be recreated based on a matching radius/probability. if doregroup is false then the islands of the input catalog will be preserved.

Multiple cores can be specified, and will be used.

Parameters:
filename : str or HDUList

Image filename or HDUList.

catalogue : str or list

Input catalogue file name or list of OutputSource objects.

hdu_index : int

The index of the FITS HDU (extension).

outfile : str

file for printing catalog (NOT a table, just a text file of my own design)

rmsin, bkgin : str or HDUList

Filename or HDUList for the noise and background images. If either are None, then it will be calculated internally.

cores : int

Number of CPU cores to use. None means all cores.

rms : float

Use this rms for the entire image (will also assume that background is 0)

beam : (major, minor, pa)

Floats representing the synthesised beam (degrees). Replaces whatever is given in the FITS header. If the FITS header has no BMAJ/BMIN then this is required.

lat : float

The latitude of the telescope (declination of zenith).

imgpsf : str or HDUList

Filename or HDUList for a psf image.

catpsf : str or HDUList

Filename or HDUList for the catalogue psf image.

stage : int

Refitting stage

ratio : float

If not None - ratio of image psf to catalog psf, otherwise interpret from catalogue or image if possible

innerclip, outerclip : float

The seed (inner) and flood (outer) clipping level (sigmas).

docov : bool

If True then include covariance matrix in the fitting process. (default=True)

cube_index : int

For image cubes, slice determines which slice is used.

Returns:
sources : list

List of sources measured.

result_to_components(result, model, island_data, isflags)[source]

Convert fitting results into a set of components

Parameters:
result : lmfit.MinimizerResult

The fitting results.

model : lmfit.Parameters

The model that was fit.

island_data : AegeanTools.models.IslandFittingData

Data about the island that was fit.

isflags : int

Flags that should be added to this island (in addition to those within the model)

Returns:
sources : list

A list of components, and islands if requested.

save_background_files(image_filename, hdu_index=0, bkgin=None, rmsin=None, beam=None, rms=None, bkg=None, cores=1, outbase=None)[source]

Generate and save the background and RMS maps as FITS files. They are saved in the current directly as aegean-background.fits and aegean-rms.fits.

Parameters:
image_filename : str or HDUList

Input image.

hdu_index : int

If fits file has more than one hdu, it can be specified here. Default = 0.

bkgin, rmsin : str or HDUList

Background and noise image filename or HDUList

beam : AegeanTools.fits_image.Beam

Beam object representing the synthsized beam. Will replace what is in the FITS header.

rms, bkg : float

A float that represents a constant rms/bkg level for the entire image. Default = None, which causes the rms/bkg to be loaded or calculated.

cores : int

Number of cores to use if different from what is autodetected.

outbase : str

Basename for output files.

save_image(outname)[source]

Save the image data. This is probably only useful if the image data has been blanked.

Parameters:
outname : str

Name for the output file.

AegeanTools.source_finder.check_cores(cores)[source]

Determine how many cores we are able to use. Return 1 if we are not able to make a queue via pprocess.

Parameters:
cores : int

The number of cores that are requested.

Returns:
cores : int

The number of cores available.

AegeanTools.source_finder.fix_shape(source)[source]

Ensure that a>=b for a given source object. If a<b then swap a/b and increment pa by 90. err_a/err_b are also swapped as needed.

Parameters:
source : object

any object with a/b/pa/err_a/err_b properties

AegeanTools.source_finder.get_aux_files(basename)[source]

Look for and return all the aux files that are associated witht this filename. Will look for: background (_bkg.fits) rms (_rms.fits) mask (.mim) catalogue (_comp.fits) psf map (_psf.fits)

will return filenames if they exist, or None where they do not.

Parameters:
basename : str

The name/path of the input image.

Returns:
aux : dict

Dict of filenames or None with keys (bkg, rms, mask, cat, psf)

AegeanTools.source_finder.pa_limit(pa)[source]

Position angle is periodic with period 180deg Constrain pa such that -90<pa<=90

Parameters:
pa : float

Initial position angle.

Returns:
pa : float

Rotate position angle.

AegeanTools.source_finder.scope2lat(telescope)[source]

Convert a telescope name into a latitude returns None when the telescope is unknown.

Parameters:
telescope : str

Acronym (name) of telescope, eg MWA.

Returns:
lat : float

The latitude of the telescope.

Notes

These values were taken from wikipedia so have varying precision/accuracy

AegeanTools.source_finder.theta_limit(theta)[source]

Angle theta is periodic with period pi. Constrain theta such that -pi/2<theta<=pi/2.

Parameters:
theta : float

Input angle.

Returns:
theta : float

Rotate angle.

wcs_helpers

This module contains two classes that provide WCS functions that are not part of the WCS toolkit, as well as some wrappers around the provided tools to make them a lot easier to use.

class AegeanTools.wcs_helpers.PSFHelper(psffile, wcshelper)[source]

An extension of the AegeanTools.wcs_helpers.WCSHelper class that also includes information about the point spread function over the sky.

This allows for the distinction between the point spread function (what a point source looks like) and the synthesized beam in an image. These two can differ at low radio frequencies when the ionosphere is not playing nice.

get_beam(ra, dec)[source]

Get the psf as a AegeanTools.fits_image.Beam object.

Parameters:
ra, dec : float

The sky position (degrees).

Returns:
beam : AegeanTools.fits_image.Beam

The psf at the given location.

get_beamarea_deg2(ra, dec)[source]

Calculate the area of the beam in square degrees.

Parameters:
ra, dec : float

The sky position (degrees).

Returns:
area : float

The area of the beam in square degrees.

get_beamarea_pix(ra, dec)[source]

Calculate the area of the beam in square pixels.

Parameters:
ra, dec : float

The sky position (degrees).

Returns:
area : float

The area of the beam in square pixels.

get_pixbeam(ra, dec)[source]

Get the psf at the location specified in pixel coordinates. The psf is also in pixel coordinates.

Parameters:
ra, dec : float

The sky position (degrees).

Returns:
a, b, pa : float

The psf semi-major axis (pixels), semi-minor axis (pixels), and rotation angle (degrees). If a psf is defined then it is the psf that is returned, otherwise the image restoring beam is returned.

get_pixbeam_pixel(x, y)[source]

Get the psf at the location specified in pixel coordinates. The psf is also in pixel coordinates.

Parameters:
x, y : float

The image position in pixels.

Returns:
a, b, pa : float

The psf semi-major axis (pixels), semi-minor axis (pixels), and rotation angle (degrees). If a psf is defined then it is the psf that is returned, otherwise the image restoring beam is returned.

get_psf_pix(ra, dec)[source]

Determine the local psf (a,b,pa) at a given sky location. The psf is in pixel coordinates.

Parameters:
ra, dec : float

The sky position (degrees).

Returns:
a, b, pa : float

The psf semi-major axis (pixels), semi-minor axis (pixels), and rotation angle (degrees). If a psf is defined then it is the psf that is returned, otherwise the image restoring beam is returned.

get_psf_sky(ra, dec)[source]

Determine the local psf at a given sky location. The psf is returned in degrees.

Parameters:
ra, dec : float

The sky position (degrees).

Returns:
a, b, pa : float

The psf semi-major axis, semi-minor axis, and position angle in (degrees). If a psf is defined then it is the psf that is returned, otherwise the image restoring beam is returned.

class AegeanTools.wcs_helpers.WCSHelper(wcs, beam, pixscale, refpix, lat=None)[source]

A wrapper around astropy.wcs that provides extra functionality, and hides the c/fortran indexing troubles.

Useful functions not provided by astropy.wcs

  • sky2pix/pix2sky functions for vectors and ellipses.
  • functions for calculating the beam in sky/pixel coords
  • the ability to change the beam according to dec-lat
classmethod from_file(filename, beam=None)[source]

Create a new WCSHelper class from a given fits file.

Parameters:
filename : string

The file to be read

beam : AegeanTools.fits_image.Beam or None

The synthesized beam. If the supplied beam is None then one is constructed form the header.

Returns:
obj : AegeanTools.wcs_helpers.WCSHelper

A helper object

classmethod from_header(header, beam=None, lat=None)[source]

Create a new WCSHelper class from the given header.

Parameters:
header : astropy.fits.HDUHeader or string

The header to be used to create the WCS helper

beam : AegeanTools.fits_image.Beam or None

The synthesized beam. If the supplied beam is None then one is constructed form the header.

lat : float

The latitude of the telescope.

Returns:
obj : AegeanTools.wcs_helpers.WCSHelper

A helper object.

get_beam(ra, dec)[source]

Determine the beam at the given sky location.

Parameters:
ra, dec : float

The sky coordinates at which the beam is determined.

Returns:
beam : AegeanTools.fits_image.Beam

A beam object, with a/b/pa in sky coordinates

get_beamarea_deg2(ra, dec)[source]

Calculate the area of the synthesized beam in square degrees.

Parameters:
ra, dec : float

The sky coordinates at which the calculation is made.

Returns:
area : float

The beam area in square degrees.

get_beamarea_pix(ra, dec)[source]

Calculate the beam area in square pixels.

Parameters:
ra, dec : float

The sky coordinates at which the calculation is made

dec
Returns:
area : float

The beam area in square pixels.

get_pixbeam(ra, dec)[source]

Determine the beam in pixels at the given location in sky coordinates.

Parameters:
ra , dec : float

The sly coordinates at which the beam is determined.

Returns:
beam : AegeanTools.fits_image.Beam

A beam object, with a/b/pa in pixel coordinates.

get_pixbeam_pixel(x, y)[source]

Determine the beam in pixels at the given location in pixel coordinates.

Parameters:
x , y : float

The pixel coordinates at which the beam is determined.

Returns:
beam : AegeanTools.fits_image.Beam

A beam object, with a/b/pa in pixel coordinates.

pix2sky(pixel)[source]

Convert pixel coordinates into sky coordinates.

Parameters:
pixel : (float, float)

The (x,y) pixel coordinates

Returns:
sky : (float, float)

The (ra,dec) sky coordinates in degrees

pix2sky_ellipse(pixel, sx, sy, theta)[source]

Convert an ellipse from pixel to sky coordinates.

Parameters:
pixel : (float, float)

The (x, y) coordinates of the center of the ellipse.

sx, sy : float

The major and minor axes (FHWM) of the ellipse, in pixels.

theta : float

The rotation angle of the ellipse (degrees). theta = 0 corresponds to the ellipse being aligned with the x-axis.

Returns:
ra, dec : float

The (ra, dec) coordinates of the center of the ellipse (degrees).

a, b : float

The semi-major and semi-minor axis of the ellipse (degrees).

pa : float

The position angle of the ellipse (degrees).

pix2sky_vec(pixel, r, theta)[source]

Given and input position and vector in pixel coordinates, calculate the equivalent position and vector in sky coordinates.

Parameters:
pixel : (int,int)

origin of vector in pixel coordinates

r : float

magnitude of vector in pixels

theta : float

angle of vector in degrees

Returns:
ra, dec : float

The (ra, dec) of the origin point (degrees).

r, pa : float

The magnitude and position angle of the vector (degrees).

sky2pix(pos)[source]

Convert sky coordinates into pixel coordinates.

Parameters:
pos : (float, float)

The (ra, dec) sky coordinates (degrees)

Returns:
pixel : (float, float)

The (x,y) pixel coordinates

sky2pix_ellipse(pos, a, b, pa)[source]

Convert an ellipse from sky to pixel coordinates.

Parameters:
pos : (float, float)

The (ra, dec) of the ellipse center (degrees).

a, b, pa: float

The semi-major axis, semi-minor axis and position angle of the ellipse (degrees).

Returns:
x,y : float

The (x, y) pixel coordinates of the ellipse center.

sx, sy : float

The major and minor axes (FWHM) in pixels.

theta : float

The rotation angle of the ellipse (degrees). theta = 0 corresponds to the ellipse being aligned with the x-axis.

sky2pix_vec(pos, r, pa)[source]

Convert a vector from sky to pixel coords. The vector has a magnitude, angle, and an origin on the sky.

Parameters:
pos : (float, float)

The (ra, dec) of the origin of the vector (degrees).

r : float

The magnitude or length of the vector (degrees).

pa : float

The position angle of the vector (degrees).

Returns:
x, y : float

The pixel coordinates of the origin.

r, theta : float

The magnitude (pixels) and angle (degrees) of the vector.

sky_sep(pix1, pix2)[source]

calculate the GCD sky separation (degrees) between two pixels.

Parameters:
pix1, pix2 : (float, float)

The (x,y) pixel coordinates for the two positions.

Returns:
dist : float

The distance between the two points (degrees).