wcsimage

This module provides support for working with image footprints on the sky and source catalogs.

Authors:

Mihai Cara

License:

LICENSE

class tweakwcs.wcsimage.RefCatalog(catalog, name=None, footprint_tol=1.0)[source]

An object that holds a reference catalog and provides tools for coordinate convertions using reference WCS as well as catalog manipulation and expansion.

Parameters:
catalog: astropy.table.Table

Reference catalog.

Note

Reference catalogs (Table) must contain both 'RA' and 'DEC' columns.

name: str, None, optional

Name of the reference catalog.

footprint_tol: float, optional

Matching tolerance in arcsec. This is used to estimate catalog’s footprint when catalog contains only one or two sources.

calc_bounding_polygon()[source]

Calculate bounding polygon of the sources in the catalog.

calc_tanp_xy(tanplane_wcs)[source]

Compute x- and y-positions of the sources from the reference catalog in the tangent plane provided by the tanplane_wcs. This creates the following columns in the catalog’s table: 'TPx' and 'TPy'.

Parameters:
tanplane_wcs: WCSCorrector

A WCSCorrector object that will provide transformations to the tangent plane to which sources of this catalog a should be “projected”.

property catalog

Get/set image’s catalog.

expand_catalog(catalog)[source]

Expand current reference catalog with sources from another catalog.

If current catalog is empty, then the catalog being added will become the new reference catalog. In this case if the catalog does have id column, those ID values will be preserved. If the catalog does not contain an ID column, then the new IDs will be assigned in increasing order starting with 1.

If the existing reference catalog is not empty, then the IDs from the catalog being added will be discarded and new IDs will be assigned in the increasing order such as to continue the numbering of existing source positions in the reference catalog.

Parameters:
catalog: astropy.table.Table

A catalog of new sources to be added to the existing reference catalog. catalog must contain both 'RA' and 'DEC' columns.

intersection(wcsim)[source]

Compute intersection of this WCSImageCatalog object and another WCSImageCatalog, WCSGroupCatalog, RefCatalog, or SphericalPolygon object.

Parameters:
wcsim: WCSImageCatalog, WCSGroupCatalog, RefCatalog, SphericalPolygon

Another object that should be intersected with this WCSImageCatalog.

Returns:
polygon: SphericalPolygon

A SphericalPolygon that is the intersection of this WCSImageCatalog and wcsim.

intersection_area(wcsim)[source]

Calculate the area of the intersection polygon.

property name

Get/set RefCatalog object’s name.

property poly_area

Area of the bounding polygon (in srad).

property polygon

Get image’s (or catalog’s) bounding spherical polygon.

class tweakwcs.wcsimage.WCSGroupCatalog(images, name=None, bb_policy='auto')[source]

A class that holds together WCSImageCatalog image catalog objects whose relative positions are fixed and whose source catalogs should be fitted together to a reference catalog.

Parameters:
images: list of WCSImageCatalog

A list of WCSImageCatalog image catalogs.

name: str, None, optional

Name of the group.

bb_policy: int, {‘exact’, ‘auto’}

Describes how to compute the bounding polygon of the group. 'exact' will compute the exact union of bounding boxes of input images. An integer number will approximate the bounding box using convex hull if the number of input images is exceeds the value of bb_policy and it will switch to exact computations (using unions) otherwise. 'auto' is the same as setting threshold to 50.

align_to_ref(refcat, ref_tpwcs=None, match=None, minobj=None, fitgeom='rscale', nclip=3, sigma=(3.0, 'rmse'), clip_accum=False)[source]

Matches sources from the image catalog to the sources in the reference catalog, finds the affine transformation between matched sources, and adjusts images’ WCS according to this fit.

