WCS¶

class
astropy.wcs.
WCS
(header=None, fobj=None, key=' ', minerr=0.0, relax=True, naxis=None, keysel=None, colsel=None, fix=True, translate_units='', _do_set=True)[source] [edit on github]¶ Bases:
astropy.wcs.WCSBase
WCS objects perform standard WCS transformations, and correct for SIP and distortion paper tablelookup transformations, based on the WCS keywords and supplementary data read from a FITS file.
Parameters: header : astropy.io.fits header object, Primary HDU, Image HDU, string, dictlike, or None, optional
If header is not provided or None, the object will be initialized to default values.
fobj : An astropy.io.fits file (hdulist) object, optional
It is needed when header keywords point to a distortion paper lookup table stored in a different extension.
key : str, optional
The name of a particular WCS transform to use. This may be either
' '
or'A'
'Z'
and corresponds to the"a"
part of theCTYPEia
cards. key may only be provided if header is also provided.minerr : float, optional
The minimum value a distortion correction must have in order to be applied. If the value of
CQERRja
is smaller than minerr, the corresponding distortion is not applied.relax : bool or int, optional
Degree of permissiveness:
True
(default): Admit all recognized informal extensions of the WCS standard.False
: Recognize only FITS keywords defined by the published WCS standard.int
: a bit field selecting specific extensions to accept. See Headerreading relaxation constants for details.
naxis : int or sequence, optional
keysel : sequence of flags, optional
A sequence of flags used to select the keyword types considered by wcslib. When
None
, only the standard image header keywords are considered (and the underlying wcspih() C function is called). To use binary table image array or pixel list keywords, keysel must be set.Each element in the list should be one of the following strings:
 ‘image’: Image header keywords
 ‘binary’: Binary table image array keywords
 ‘pixel’: Pixel list keywords
Keywords such as
EQUIna
orRFRQna
that are common to binary table image arrays and pixel lists (includingWCSNna
andTWCSna
) are selected by both ‘binary’ and ‘pixel’.colsel : sequence of int, optional
A sequence of table column numbers used to restrict the WCS transformations considered to only those pertaining to the specified columns. If
None
, there is no restriction.fix : bool, optional
When
True
(default), callfix
on the resulting object to fix any nonstandard uses in the header.FITSFixedWarning
Warnings will be emitted if any changes were made.translate_units : str, optional
Raises: MemoryError
Memory allocation failed.
ValueError
Invalid key.
KeyError
Key not found in FITS header.
ValueError
Lookup table distortion present in the header but fobj was not provided.
Notes
astropy.wcs supports arbitrary n dimensions for the core WCS (the transformations handled by WCSLIB). However, the distortion paper lookup table and SIP distortions must be two dimensional. Therefore, if you try to create a WCS object where the core WCS has a different number of dimensions than 2 and that object also contains a distortion paper lookup table or SIP distortion, a
ValueError
exception will be raised. To avoid this, consider using the naxis kwarg to select two dimensions from the core WCS.The number of coordinate axes in the transformation is not determined directly from the
NAXIS
keyword but instead from the highest of:NAXIS
keywordWCSAXESa
keyword The highest axis number in any parameterized WCS keyword. The keyvalue, as well as the keyword, must be syntactically valid otherwise it will not be considered.
If none of these keyword types is present, i.e. if the header only contains auxiliary WCS keywords for a particular coordinate representation, then no coordinate description is constructed for it.
The number of axes, which is set as the
naxis
member, may differ for different coordinate representations of the same image.When the header includes duplicate keywords, in most cases the last encountered is used.
set
is called immediately after construction, so any invalid keywords or transformations will be raised by the constructor, not when subsequently calling a transformation method.
Attributes Summary
axis_type_names
World names for each coordinate axis celestial
A copy of the current WCS with only the celestial axes included has_celestial
is_celestial
pixel_scale_matrix
Methods Summary
all_pix2world
(*args, **kwargs)Transforms pixel coordinates to world coordinates. all_world2pix
(*arg[, accuracy, maxiter, …])Transforms world coordinates to pixel coordinates, using numerical iteration to invert the full forward transformation all_pix2world
with complete distortion model.calc_footprint
([header, undistort, axes, center])Calculates the footprint of the image on the sky. copy
()Return a shallow copy of the object. deepcopy
()Return a deep copy of the object. det2im
(*args)Convert detector coordinates to image plane coordinates using distortion paper tablelookup correction. dropaxis
(dropax)Remove an axis from the WCS. fix
([translate_units, naxis])Perform the fix operations from wcslib, and warn about any changes it has made. footprint_to_file
([filename, color, width, …])Writes out a ds9 style regions file. get_axis_types
()Similar to self.wcsprm.axis_types
but provides the information in a more Pythonfriendly format.p4_pix2foc
(*args)Convert pixel coordinates to focal plane coordinates using distortion paper tablelookup correction. pix2foc
(*args)Convert pixel coordinates to focal plane coordinates using the SIP polynomial distortion convention and distortion paper tablelookup correction. printwcs
()reorient_celestial_first
()Reorient the WCS such that the celestial axes are first, followed by the spectral axis, followed by any others. sip_foc2pix
(*args)Convert focal plane coordinates to pixel coordinates using the SIP polynomial distortion convention. sip_pix2foc
(*args)Convert pixel coordinates to focal plane coordinates using the SIP polynomial distortion convention. slice
(view[, numpy_order])Slice a WCS instance using a Numpy slice. sub
(axes)Extracts the coordinate description for a subimage from a WCS
object.swapaxes
(ax0, ax1)Swap axes in a WCS. to_fits
([relax, key])Generate an astropy.io.fits.HDUList
object with all of the information stored in this object.to_header
([relax, key])Generate an astropy.io.fits.Header
object with the basic WCS and SIP information stored in this object.to_header_string
([relax])Identical to to_header
, but returns a string containing the header cards.wcs_pix2world
(*args, **kwargs)Transforms pixel coordinates to world coordinates by doing only the basic wcslib transformation. wcs_world2pix
(*args, **kwargs)Transforms world coordinates to pixel coordinates, using only the basic wcslib WCS transformation. Attributes Documentation

