imalign
A module that provides functions for “aligning” images: specifically, it
provides functions for computing corrections to image WCS so that
image catalogs “align” to the reference catalog on the sky.
- Authors:
Mihai Cara
- License:
- exception tweakwcs.imalign.NotEnoughCatalogs[source]
An exception class used to notify that an alignment routine does not have enough input catalogs to perform alignment.
- tweakwcs.imalign.align_wcs(wcscat, refcat=None, ref_tpwcs=None, enforce_user_order=True, expand_refcat=False, minobj=None, match=<tweakwcs.matchutils.XYXYMatch object>, fitgeom='general', nclip=3, sigma=(3.0, 'rmse'), clip_accum=False, group_bb_policy='auto')[source]
Align (groups of) image catalogs by adjusting the parameters of their WCS based on fits between matched sources in these catalogs and a reference catalog which may be automatically created from one of the input
wcscatcatalogs.Warning
This function modifies the
wcsattribute of each item in the inputwcscatlist!Upon completion, this function will add a field
'fit_info'to themetaattribute of the input WCS correctors (except of the one chosen as a reference catalog whenrefcatisNone) containing a dictionary describing matching and fit results. For a description of the items in this dictionary, seetweakwcs.wcsimage.WCSGroupCatalog.align_to_ref(). In addition to the status set byalign_to_ref(), this function may set status to'REFERENCE'for an input image used as a reference image when a reference catalog is not provided. In this case no other fields in the'fit_info'will be present because a reference image is not being aligned. When alignment failed, the reason for failure is provided after alignment status.Warning
Unless status in
'fit_info'is'SUCCESS', there is no guarantee that other fields in'fit_info'are present or valid. Therefore, it is advisable verify that status is'SUCCESS'before attempting to access other items, for example:>>> fit_info = wcscat[0].meta.get('fit_info') # noqa >>> if fit_info['status'] == 'SUCCESS': ... print("shifts: [{}, {}]".format(*fit_info['shift'])) ... else: ... print("tweak info not available for this image")
- Parameters:
wcscat (tweakwcs.correctors.WCSCorrector, list of tweakwcs.correctors.WCSCorrector) –
A list of all
WCSCorrector-derived WCS correctors whosemetadictionary must contain'catalog'item with a non-empty table value of typeastropy.table.Table. This catalog must contain'x'and'y'columns which indicate source coordinates (in pixels) in the associated image. An optional column in the catalog is the'weight'column, which when present, will be used in fitting. SeeNotessection for further details. In addition to'catalog', the following items in themetadictionary are recognized/supported:'name'and'group_id'.'name'is catalog’s name and it used to identify catalog during logging. If'name'value isNoneor not present at all in themetaof a catalog, the name of that catalog will reported as'Unknown'. Group ID that may be used for identifying catalogs that need to be aligned together.group_idmust be hashable. If'group_id'isNoneor not provided, each input WCS/catalog will be aligned individually.Note
Upon completion this function will add
'fit_info'item (a dictionary) to input object’smetadictionary. See Notes section for more details.Warning
This function modifies the WCS of
WCSCorrectorobjects by calling theirset_correction()method.refcat (astropy.table.Table, optional) – A reference source catalog. The catalog must contain
'RA'and'DEC'columns which indicate reference source world coordinates (in degrees). An optional column in the catalog is the'weight'column, which when present, will be used in fitting. SeeNotessection for further details.ref_tpwcs (WCSCorrector, None, optional) – A reference WCS of the type
WCSCorrectorthat provides the tangent plane in which matching will be performed and corrections will be defined. When not provided (i.e., set toNone), reference tangent plane will be defined from the firstWCSCorrectorobject in the re-ordered (ifenforce_user_orderwas set toTrue) input listwcscat.enforce_user_order (bool, optional) – Specifies whether images should be aligned in the order specified in the
fileinput parameter oralignshould optimize the order of alignment by intersection area of the images. Default value (True) will align images in the user specified order, except when some images cannot be aligned in which casealignwill optimize the image alignment order. Alignment order optimization is available only whenexpand_refcatisTrue.expand_refcat (bool, optional) –
Specifies whether to add new sources from just matched images to the reference catalog to allow next image to be matched against an expanded reference catalog. By delault, the reference catalog is not being expanded.
If
refcatis notNoneand contains an'id'column, then sources being added to the reference catalog will be assigned consecutive IDs that continue maximum ID in therefcat.If one desires to uniquely associate source in the expanded catalog to their original catalogs, it is recommended that one assign unique IDs to all sources in all input catalogs and in the reference catalog in a separate column such as
'uuid'.minobj (int, None, optional) – Minimum number of identified objects from each input image to use in matching objects from other images. If the default
Nonevalue is used thenalignwill automatically deternmine the minimum number of sources from the value of thefitgeomparameter.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.fitgeom ({'shift', 'rshift', '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
nclipis eitherNoneor 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'- seeiter_linear_fitfor more details.When
sigmais a single number, it must be a positive number and the default error estimate'rmse'is assumed.This parameter is ignored when
nclipis eitherNoneor 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
Truethe 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 whennclipis eitherNoneor 0.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 inputimages. An integer number will approximate the bounding box using convex hull if the number of inputimagesis exceeds the value ofgroup_bb_policyand it will switch to exact computations (using unions) otherwise.'auto'is the same as setting threshold to 50.
- Returns:
eff_refcat – Effective reference catalog used for aligning all images. Depending on the values of the input parameters
refcat,enforce_user_order, andexpand_refcat, effective reference catalog may be one of the input image catalogs, the originalrefcatcatalog, an expandedrefcatwith a combination of source positions from all input images.- Return type:
- Raises:
NotEnoughCatalogs – This exception is raised when there are not enough input catalogs to perform alignment. For example,
wcscatmust be a list of at least two correctors whenrefcatisNone, or be a single corrector when a reference catalog is provided viarefcat.
Notes
1. Weights:
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 either 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].Warning
When image catalogs contain optional
'weight'column, then all image catalogs in a group must contain this column.2.
'fit_info':Upon completion, this function will add
'fit_info'item (itself a dictionary) to input object’smetadictionary. If input objects areWCSCorrectorWCS correctors, thenWCSCorrector.meta['fit_info']will be set to a dictionary containing fit information.Note
For
WCSCorrectorthat are aligned in a group, the'matrix'and'shift'items in the'fit_info'dictionary may differ from the values of the same items inWCSCorrector.metadictionary. This is normal since WCS corrections (inWCSCorrector) are applied in the image’s WCS plane while fit may be performed in a slightly different tangent plane.
- tweakwcs.imalign.fit_wcs(refcat, imcat, corrector, ref_tpwcs=None, fitgeom='general', nclip=3, sigma=(3.0, 'rmse'), clip_accum=False, group_bb_policy='auto')[source]
“Tweak” a single image’s
WCSby fitting image catalog to a reference catalog. This is a simplified version ofalign_wcsthat does not perform matching and is limited to the fitting part.Note
Both reference and image catalogs must have been matched prior to calling
fit_wcs(). This means that the lengths of bothrefcatandimcatcatalogs must be equal and that coordinates with the same indices in both catalogs correspond to the same source.Warning
If
corrector.metadictionary contains'catalog'keyword, it will be ignored.- Parameters:
refcat (astropy.table.Table) – A reference source catalog. The catalog must contain
'RA'and'DEC'columns which indicate reference source world coordinates (in degrees). An optional column in the catalog is the'weight'column, which when present, will be used in fitting. SeeNotessection for further details.imcat (astropy.table.Table) – Source catalog associated with an image whose WCS needs to be aligned by fitting a linear transformation to
imcatsource positions so as to align them to the same sources from therefcatcatalog. Must contain'x'and'y'columns which indicate source coordinates (in pixels) in the associated image. An optional column in the catalog is the'weight'column, which when present, will be used in fitting. SeeNotessection for further details.corrector (WCSCorrector) – A
WCSassociated with the image from which the catalog was derived. ThisWCSCorrector-subclassed WCS corrector object must also define a tangent plane that will be used for fitting the two catalogs’ sources and in which WCS corrections will be applied.ref_tpwcs (WCSCorrector, None, optional) – A reference WCS of the type
WCSCorrectorthat provides the tangent plane in which matching will be performed and corrections will be defined. When not provided (i.e., set toNone), reference tangent plane will be the same as defined bycorrectorargument.fitgeom ({'shift', 'rshift', '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
nclipis eitherNoneor 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'- seeiter_linear_fitfor more details.When
sigmais a single number, it must be a positive number and the default error estimate'rmse'is assumed.This parameter is ignored when
nclipis eitherNoneor 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
Truethe 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 whennclipis eitherNoneor 0.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 inputimages. An integer number will approximate the bounding box using convex hull if the number of inputimagesis exceeds the value ofgroup_bb_policyand it will switch to exact computations (using unions) otherwise.'auto'is the same as setting threshold to 50.
- Returns:
twwcs – “Tweaked” (aligned)
WCSthat contains tangent-plane corrections so that reference and image catalog sources better align in the tangent plane and therefore on the sky as well.- Return type:
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 either 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].Upon successful completion, this function will set the
'fit_info'key value of themetaattribute of the returnedWCSCorrectorobject.'fit_info'is a dictionary with the following items:‘shift’: A
numpy.ndarraywith two components of the computed shift. Note: shift is in units of the tangent plane.‘matrix’: A
2x2numpy.ndarraywith the computed generalized rotation matrix.‘proper_rot’: Rotation angle (degree) as if the rotation is proper.
‘rot’: A tuple of
(rotx, roty)- the rotation angles with regard to theXandYaxes.‘<rot>’: Arithmetic mean of the angles of rotation around
XandYaxes.‘scale’: A tuple of
(sx, sy)- scale change in the direction of theXandYaxes.‘<scale>’: Geometric mean of scales
sxandsy.‘skew’: Computed skew.
‘proper’: a boolean indicating whether the rotation is proper.
‘fitgeom’: Fit geometry (allowed transformations) used for fitting data (to minimize residuals). This is copy of the input argument
fitgeom.‘center’: Center of rotation in the tangent plane of the computed linear transformations.
‘fitmask’: A boolean array indicating which source positions where used for fitting (
True) and which were clipped out (False). NOTE: For weighted fits, positions with zero weights are automatically excluded from the fits.‘eff_nclip’: Effective number of clipping iterations
‘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.
‘resids’: An array of residuals of the fit in the tangent plane.
NOTE: Only the residuals for the “valid” points are reported here. Therefore the length of this array may be smaller than the length of input arrays of positions.
‘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.