Upon successful return, this function will also set the following fields of the fit_info attribute of each member WCSImageCatalog object:

  • ‘fitgeom’: the value of the fitgeom argument

  • ‘eff_minobj’: effective value of the minobj parameter

  • ‘matrix’: computed rotation matrix

  • ‘shift’: shift (offset) along X- and Y-axis in units of the tangent plane coordinates.

  • ‘rot’: A tuple of (rotx, roty) - the rotation angles with regard to the X and Y axes.

  • ‘<rot>’: Arithmetic mean of the angles of rotation around X and Y axes.

  • ‘proper_rot’: rotation angle as if rotation is a proper rotation.

  • ‘proper’: Indicates whether the rotation is a proper rotation (boolean)

  • ‘scale’: A tuple of (sx, sy) - scale change in the direction of the X and Y axes.

  • ‘<scale>’: Geometric mean of scales sx and sy.

  • ‘skew’: Computed skew - an angle in the range [-180, 180).

  • ‘center’: Center of rotation in the tangent plane of the computed linear transformations.

  • ‘fitmask’: boolean array indicating (with True) sources used for fitting

  • ‘nmatches’ [when match is not None]: number of matched sources

  • ‘matched_ref_idx’ [when match is not None]: indices of the matched sources in the reference catalog

  • ‘matched_input_idx’ [when match is not None]: indices of the matched sources in the “input” catalog (the catalog from image to be aligned)

  • ‘fit_ref_idx’: indices of the sources from the reference catalog used for fitting (a subset of ‘matched_ref_idx’ indices, when match is not None, left after clipping iterations performed during fitting)

  • ‘fit_input_idx’: indices of the sources from the “input” (image) catalog used for fitting (a subset of ‘matched_input_idx’ indices, when match is not None, left after clipping iterations performed during fitting)

  • ‘rmse’: fit Root-Mean-Square Error in tangent plane coordinates of corrected image source positions from reference source positions.

  • ‘mae’: fit Mean Absolute Error in tangent plane coordinates of corrected image source positions from reference source positions.

  • ‘std’: Norm of the STandard Deviation of the residuals in tangent plane along each axis.

  • ‘fit_RA’: first (corrected) world coordinate of input source positions used in fitting.

  • ‘fit_DEC’: second (corrected) world coordinate of input source positions used in fitting.

  • ‘status’: Alignment status. Currently two possible status are possible 'SUCCESS' or 'FAILED: reason for failure'. When alignment failed, the reason for failure is provided after alignment status.

Note

A 'SUCCESS' status does not indicate a “good” alignment. It simply indicates that alignment algortithm has completed without errors. Use other fields to evaluate alignment: fit RMSE and MAE values, number of matched sources, etc.

Note

Many quantities in fit_info are in units of the tangent plane coordinates, e.g., shift, rmse, std, mae. See specific WCSCorrector in correctors for the units of the tangent plane.

Parameters:
refcat: RefCatalog

A RefCatalog object that contains a catalog of reference sources.

ref_tpwcs: WCSCorrector

A WCSCorrector object that defines a projection tangent plane to be used for matching and fitting during alignment.

match: MatchCatalogs, function, None, optional

A callable that takes two arguments: a reference catalog and an image catalog.

minobj: int, None, optional

Minimum number of identified objects from each input image to use in matching objects from other images. If the default None value is used then align will automatically deternmine the minimum number of sources from the value of the fitgeom parameter. This parameter is used to interrupt alignment process (catalog fitting, WCS “tweaking”) when the number of matched sources is smaller than the value of minobj in which case this method will return False.

fitgeom: {‘shift’, ‘rscale’, ‘general’}, optional

The fitting geometry to be used in fitting the matched object lists. This parameter is used in fitting the offsets, rotations and/or scale changes from the matched object lists. The ‘general’ fit geometry allows for independent scale and rotation for each axis. This parameter is ignored if match is False.

nclip: int, None, optional

Number (a non-negative integer) of clipping iterations in fit. Clipping will be turned off if nclip is either None or 0.

This parameter is ignored if match is False.

sigma: float, tuple of the form (float, str), optional

When a tuple is provided, first value (a positive number) indicates the number of “fit error estimates” to use for clipping. The second value (a string) indicates the statistic to be used for “fit error estimate”. Currently the following values are supported: 'rmse', 'mae', and 'std' - see iter_linear_fit for more details.

When sigma is a single number, it must be a positive number and the default error estimate 'rmse' is assumed.

This parameter is ignored when nclip is either None or 0 or when match is False.

clip_accum: bool, optional

Indicates whether or not to reset the list of “bad” (clipped out) sources after each clipping iteration. When set to True the list only grows with each iteration as “bad” positions never re-enter the pool of available position for the fit. By default the list of “bad” source positions is purged at each iteration. This parameter is ignored when nclip is either None or 0.

Returns:
bool

Returns True if the number of matched sources is larger or equal to minobj and all steps have been performed, including catalog fitting and WCS “tweaking”. If the number of matched sources is smaller than minobj, this function will return False.

apply_affine_to_wcs(ref_tpwcs, matrix, shift, meta=None)[source]

Applies a general affine transformation to the WCS.

bb_approx_threshold = 50
property bb_policy

Get/set WCSImageCatalog policy for switching to approximate computation of group’s bounding box.

calc_tanp_xy(tanplane_wcs)[source]

Compute x- and y-positions of the sources from the image catalog in the tangent plane. This creates the following columns in the catalog’s table: 'TPx' and 'TPy'.

Parameters:
tanplane_wcs: WCSCorrector

A WCSCorrector object that will provide transformations to the tangent plane to which sources of this catalog a should be “projected”.

property catalog

Get/set image’s catalog.

create_group_catalog()[source]

Combine member’s image catalogs into a single group’s catalog.