axis_type_names
¶ World names for each coordinate axis
Returns: A list of names along each axis

celestial
¶ A copy of the current WCS with only the celestial axes included

has_celestial
¶

is_celestial
¶

pixel_scale_matrix
¶
Methods Documentation

all_pix2world
(*args, **kwargs)[source] [edit on github]¶ Transforms pixel coordinates to world coordinates.
Performs all of the following in series:
 Detector to image plane correction (if present in the FITS file)
 SIP distortion correction (if present in the FITS file)
 distortion paper tablelookup correction (if present in the FITS file)
 wcslib “core” WCS transformation
Parameters: args : flexible
There are two accepted forms for the positional arguments:
 2 arguments: An N x naxis array of coordinates, and an origin.
 more than 2 arguments: An array for each axis, followed by an origin. These arrays must be broadcastable to one another.
Here, origin is the coordinate in the upper left corner of the image. In FITS and Fortran standards, this is 1. In Numpy and C standards this is 0.
For a transformation that is not twodimensional, the twoargument form must be used.
ra_dec_order : bool, optional
Returns: result : array
Returns the sky coordinates, in degrees. If the input was a single array and origin, a single array is returned, otherwise a tuple of arrays is returned.
Raises: MemoryError
Memory allocation failed.
SingularMatrixError
Linear transformation matrix is singular.
InconsistentAxisTypesError
Inconsistent or unrecognized coordinate axis types.
ValueError
Invalid parameter value.
ValueError
Invalid coordinate transformation parameters.
ValueError
x and ycoordinate arrays are not the same size.
InvalidTransformError
Invalid coordinate transformation parameters.
InvalidTransformError
Illconditioned coordinate transformation parameters.
Notes
The order of the axes for the result is determined by the
CTYPEia
keywords in the FITS header, therefore it may not always be of the form (ra, dec). Thelat
,lng
,lattyp
andlngtyp
members can be used to determine the order of the axes.

all_world2pix
(*arg, accuracy=1.0e4, maxiter=20, adaptive=False, detect_divergence=True, quiet=False)[source] [edit on github]¶ Transforms world coordinates to pixel coordinates, using numerical iteration to invert the full forward transformation
all_pix2world
with complete distortion model.Parameters: args : flexible
There are two accepted forms for the positional arguments:
 2 arguments: An N x naxis array of coordinates, and an origin.
 more than 2 arguments: An array for each axis, followed by an origin. These arrays must be broadcastable to one another.
Here, origin is the coordinate in the upper left corner of the image. In FITS and Fortran standards, this is 1. In Numpy and C standards this is 0.
For a transformation that is not twodimensional, the twoargument form must be used.
ra_dec_order : bool, optional
tolerance : float, optional (Default = 1.0e4)
Tolerance of solution. Iteration terminates when the iterative solver estimates that the “true solution” is within this many pixels current estimate, more specifically, when the correction to the solution found during the previous iteration is smaller (in the sense of the L2 norm) than
tolerance
.maxiter : int, optional (Default = 20)
Maximum number of iterations allowed to reach a solution.
quiet : bool, optional (Default = False)
Do not throw
NoConvergence
exceptions when the method does not converge to a solution with the required accuracy within a specified number of maximum iterations set bymaxiter
parameter. Instead, simply return the found solution.Returns: result : array
Returns the pixel coordinates. If the input was a single array and origin, a single array is returned, otherwise a tuple of arrays is returned.
Other Parameters: adaptive : bool, optional (Default = False)
Specifies whether to adaptively select only points that did not converge to a solution within the required accuracy for the next iteration. Default is recommended for HST as well as most other instruments.
Note
The
all_world2pix()
uses a vectorized implementation of the method of consecutive approximations (seeNotes
section below) in which it iterates over all input points regardless until the required accuracy has been reached for all input points. In some cases it may be possible that almost all points have reached the required accuracy but there are only a few of input data points for which additional iterations may be needed (this depends mostly on the characteristics of the geometric distortions for a given instrument). In this situation it may be advantageous to setadaptive
=True
in which caseall_world2pix()
will continue iterating only over the points that have not yet converged to the required accuracy. However, for the HST’s ACS/WFC detector, which has the strongest distortions of all HST instruments, testing has shown that enabling this option would lead to a about 50100% penalty in computational time (depending on specifics of the image, geometric distortions, and number of input points to be converted). Therefore, for HST and possibly instruments, it is recommended to setadaptive
=False
. The only danger in getting this setting wrong will be a performance penalty.Note
When
detect_divergence
isTrue
,all_world2pix()
will automatically switch to the adaptive algorithm once divergence has been detected.detect_divergence : bool, optional (Default = True)
Specifies whether to perform a more detailed analysis of the convergence to a solution. Normally
all_world2pix()
may not achieve the required accuracy if either thetolerance
ormaxiter
arguments are too low. However, it may happen that for some geometric distortions the conditions of convergence for the the method of consecutive approximations used byall_world2pix()
may not be satisfied, in which case consecutive approximations to the solution will diverge regardless of thetolerance
ormaxiter
settings.When
detect_divergence
isFalse
, these divergent points will be detected as not having achieved the required accuracy (without further details). In addition, ifadaptive
isFalse
then the algorithm will not know that the solution (for specific points) is diverging and will continue iterating and trying to “improve” diverging solutions. This may result inNaN
orInf
values in the return results (in addition to a performance penalties). Even whendetect_divergence
isFalse
,all_world2pix()
, at the end of the iterative process, will identify invalid results (NaN
orInf
) as “diverging” solutions and will raiseNoConvergence
unless thequiet
parameter is set toTrue
.When
detect_divergence
isTrue
,all_world2pix()
will detect points for which current correction to the coordinates is larger than the correction applied during the previous iteration if the requested accuracy has not yet been achieved. In this case, ifadaptive
isTrue
, these points will be excluded from further iterations and ifadaptive
isFalse
,all_world2pix()
will automatically switch to the adaptive algorithm. Thus, the reported divergent solution will be the latest converging solution computed immediately before divergence has been detected.Note
When accuracy has been achieved, small increases in current corrections may be possible due to rounding errors (when
adaptive
isFalse
) and such increases will be ignored.Note
Based on our testing using HST ACS/WFC images, setting
detect_divergence
toTrue
will incur about 520% performance penalty with the larger penalty corresponding toadaptive
set toTrue
. Because the benefits of enabling this feature outweigh the small performance penalty, especially whenadaptive
=False
, it is recommended to setdetect_divergence
toTrue
, unless extensive testing of the distortion models for images from specific instruments show a good stability of the numerical method for a wide range of coordinates (even outside the image itself).Note
Indices of the diverging inverse solutions will be reported in the
divergent
attribute of the raisedNoConvergence
exception object.Raises: NoConvergence
The method did not converge to a solution to the required accuracy within a specified number of maximum iterations set by the
maxiter
parameter. To turn off this exception, setquiet
toTrue
. Indices of the points for which the requested accuracy was not achieved (if any) will be listed in theslow_conv
attribute of the raisedNoConvergence
exception object.See
NoConvergence
documentation for more details.MemoryError
Memory allocation failed.
SingularMatrixError
Linear transformation matrix is singular.
InconsistentAxisTypesError
Inconsistent or unrecognized coordinate axis types.
ValueError
Invalid parameter value.
ValueError
Invalid coordinate transformation parameters.
ValueError
x and ycoordinate arrays are not the same size.
InvalidTransformError
Invalid coordinate transformation parameters.
InvalidTransformError
Illconditioned coordinate transformation parameters.
Notes
The order of the axes for the input world array is determined by the
CTYPEia
keywords in the FITS header, therefore it may not always be of the form (ra, dec). Thelat
,lng
,lattyp
, andlngtyp
members can be used to determine the order of the axes.Using the method of fixedpoint iterations approximations we iterate starting with the initial approximation, which is computed using the nondistortionaware
wcs_world2pix()
(or equivalent).The
all_world2pix()
function uses a vectorized implementation of the method of consecutive approximations and therefore it is highly efficient (>30x) when all data points that need to be converted from sky coordinates to image coordinates are passed at once. Therefore, it is advisable, whenever possible, to pass as input a long array of all points that need to be converted toall_world2pix()
instead of callingall_world2pix()
for each data point. Also see the note to theadaptive
parameter.Examples
>>> import astropy.io.fits as fits >>> import astropy.wcs as wcs >>> import numpy as np >>> import os
>>> filename = os.path.join(wcs.__path__[0], 'tests/data/j94f05bgq_flt.fits') >>> hdulist = fits.open(filename) >>> w = wcs.WCS(hdulist[('sci',1)].header, hdulist) >>> hdulist.close()
>>> ra, dec = w.all_pix2world([1,2,3], [1,1,1], 1) >>> print(ra) [ 5.52645627 5.52649663 5.52653698] >>> print(dec) [72.05171757 72.05171276 72.05170795] >>> radec = w.all_pix2world([[1,1], [2,1], [3,1]], 1) >>> print(radec) [[ 5.52645627 72.05171757] [ 5.52649663 72.05171276] [ 5.52653698 72.05170795]] >>> x, y = w.all_world2pix(ra, dec, 1) >>> print(x) [ 1.00000238 2.00000237 3.00000236] >>> print(y) [ 0.99999996 0.99999997 0.99999997] >>> xy = w.all_world2pix(radec, 1) >>> print(xy) [[ 1.00000238 0.99999996] [ 2.00000237 0.99999997] [ 3.00000236 0.99999997]] >>> xy = w.all_world2pix(radec, 1, maxiter=3, ... tolerance=1.0e10, quiet=False) Traceback (most recent call last): ... NoConvergence: 'WCS.all_world2pix' failed to converge to the requested accuracy. After 3 iterations, the solution is diverging at least for one input point.
>>> # Now try to use some diverging data: >>> divradec = w.all_pix2world([[1.0, 1.0], ... [10000.0, 50000.0], ... [3.0, 1.0]], 1) >>> print(divradec) [[ 5.52645627 72.05171757] [ 7.15976932 70.8140779 ] [ 5.52653698 72.05170795]]
>>> # First, turn detect_divergence on: >>> try: ... xy = w.all_world2pix(divradec, 1, maxiter=20, ... tolerance=1.0e4, adaptive=False, ... detect_divergence=True, ... quiet=False) ... except wcs.wcs.NoConvergence as e: ... print("Indices of diverging points: {0}" ... .format(e.divergent)) ... print("Indices of poorly converging points: {0}" ... .format(e.slow_conv)) ... print("Best solution:\n{0}".format(e.best_solution)) ... print("Achieved accuracy:\n{0}".format(e.accuracy)) Indices of diverging points: [1] Indices of poorly converging points: None Best solution: [[ 1.00000238e+00 9.99999965e01] [ 1.99441636e+06 1.44309097e+06] [ 3.00000236e+00 9.99999966e01]] Achieved accuracy: [[ 6.13968380e05 8.59638593e07] [ 8.59526812e+11 6.61713548e+11] [ 6.09398446e05 8.38759724e07]] >>> raise e Traceback (most recent call last): ... NoConvergence: 'WCS.all_world2pix' failed to converge to the requested accuracy. After 5 iterations, the solution is diverging at least for one input point.
>>> # This time turn detect_divergence off: >>> try: ... xy = w.all_world2pix(divradec, 1, maxiter=20, ... tolerance=1.0e4, adaptive=False, ... detect_divergence=False, ... quiet=False) ... except wcs.wcs.NoConvergence as e: ... print("Indices of diverging points: {0}" ... .format(e.divergent)) ... print("Indices of poorly converging points: {0}" ... .format(e.slow_conv)) ... print("Best solution:\n{0}".format(e.best_solution)) ... print("Achieved accuracy:\n{0}".format(e.accuracy)) Indices of diverging points: [1] Indices of poorly converging points: None Best solution: [[ 1.00000009 1. ] [ nan nan] [ 3.00000009 1. ]] Achieved accuracy: [[ 2.29417358e06 3.21222995e08] [ nan nan] [ 2.27407877e06 3.13005639e08]] >>> raise e Traceback (most recent call last): ... NoConvergence: 'WCS.all_world2pix' failed to converge to the requested accuracy. After 6 iterations, the solution is diverging at least for one input point.