Returns:
group_catalog: astropy.table.Table

Combined group catalog.

fit2ref(refcat, tanplane_wcs, fitgeom='general', nclip=3, sigma=(3.0, 'rmse'), clip_accum=False)[source]

Perform linear fit of this group’s combined catalog to the reference catalog. When either/both group’s catalog or/and the reference catalog contain 'weight' column, weigted fitting will be performed. See Notes section for further details.

Parameters:
refcat: RefCatalog

A RefCatalog object that contains a catalog of reference sources.

tanplane_wcs: WCSCorrector

A WCSCorrector object that will provide transformations to the tangent plane to which sources of this catalog a should be “projected”.

fitgeom: {‘shift’, ‘rscale’, ‘general’}, optional

The fitting geometry to be used in fitting the matched object lists. This parameter is used in fitting the offsets, rotations and/or scale changes from the matched object lists. The ‘general’ fit geometry allows for independent scale and rotation for each axis.

nclip: int, None, optional

Number (a non-negative integer) of clipping iterations in fit. Clipping will be turned off if nclip is either None or 0.

sigma: float, tuple of the form (float, str), optional

When a tuple is provided, first value (a positive number) indicates the number of “fit error estimates” to use for clipping. The second value (a string) indicates the statistic to be used for “fit error estimate”. Currently the following values are supported: 'rmse', 'mae', and 'std' - see iter_linear_fit for more details.

When sigma is a single number, it must be a positive number and the default error estimate 'rmse' is assumed.

This parameter is ignored when nclip is either None or 0.

clip_accum: bool, optional

Indicates whether or not to reset the list of “bad” (clipped out) sources after each clipping iteration. When set to True the list only grows with each iteration as “bad” positions never re-enter the pool of available position for the fit. By default the list of “bad” source positions is purged at each iteration. This parameter is ignored when nclip is either None or 0.

Notes

When fitting image sources to reference catalog sources, we can specify which sources have higher weights. This can be done by assigning a “weight” to each source by specifying these values in the optional 'weight' column of either the reference catalog, image catalog, or both.

When weights are not provided, all sources are weighed equally. When only one of image or reference catalog weights are provided, the sources will be weighted with the specified weights. When both image and reference catalogs specify weights for the same sources, the two weights will be combined into a single weight as:

\[1/w = 1/w_i + 1/w_r\]

Warning

Keep in mind that when a group catalog is created from individual catalogs, weights of the group catalog are created by concatenating weights of individual catalogs. Therefore, for the weighting of groups of catalogs to work correctly, the weights of individual catalogs should be scaled in such a way that when individual catalogs are combined into a single “group catalog”, weights preserve their relative values.

For example, let’s say a group is formed from two individual catalogs. Let’s say first catalog contains four sources with equal weights [1,1,1,1] and the second catalog contains two sources with weights [1,1] then the group’s catalogs sources will also have equal weights [1,1,1,1,1,1]. However, if each individual catalog’s weights were normalized such that sum of all weights is 1, then group’s sources will be weighed unequally: [0.25,0.25,0.25,0.25,0.5,0.5].

get_matched_cat()[source]

Retrieve only those sources from the catalog that have been matched to the sources in the reference catalog.

get_unmatched_cat()[source]

Retrieve only those sources from the catalog that have not been matched to the sources in the reference catalog.

intersection(wcsim)[source]

Compute intersection of this WCSGroupCatalog object and another WCSImageCatalog, WCSGroupCatalog, or SphericalPolygon object.

Parameters:
wcsim: WCSImageCatalog, WCSGroupCatalog, SphericalPolygon

Another object that should be intersected with this WCSGroupCatalog.

Returns:
polygon: SphericalPolygon

A SphericalPolygon that is the intersection of this WCSGroupCatalog and wcsim.

intersection_area(wcsim)[source]

Calculate the area of the intersection polygon.

match2ref(refcat, match=None)[source]
Uses xyxymatch to cross-match sources between this catalog and

a reference catalog.

Parameters:
refcat: RefCatalog

A RefCatalog object that contains a catalog of reference sources as well as a valid reference WCS.

match: MatchCatalogs, function, None, optional

A callable that takes two arguments: a reference catalog and an image catalog. Both catalogs will have columns 'TPx' and 'TPy' that represent the source coordinates in some common (to both catalogs) coordinate system.

Returns:
nmatches: int

Number of found matches.

mref_idx: numpy.ndarray

Integer array indicating indices of sources in the reference catalog that were matched to sources in group’s catalog.

minput_idx: numpy.ndarray

Integer array indicating indices of sources in group’s catalog that were matched to sources in the reference catalog.

property name

Get/set WCSImageCatalog object’s name.

property poly_area

Area of the bounding polygon (in srad).

property polygon