calc_footprint
(header=None, undistort=True, axes=None, center=True)[source] [edit on github]¶ Calculates the footprint of the image on the sky.
A footprint is defined as the positions of the corners of the image on the sky after all available distortions have been applied.
Parameters: header :
Header
object, optionalUsed to get
NAXIS1
andNAXIS2
header and axes are mutually exclusive, alternative ways to provide the same information.undistort : bool, optional
If
True
, take SIP and distortion lookup table into accountaxes : length 2 sequence ints, optional
If provided, use the given sequence as the shape of the image. Otherwise, use the
NAXIS1
andNAXIS2
keywords from the header that was used to create thisWCS
object.center : bool, optional
If
True
use the center of the pixel, otherwise use the corner.Returns: coord : (4, 2) array of (x, y) coordinates.
The order is clockwise starting with the bottom left corner.

copy
()[source] [edit on github]¶ Return a shallow copy of the object.
Convenience method so user doesn’t have to import the
copy
stdlib module.

deepcopy
()[source] [edit on github]¶ Return a deep copy of the object.
Convenience method so user doesn’t have to import the
copy
stdlib module.

det2im
(*args)[source] [edit on github]¶ Convert detector coordinates to image plane coordinates using distortion paper tablelookup correction.
The output is in absolute pixel coordinates, not relative to
CRPIX
.Parameters: args : flexible
There are two accepted forms for the positional arguments:
 2 arguments: An N x 2 array of coordinates, and an origin.
 more than 2 arguments: An array for each axis, followed by an origin. These arrays must be broadcastable to one another.