Get image’s (or catalog’s) bounding spherical polygon.

recalc_catalog_radec()[source]

Recalculate RA and DEC of the sources in the catalog.

update_bounding_polygon()[source]

Recompute bounding polygons of the member images.

class tweakwcs.wcsimage.WCSImageCatalog(catalog, corrector, name=None, group_id=None, meta={})[source]

A class that holds information pertinent to an image WCS and a source catalog of the sources found in that image.

Warning

If tpwcs.meta dictionary contains any of the following keywords 'catalog', 'name', or 'group_id', they will be ignored without warning.

Parameters:
catalog: astropy.table.Table

Source catalog associated with an image. Must contain 'x' and 'y' columns which indicate source coordinates (in pixels) in the associated image.

corrector: WCSCorrector

WCSCorrector-derived tangent-plane WCS corrector object associated with the image from which the catalog was derived.

name: str, None, optional

Image catalog’s name. This is used to identify catalog during logging. If name is None, the name of this WCSImageCatalog object will be set to 'Unknown'.

group_id: hashable, None, optional

Group ID that may be used for identifying catalogs that need to be aligned together. group_id must be hashable.

meta: dict, optional

Additional information about image, catalog, and/or WCS to be stored (for convenience) within WCSImageCatalog object.

property bb_radec

Get a tuple of numpy.ndarray of RA and DEC of the vertices of the bounding polygon.

calc_bounding_polygon()[source]

Calculate bounding polygon of the image or of the sources in the catalog (if catalog was set).

property catalog

Get/set image’s catalog.

property corrector

Get WCSCorrector WCS.

det_to_tanp(x, y)[source]

Convert detector (pixel) coordinates to tangent plane coordinates.

det_to_world(x, y)[source]

Convert pixel coordinates to sky coordinates using full (i.e., including distortions) transformations.

property fit_info

Get fit information - a dictionary. This class sets only the 'status' field but fitting routines may set additional fields.

property fit_status

Get/Set fit status. This property is a shortcut to the 'status' key value in the fit_info dictionary. When the WCSImageCatalog object is created, fit_status is initially set to 'SKIPPED'. Alignment tools are reponsible for updating catalog’s fit status.

property group_id

Get/set WCSImageCatalog object’s group ID that may be used for identifying catalogs that need to be aligned together. group_id must be hashable.

intersection(wcsim)[source]

Compute intersection of this WCSImageCatalog object and another WCSImageCatalog, WCSGroupCatalog, or SphericalPolygon object.

Parameters:
wcsim: WCSImageCatalog, WCSGroupCatalog, SphericalPolygon

Another object that should be intersected with this WCSImageCatalog.

Returns:
polygon: SphericalPolygon

A SphericalPolygon that is the intersection of this WCSImageCatalog and wcsim.

intersection_area(wcsim)[source]

Calculate the area of the intersection polygon.

property name

Get/set catalog’s name. This is used to identify catalog during logging. Upon setting, the value will be converted to a str. When setting to None, the name will be set to 'Unknown'.

property poly_area

Area of the bounding polygon (in srad).

property polygon

Get image’s (or catalog’s) bounding spherical polygon.

tanp_to_det(x, y)[source]

Convert tangent plane coordinates to detector (pixel) coordinates.

tanp_to_world(x, y)[source]

Convert tangent plane coordinates to world coordinates.

property tpwcs

Deprecated since version 0.8.0: The tpwcs property is deprecated and may be removed in a future version.

Get WCSCorrector WCS.

world_to_det(ra, dec)[source]

Convert sky coordinates to image’s pixel coordinates using full (i.e., including distortions) transformations.

world_to_tanp(ra, dec)[source]

Convert tangent plane coordinates to detector (pixel) coordinates.

tweakwcs.wcsimage.convex_hull(x, y, wcs=None, min_separation=None)[source]

Computes the convex hull of a set of 2D points.

Implements Andrew’s monotone chain algorithm. The algorithm has O(n log n) complexity.

Credit: http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain

Parameters:
x: list, tuple, numpy.ndarray

An iterable sequence of x-coordinates of points.

y: list, tuple, numpy.ndarray

An iterable sequence of y-coordinates of points.

wcsfunction

A function that takes two arguments (x, y) and converts them to “world” coordinates. If provided, returned convex hull vertex coordnates will be in “world” coordinates.

min_separationNone, float

A non-negative number or None. When provided as a number, it specifies the minimum separation in both x and y coordinates between adjacent verices in the hull. Vertices too close to their neighbors will be removed. This operation is performed _before_ convertion to “world” coordinates. When min_separation is None, all vertices are kept.

Returns:
Output: list

A list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically smallest coordinates. When a coordinate conversion function is supplied via the wcs argument, the returned values are those of the converted vertex coordinates.