Here, origin is the coordinate in the upper left corner of the image. In FITS and Fortran standards, this is 1. In Numpy and C standards this is 0.
Returns: result : array
Returns the pixel coordinates. If the input was a single array and origin, a single array is returned, otherwise a tuple of arrays is returned.
Raises: MemoryError
Memory allocation failed.
ValueError
Invalid coordinate transformation parameters.

dropaxis
(dropax)[source] [edit on github]¶ Remove an axis from the WCS.
Parameters: wcs :
WCS
The WCS with naxis to be chopped to naxis1
dropax : int
The index of the WCS to drop, counting from 0 (i.e., python convention, not FITS convention)
Returns: A new
WCS
instance with one axis fewer

fix
(translate_units='', naxis=None)[source] [edit on github]¶ Perform the fix operations from wcslib, and warn about any changes it has made.
Parameters: translate_units : str, optional
Specify which potentially unsafe translations of nonstandard unit strings to perform. By default, performs none.
Although
"S"
is commonly used to represent seconds, its translation to"s"
is potentially unsafe since the standard recognizes"S"
formally as Siemens, however rarely that may be used. The same applies to"H"
for hours (Henry), and"D"
for days (Debye).This string controls what to do in such cases, and is caseinsensitive.
 If the string contains
"s"
, translate"S"
to"s"
.  If the string contains
"h"
, translate"H"
to"h"
.  If the string contains
"d"
, translate"D"
to"d"
.
Thus
''
doesn’t do any unsafe translations, whereas'shd'
does all of them.naxis : int array[naxis], optional
Image axis lengths. If this array is set to zero or
None
, thencylfix
will not be invoked. If the string contains

footprint_to_file
(filename='footprint.reg', color='green', width=2, coordsys=None)[source] [edit on github]¶ Writes out a ds9 style regions file. It can be loaded directly by ds9.
Parameters: filename : str, optional
Output file name  default is
'footprint.reg'
color : str, optional
Color to use when plotting the line.
width : int, optional
Width of the region line.
coordsys : str, optional
Coordinate system. If not specified (default), the
radesys
value is used. For all possible values, see http://ds9.si.edu/doc/ref/region.html#RegionFileFormat

get_axis_types
()[source] [edit on github]¶ Similar to
self.wcsprm.axis_types
but provides the information in a more Pythonfriendly format.Returns: result : list of dicts
Returns a list of dictionaries, one for each axis, each containing attributes about the type of that axis.
Each dictionary has the following keys:
 ‘coordinate_type’:
 None: Nonspecific coordinate type.
 ‘stokes’: Stokes coordinate.
 ‘celestial’: Celestial coordinate (including
CUBEFACE
).  ‘spectral’: Spectral coordinate.
 ‘scale’:
 ‘linear’: Linear axis.
 ‘quantized’: Quantized axis (
STOKES
,CUBEFACE
).  ‘nonlinear celestial’: Nonlinear celestial axis.
 ‘nonlinear spectral’: Nonlinear spectral axis.
 ‘logarithmic’: Logarithmic axis.
 ‘tabular’: Tabular axis.
 ‘group’
 Group number, e.g. lookup table number
 ‘number’
 For celestial axes:
 0: Longitude coordinate.
 1: Latitude coordinate.
 2:
CUBEFACE
number.
 For lookup tables:
 the axis number in a multidimensional table.
 For celestial axes:
CTYPEia
in"43"
form with unrecognized algorithm code will generate an error. ‘coordinate_type’:

p4_pix2foc
(*args)[source] [edit on github]¶ Convert pixel coordinates to focal plane coordinates using distortion paper tablelookup correction.
The output is in absolute pixel coordinates, not relative to
CRPIX
.Parameters: args : flexible
There are two accepted forms for the positional arguments:
 2 arguments: An N x 2 array of coordinates, and an origin.
 more than 2 arguments: An array for each axis, followed by an origin. These arrays must be broadcastable to one another.
Here, origin is the coordinate in the upper left corner of the image. In FITS and Fortran standards, this is 1. In Numpy and C standards this is 0.
Returns: result : array
Returns the focal coordinates. If the input was a single array and origin, a single array is returned, otherwise a tuple of arrays is returned.
Raises: MemoryError
Memory allocation failed.
ValueError
Invalid coordinate transformation parameters.

pix2foc
(*args)[source] [edit on github]¶ Convert pixel coordinates to focal plane coordinates using the SIP polynomial distortion convention and distortion paper tablelookup correction.
The output is in absolute pixel coordinates, not relative to
CRPIX
.Parameters: args : flexible
There are two accepted forms for the positional arguments:
 2 arguments: An N x 2 array of coordinates, and an origin.
 more than 2 arguments: An array for each axis, followed by an origin. These arrays must be broadcastable to one another.
Here, origin is the coordinate in the upper left corner of the image. In FITS and Fortran standards, this is 1. In Numpy and C standards this is 0.
Returns: result : array
Returns the focal coordinates. If the input was a single array and origin, a single array is returned, otherwise a tuple of arrays is returned.
Raises: MemoryError
Memory allocation failed.
ValueError
Invalid coordinate transformation parameters.

printwcs
()[source] [edit on github]¶

reorient_celestial_first
()[source] [edit on github]¶ Reorient the WCS such that the celestial axes are first, followed by the spectral axis, followed by any others. Assumes at least celestial axes are present.

sip_foc2pix
(*args)[source] [edit on github]¶ Convert focal plane coordinates to pixel coordinates using the SIP polynomial distortion convention.
FITS WCS distortion paper table lookup distortion correction is not applied, even if that information existed in the FITS file that initialized this
WCS
object.Parameters: args : flexible
There are two accepted forms for the positional arguments:
 2 arguments: An N x 2 array of coordinates, and an origin.
 more than 2 arguments: An array for each axis, followed by an origin. These arrays must be broadcastable to one another.
Here, origin is the coordinate in the upper left corner of the image. In FITS and Fortran standards, this is 1. In Numpy and C standards this is 0.
Returns: result : array
Returns the pixel coordinates. If the input was a single array and origin, a single array is returned, otherwise a tuple of arrays is returned.
Raises: MemoryError
Memory allocation failed.
ValueError
Invalid coordinate transformation parameters.

sip_pix2foc
(*args)[source] [edit on github]¶ Convert pixel coordinates to focal plane coordinates using the SIP polynomial distortion convention.
The output is in pixel coordinates, relative to
CRPIX
.FITS WCS distortion paper table lookup correction is not applied, even if that information existed in the FITS file that initialized this
WCS
object. To correct for that, usepix2foc
orp4_pix2foc
.Parameters: args : flexible
There are two accepted forms for the positional arguments:
 2 arguments: An N x 2 array of coordinates, and an origin.
 more than 2 arguments: An array for each axis, followed by an origin. These arrays must be broadcastable to one another.
Here, origin is the coordinate in the upper left corner of the image. In FITS and Fortran standards, this is 1. In Numpy and C standards this is 0.
Returns: result : array
Returns the focal coordinates. If the input was a single array and origin, a single array is returned, otherwise a tuple of arrays is returned.
Raises: MemoryError
Memory allocation failed.
ValueError
Invalid coordinate transformation parameters.

slice
(view, numpy_order=True)[source] [edit on github]¶ Slice a WCS instance using a Numpy slice. The order of the slice should be reversed (as for the data) compared to the natural WCS order.
Parameters: view : tuple
A tuple containing the same number of slices as the WCS system. The
step
method, the third argument to a slice, is not presently supported.numpy_order : bool
Use numpy order, i.e. slice the WCS so that an identical slice applied to a numpy array will slice the array and WCS in the same way. If set to
False
, the WCS will be sliced in FITS order, meaning the first slice will be applied to the last numpy index but the first WCS axis.Returns: wcs_new :
WCS
A new resampled WCS axis

sub
(axes)[source] [edit on github]¶ Extracts the coordinate description for a subimage from a
WCS
object.The world coordinate system of the subimage must be separable in the sense that the world coordinates at any point in the subimage must depend only on the pixel coordinates of the axes extracted. In practice, this means that the
PCi_ja
matrix of the original image must not contain nonzero offdiagonal terms that associate any of the subimage axes with any of the nonsubimage axes.sub
can also add axes to a wcsprm object. The new axes will be created using the defaults set by the Wcsprm constructor which produce a simple, unnamed, linear axis with world coordinates equal to the pixel coordinate. These default values can be changed before invokingset
.Parameters: axes : int or a sequence.
 If an int, include the first N axes in their original order.
 If a sequence, may contain a combination of image axis numbers
(1relative) or special axis identifiers (see below). Order is
significant;
axes[0]
is the axis number of the input image that corresponds to the first axis in the subimage, etc. Use an axis number of 0 to create a new axis using the defaults.  If
0
,[]
orNone
, do a deep copy.
Coordinate axes types may be specified using either strings or special integer constants. The available types are:
'longitude'
/WCSSUB_LONGITUDE
: Celestial longitude'latitude'
/WCSSUB_LATITUDE
: Celestial latitude'cubeface'
/WCSSUB_CUBEFACE
: QuadcubeCUBEFACE
axis'spectral'
/WCSSUB_SPECTRAL
: Spectral axis'stokes'
/WCSSUB_STOKES
: Stokes axis'celestial'
/WCSSUB_CELESTIAL
: An alias for the combination of'longitude'
,'latitude'
and'cubeface'
.
Returns: new_wcs :
WCS
objectRaises: MemoryError
Memory allocation failed.
InvalidSubimageSpecificationError
Invalid subimage specification (no spectral axis).
NonseparableSubimageCoordinateSystem
Nonseparable subimage coordinate system.
Notes
Combinations of subimage axes of particular types may be extracted in the same order as they occur in the input image by combining the integer constants with the ‘binary or’ (

) operator. For example:wcs.sub([WCSSUB_LONGITUDE  WCSSUB_LATITUDE  WCSSUB_SPECTRAL])
would extract the longitude, latitude, and spectral axes in the same order as the input image. If one of each were present, the resulting object would have three dimensions.
For convenience,
WCSSUB_CELESTIAL
is defined as the combinationWCSSUB_LONGITUDE  WCSSUB_LATITUDE  WCSSUB_CUBEFACE
.The codes may also be negated to extract all but the types specified, for example:
wcs.sub([ WCSSUB_LONGITUDE, WCSSUB_LATITUDE, WCSSUB_CUBEFACE, (WCSSUB_SPECTRAL  WCSSUB_STOKES)])
The last of these specifies all axis types other than spectral or Stokes. Extraction is done in the order specified by
axes
, i.e. a longitude axis (if present) would be extracted first (viaaxes[0]
) and not subsequently (viaaxes[3]
). Likewise for the latitude and cubeface axes in this example.The number of dimensions in the returned object may be less than or greater than the length of
axes
. However, it will never exceed the number of axes in the input image.

swapaxes
(ax0, ax1)[source] [edit on github]¶ Swap axes in a WCS.
Parameters: wcs :
WCS
The WCS to have its axes swapped
ax0 : int
ax1 : int
The indices of the WCS to be swapped, counting from 0 (i.e., python convention, not FITS convention)
Returns: A new
WCS
instance with the same number of axes, but twoswapped

to_fits
(relax=False, key=None)[source] [edit on github]¶ Generate an
astropy.io.fits.HDUList
object with all of the information stored in this object. This should be logically identical to the input FITS file, but it will be normalized in a number of ways.See
to_header
for some warnings about the output produced.Parameters: relax : bool or int, optional
Degree of permissiveness:
False
(default): Write all extensions that are considered to be safe and recommended.True
: Write all recognized informal extensions of the WCS standard.int
: a bit field selecting specific extensions to write. See Headerwriting relaxation constants for details.
key : str
The name of a particular WCS transform to use. This may be either
' '
or'A'
'Z'
and corresponds to the"a"
part of theCTYPEia
cards.Returns: hdulist :
astropy.io.fits.HDUList

to_header
(relax=None, key=None)[source] [edit on github]¶ Generate an
astropy.io.fits.Header
object with the basic WCS and SIP information stored in this object. This should be logically identical to the input FITS file, but it will be normalized in a number of ways.Warning
This function does not write out FITS WCS distortion paper information, since that requires multiple FITS header data units. To get a full representation of everything in this object, use
to_fits
.Parameters: relax : bool or int, optional
Degree of permissiveness:
False
(default): Write all extensions that are considered to be safe and recommended.True
: Write all recognized informal extensions of the WCS standard.int
: a bit field selecting specific extensions to write. See Headerwriting relaxation constants for details.
If the
relax
keyword argument is not given and any keywords were omitted from the output, anAstropyWarning
is displayed. To override this, explicitly pass a value torelax
.key : str
The name of a particular WCS transform to use. This may be either
' '
or'A'
'Z'
and corresponds to the"a"
part of theCTYPEia
cards.Returns: header :
astropy.io.fits.Header
Notes
The output header will almost certainly differ from the input in a number of respects:
 The output header only contains WCSrelated keywords. In
particular, it does not contain syntacticallyrequired
keywords such as
SIMPLE
,NAXIS
,BITPIX
, orEND
.  Deprecated (e.g.
CROTAn
) or nonstandard usage will be translated to standard (this is partially dependent on whetherfix
was applied).  Quantities will be converted to the units used internally, basically SI with the addition of degrees.
 Floatingpoint quantities may be given to a different decimal precision.
 Elements of the
PCi_j
matrix will be written if and only if they differ from the unit matrix. Thus, if the matrix is unity then no elements will be written.  Additional keywords such as
WCSAXES
,CUNITia
,LONPOLEa
andLATPOLEa
may appear.  The original keycomments will be lost, although
to_header
tries hard to write meaningful comments.  Keyword order may be changed.

to_header_string
(relax=None)[source] [edit on github]¶ Identical to
to_header
, but returns a string containing the header cards.

wcs_pix2world
(*args, **kwargs)[source] [edit on github]¶ Transforms pixel coordinates to world coordinates by doing only the basic wcslib transformation.
No SIP or distortion paper table lookup correction is applied. To perform distortion correction, see
all_pix2world
,sip_pix2foc
,p4_pix2foc
, orpix2foc
.Parameters: args : flexible
There are two accepted forms for the positional arguments:
 2 arguments: An N x naxis array of coordinates, and an origin.
 more than 2 arguments: An array for each axis, followed by an origin. These arrays must be broadcastable to one another.
Here, origin is the coordinate in the upper left corner of the image. In FITS and Fortran standards, this is 1. In Numpy and C standards this is 0.
For a transformation that is not twodimensional, the twoargument form must be used.
ra_dec_order : bool, optional
Returns: result : array
Returns the world coordinates, in degrees. If the input was a single array and origin, a single array is returned, otherwise a tuple of arrays is returned.
Raises: MemoryError
Memory allocation failed.
SingularMatrixError
Linear transformation matrix is singular.
InconsistentAxisTypesError
Inconsistent or unrecognized coordinate axis types.
ValueError
Invalid parameter value.
ValueError
Invalid coordinate transformation parameters.
ValueError
x and ycoordinate arrays are not the same size.
InvalidTransformError
Invalid coordinate transformation parameters.
InvalidTransformError
Illconditioned coordinate transformation parameters.
Notes
The order of the axes for the result is determined by the
CTYPEia
keywords in the FITS header, therefore it may not always be of the form (ra, dec). Thelat
,lng
,lattyp
andlngtyp
members can be used to determine the order of the axes.

wcs_world2pix
(*args, **kwargs)[source] [edit on github]¶ Transforms world coordinates to pixel coordinates, using only the basic wcslib WCS transformation. No SIP or distortion paper table lookup transformation is applied.
Parameters: args : flexible
There are two accepted forms for the positional arguments:
 2 arguments: An N x naxis array of coordinates, and an origin.
 more than 2 arguments: An array for each axis, followed by an origin. These arrays must be broadcastable to one another.
Here, origin is the coordinate in the upper left corner of the image. In FITS and Fortran standards, this is 1. In Numpy and C standards this is 0.
For a transformation that is not twodimensional, the twoargument form must be used.
ra_dec_order : bool, optional
Returns: result : array
Returns the pixel coordinates. If the input was a single array and origin, a single array is returned, otherwise a tuple of arrays is returned.
Raises: MemoryError
Memory allocation failed.
SingularMatrixError
Linear transformation matrix is singular.
InconsistentAxisTypesError
Inconsistent or unrecognized coordinate axis types.
ValueError
Invalid parameter value.
ValueError
Invalid coordinate transformation parameters.
ValueError
x and ycoordinate arrays are not the same size.
InvalidTransformError
Invalid coordinate transformation parameters.
InvalidTransformError
Illconditioned coordinate transformation parameters.
Notes
The order of the axes for the input world array is determined by the
CTYPEia
keywords in the FITS header, therefore it may not always be of the form (ra, dec). Thelat
,lng
,lattyp
andlngtyp
members can be used to determine the order of the axes.