gwcs.wcs.WCS¶
- class gwcs.wcs.WCS(forward_transform, input_frame=None, output_frame=None, name=None)¶
Bases:
Pipeline,WCSAPIMixinBasic WCS class.
- Parameters:
forward_transform (
ForwardTransform) – The transform betweeninput_frameandoutput_frame. A list of (frame, transform) tuples whereframeis the starting frame andtransformis the transform from this frame to the next one oroutput_frame. The last tuple is (transform, None), where None indicates the end of the pipeline.input_frame (
str|CoordinateFrameProtocol|None, default:None) – A coordinates object or a string name.output_frame (
str|CoordinateFrameProtocol|None, default:None) – A coordinates object or a string name.
Attributes¶
The shape of the data that the WCS applies to as a tuple of length |
|
List of all the frame names in this WCS in their order in the pipeline |
|
Returns an ( |
|
Return the total backward transform if available - from output to input coordinate system. |
|
Return the bounding box of the pipeline. |
|
Return the forward transform of the pipeline. |
|
Return the input frame name of the pipeline. |
|
Returns a reference to the underlying low-level WCS object. |
|
Return the name for this WCS. |
|
Return the output frame name of the pipeline. |
|
Allow direct access to the raw pipeline steps. |
|
An iterable of strings describing the name for each pixel axis. |
|
The bounds (in pixel coordinates) inside which the WCS is defined, as a list with |
|
The number of axes in the pixel coordinate system. |
|
The shape of the data that the WCS applies to as a tuple of length |
|
Indicates whether Python objects are given in serialized form or as actual Python objects. |
|
The unit of the coordinates in the output coordinate system. |
|
An iterable of strings describing the name for each world axis. |
|
A dictionary giving information on constructing high-level objects for the world coordinates. |
|
A list with |
|
An iterable of strings describing the physical type for each world axis. |
|
An iterable of strings given the units of the world coordinates for each axis. |
|
The number of axes in the world coordinate system. |
- property WCS.array_shape: tuple[int, ...] | None¶
The shape of the data that the WCS applies to as a tuple of length
pixel_n_dim. If the WCS is valid in the context of a dataset with a particular shape, then this property can be used to store the shape of the data. This can be used for example if implementing slicing of WCS objects. This is an optional property, and it should returnNoneif a shape is not known or relevant. The shape should be given in(row, column)order (the convention for arrays in Python).
- property WCS.available_frames: list[str]¶
List of all the frame names in this WCS in their order in the pipeline
- property WCS.axis_correlation_matrix¶
Returns an (
world_n_dim,pixel_n_dim) matrix that indicates using booleans whether a given world coordinate depends on a given pixel coordinate. This defaults to a matrix where all elements areTruein the absence of any further information. For completely independent axes, the diagonal would beTrueand all other entriesFalse.
- property WCS.backward_transform: Model¶
Return the total backward transform if available - from output to input coordinate system.
- Raises:
NotImplementedError – An analytical inverse does not exist.
- property WCS.bounding_box: ModelBoundingBox | CompoundBoundingBox | None¶
Return the bounding box of the pipeline.
- property WCS.input_frame: CoordinateFrameProtocol¶
Return the input frame name of the pipeline.
- property WCS.low_level_wcs¶
Returns a reference to the underlying low-level WCS object.
- property WCS.output_frame: CoordinateFrameProtocol¶
Return the output frame name of the pipeline.
- property WCS.pixel_axis_names: tuple[str, ...]¶
An iterable of strings describing the name for each pixel axis.
- property WCS.pixel_bounds: tuple[tuple[float, float], ...] | None¶
The bounds (in pixel coordinates) inside which the WCS is defined, as a list with
pixel_n_dim(min, max)tuples. The bounds should be given in[(xmin, xmax), (ymin, ymax)]order. WCS solutions are sometimes only guaranteed to be accurate within a certain range of pixel values, for example when defining a WCS that includes fitted distortions. This is an optional property, and it should returnNoneif a shape is not known or relevant.
- property WCS.pixel_shape: tuple[int, ...] | None¶
The shape of the data that the WCS applies to as a tuple of length
pixel_n_dimin(x, y)order (where for an image,xis the horizontal coordinate andyis the vertical coordinate) (optional).If the WCS is valid in the context of a dataset with a particular shape, then this property can be used to store the shape of the data. This can be used for example if implementing slicing of WCS objects. This is an optional property, and it should return
Noneif a shape is neither known nor relevant.
- property WCS.serialized_classes: bool¶
Indicates whether Python objects are given in serialized form or as actual Python objects.
- property WCS.unit: tuple[Unit | None, ...] | None¶
The unit of the coordinates in the output coordinate system.
- property WCS.world_axis_names: tuple[str, ...]¶
An iterable of strings describing the name for each world axis.
- property WCS.world_axis_object_classes: WorldAxisObjectClasses¶
A dictionary giving information on constructing high-level objects for the world coordinates.
Each key of the dictionary is a string key from
world_axis_object_components, and each value is a tuple with three elements or four elements:The first element of the tuple must be a class or a string specifying the fully-qualified name of a class, which will specify the actual Python object to be created.
The second element, should be a tuple specifying the positional arguments required to initialize the class. If
world_axis_object_componentsspecifies that the world coordinates should be passed as a positional argument, this this tuple should includeNoneplaceholders for the world coordinates.The third tuple element must be a dictionary with the keyword arguments required to initialize the class.
Optionally, for advanced use cases, the fourth element (if present) should be a callable Python object that gets called instead of the class and gets passed the positional and keyword arguments. It should return an object of the type of the first element in the tuple.
Note that we don’t require the classes to be Astropy classes since there is no guarantee that Astropy will have all the classes to represent all kinds of world coordinates. Furthermore, we recommend that the output be kept as human-readable as possible.
The classes used here should have the ability to do conversions by passing an instance as the first argument to the same class with different arguments (e.g.
Time(Time(...), scale='tai')). This is a requirement for the implementation of the high-level interface.The second and third tuple elements for each value of this dictionary can in turn contain either instances of classes, or if necessary can contain serialized versions that should take the same form as the main classes described above (a tuple with three elements with the fully qualified name of the class, then the positional arguments and the keyword arguments). For low-level API objects implemented in Python, we recommend simply returning the actual objects (not the serialized form) for optimal performance. Implementations should either always or never use serialized classes to represent Python objects, and should indicate which of these they follow using the
serialized_classesattribute.See the document APE 14: A shared Python interface for World Coordinate Systems for examples.
- property WCS.world_axis_object_components: list[WorldAxisObjectComponent]¶
A list with
world_n_dimelements giving information on constructing high-level objects for the world coordinates.Each element of the list is a tuple with three items:
The first is a name for the world object this world array corresponds to, which must match the string names used in
world_axis_object_classes. Note that names might appear twice because two world arrays might correspond to a single world object (e.g. a celestial coordinate might have both “ra” and “dec” arrays, which correspond to a single sky coordinate object).The second element is either a string keyword argument name or a positional index for the corresponding class from
world_axis_object_classes.The third argument is a string giving the name of the property to access on the corresponding class from
world_axis_object_classesin order to get numerical values. Alternatively, this argument can be a callable Python object that takes a high-level coordinate object and returns the numerical values suitable for passing to the low-level WCS transformation methods.
See the document APE 14: A shared Python interface for World Coordinate Systems for examples.
- property WCS.world_axis_physical_types: tuple[str | None, ...] | None¶
An iterable of strings describing the physical type for each world axis. These should be names from the VO UCD1+ controlled Vocabulary (http://www.ivoa.net/documents/latest/UCDlist.html). If no matching UCD type exists, this can instead be
"custom:xxx", wherexxxis an arbitrary string. Alternatively, if the physical type is unknown/undefined, an element can beNone.
- property WCS.world_axis_units: tuple[str, ...]¶
An iterable of strings given the units of the world coordinates for each axis. The strings should follow the IVOA VOUnit standard (though as noted in the VOUnit specification document, units that do not follow this standard are still allowed, but just not recommended).
Methods¶
|
Convert array indices to world coordinates (represented by Astropy objects). |
|
Convert array indices to world coordinates. |
|
Attach a compound bounding box dictionary to the pipeline. |
|
Executes the forward transform. |
|
Return a new unique WCS by fixing inputs to constant values. |
|
Return the footprint in world coordinates. |
|
Return the frame object corresponding to the given frame name. |
|
Return a transform between two coordinate frames. |
|
This method tests if one or more of the input world coordinates are contained within forward transformation's image and that it maps to the domain of definition of the forward transformation. |
|
Insert a new frame into an existing pipeline. |
|
Insert a transform before (default) or after a coordinate frame. |
|
Invert coordinates from output frame to input frame using analytical or user-supplied inverse. |
|
Invert coordinates from output frame to input frame using numerical inverse. |
|
|
|
|
|
Return a pipeline between the two given frames. |
|
Convert pixel coordinates to world coordinates (represented by high-level objects). |
|
Convert pixel coordinates to world coordinates. |
|
Set/replace the transform between two coordinate frames. |
|
Construct a FITS WCS |
|
Construct a SIP-based approximation to the WCS for the axes corresponding to the |
|
Construct a FITS WCS |
|
Transform positions between two frames. |
|
Convert world coordinates (represented by Astropy objects) to array indices. |
|
Convert world coordinates to array indices. |
|
Convert world coordinates (represented by Astropy objects) to pixel coordinates. |
|
Convert world coordinates to pixel coordinates. |
- WCS.array_index_to_world(*index_arrays)¶
Convert array indices to world coordinates (represented by Astropy objects).
If a single high-level object is used to represent the world coordinates (i.e., if
len(wcs.world_axis_object_classes) == 1), it is returned as-is (not in a tuple/list), otherwise a tuple of high-level objects is returned. Seearray_index_to_world_valuesfor pixel indexing and ordering conventions.
- WCS.array_index_to_world_values(*index_arrays)¶
Convert array indices to world coordinates. This is the same as
pixel_to_world_valuesexcept that the indices should be given in(i, j)order, where for an imageiis the row andjis the column (i.e. the opposite order topixel_to_world_values).- Parameters:
index_arrays (
LowLevelInput)- Return type:
- WCS.attach_compound_bounding_box(cbbox, selector_args)¶
Attach a compound bounding box dictionary to the pipeline.
- WCS.evaluate(*args, with_bounding_box=True, fill_value=nan, **kwargs)¶
Executes the forward transform.
- Parameters:
args (
LowLevelInput) – Inputs in the input coordinate system, separate inputs for each dimension.with_bounding_box (
bool, default:True) – If True(default) values in the result which correspond to any of the inputs being outside the bounding_box are set tofill_value.fill_value (
float|number, default:nan) – Output value for inputs outside the bounding_box (default is np.nan).kwargs (dict) – Keyword arguments to be passed to the
forward_transformmodel.
- Return type:
- WCS.fix_inputs(fixed)¶
Return a new unique WCS by fixing inputs to constant values.
- Parameters:
fixed (
dict[str|int,LowLevelArray|Quantity|float|number]) – Keyword arguments with fixed values corresponding toself.selector.- Returns:
new_wcs – A new unique WCS corresponding to the values in
fixed.- Return type:
Self
Examples
>>> w = WCS(pipeline, selector={"spectral_order": [1, 2]}) >>> new_wcs = w.set_inputs(spectral_order=2) >>> new_wcs.inputs ("x", "y")
- WCS.footprint(bounding_box=None, center=False, axis_type=None)¶
Return the footprint in world coordinates.
- Parameters:
bounding_box (tuple) –
prop: bounding_box, given as(start, stop)per axis.center (bool) – If
Trueuse the center of the pixel, otherwise use the corner.axis_type (
AxisType|str|None, default:None) – A supportedoutput_frame.axes_typeor"all"(default). One of ['spatial','spectral','temporal'] or a custom type.
- Returns:
coord – Array of coordinates in the output_frame mapping corners to the output frame. For spatial coordinates the order is clockwise, starting from the bottom left corner.
- Return type:
ndarray
- WCS.get_frame(frame)¶
Return the frame object corresponding to the given frame name.
- Parameters:
frame (
str|CoordinateFrameProtocol) – Name of the frame or the frame object.- Returns:
The frame object corresponding to the given name.
- Return type:
- WCS.get_transform(from_frame, to_frame)¶
Return a transform between two coordinate frames.
- Parameters:
from_frame (
str|CoordinateFrameProtocol) – Initial coordinate frame name of object.to_frame (
str|CoordinateFrameProtocol) – End coordinate frame name or object.
- Returns:
Transform between two frames.
- Return type:
- WCS.in_image(*args, with_bounding_box=True, fill_value=nan, **kwargs)¶
This method tests if one or more of the input world coordinates are contained within forward transformation’s image and that it maps to the domain of definition of the forward transformation. In practical terms, this function tests that input world coordinate(s) can be converted to input frame and that it is within the forward transformation’s
bounding_boxwhen defined.- Parameters:
args (
LowLevelInput) – Coordinates to be inverted.kwargs (dict) – keyword arguments to be passed either to
backward_transform(when defined) or to the iterative invert method.with_bounding_box (
bool, default:True)
- Returns:
result – A single boolean value or an array of boolean values with
Trueindicating that the WCS footprint contains the coordinate andFalseif input is outside the footprint.- Return type:
- WCS.insert_frame(input_frame, transform, output_frame)¶
Insert a new frame into an existing pipeline. This frame must be anchored to a frame already in the pipeline by a transform. This existing frame is identified solely by its name, although an entire
CoordinateFrameProtocolcan be passed (e.g., theinput_frameoroutput_frameattribute). This frame is never modified.- Parameters:
input_frame (
str|CoordinateFrameProtocol) – Coordinate frame at start of new transformtransform (
Model) – New transform to be inserted in the pipelineoutput_frame (
str|CoordinateFrameProtocol) – Coordinate frame at end of new transform
- Return type:
- WCS.insert_transform(frame, transform, after=False)¶
Insert a transform before (default) or after a coordinate frame.
Append (or prepend) a transform to the transform connected to frame.
- Parameters:
frame (
str|CoordinateFrameProtocol) – Coordinate frame which sets the point of insertion.transform (
Model) – New transform to be inserted in the pipelineafter (
bool, default:False) – If True, the new transform is inserted in the pipeline immediately afterframe.
- Return type:
- WCS.invert(*args, with_bounding_box=True, fill_value=nan, **kwargs)¶
Invert coordinates from output frame to input frame using analytical or user-supplied inverse. When neither analytical nor user-supplied inverses are defined, a numerical solution will be attempted using
numerical_inverse().Note
Currently numerical inverse is implemented only for 2D imaging WCS.
- Parameters:
args (
LowLevelInput) – Coordinates to be inverted. The number of arguments must be equal to the number of world coordinates given byworld_n_dim.with_bounding_box (
bool, default:True) – IfTrue(default) values in the result which correspond to any of the inputs being outside the bounding_box are set tofill_value.fill_value (
float|number, default:nan) – Output value for inputs outside the bounding_box (default isnp.nan).kwargs (dict) – Keyword arguments to be passed to
numerical_inverse()(when defined) or to the iterative invert method.
- Returns:
result – Returns a tuple of scalar or array values for each axis. Unless
input_frame.naxes == 1when it shall return the value. The return type will beQuantityobjects if the transform returnsQuantityobjects, else values.- Return type:
- WCS.numerical_inverse(*args, tolerance=1e-05, maxiter=30, adaptive=True, detect_divergence=True, quiet=True, with_bounding_box=True, fill_value=nan, **kwargs)¶
Invert coordinates from output frame to input frame using numerical inverse.
Note
Currently numerical inverse is implemented only for 2D imaging WCS.
Note
This method uses a combination of vectorized fixed-point iterations algorithm and
scipy.optimize.root. The later is used for input coordinates for which vectorized algorithm diverges.- Parameters:
args (float, array like,
SkyCoordorUnit) – Coordinates to be inverted. The number of arguments must be equal to the number of world coordinates given byworld_n_dim.with_bounding_box (bool, optional) – If
True(default) values in the result which correspond to any of the inputs being outside the bounding_box are set tofill_value.fill_value (float, optional) – Output value for inputs outside the bounding_box (default is
np.nan).tolerance (float, optional) – Absolute 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. Defaulttoleranceis 1.0e-5.maxiter (int, optional) – Maximum number of iterations allowed to reach a solution. Default is 50.
quiet (bool, optional) – Do not throw
NoConvergenceexceptions when the method does not converge to a solution with the required accuracy within a specified number of maximum iterations set bymaxiterparameter. Instead, simply return the found solution. Default isTrue.adaptive (bool, optional) –
Specifies whether to adaptively select only points that did not converge to a solution within the required accuracy for the next iteration. Default (
True) is recommended.Note
The
numerical_inverse()uses a vectorized implementation of the method of consecutive approximations (seeNotessection 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=Truein which casenumerical_inverse()will continue iterating only over the points that have not yet converged to the required accuracy.Note
When
detect_divergenceisTrue,numerical_inverse()will automatically switch to the adaptive algorithm once divergence has been detected.detect_divergence (bool, optional) –
Specifies whether to perform a more detailed analysis of the convergence to a solution. Normally
numerical_inverse()may not achieve the required accuracy if either thetoleranceormaxiterarguments are too low. However, it may happen that for some geometric distortions the conditions of convergence for the the method of consecutive approximations used bynumerical_inverse()may not be satisfied, in which case consecutive approximations to the solution will diverge regardless of thetoleranceormaxitersettings.When
detect_divergenceisFalse, these divergent points will be detected as not having achieved the required accuracy (without further details). In addition, ifadaptiveisFalsethen 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 inNaNorInfvalues in the return results (in addition to a performance penalties). Even whendetect_divergenceisFalse,numerical_inverse(), at the end of the iterative process, will identify invalid results (NaNorInf) as “diverging” solutions and will raiseNoConvergenceunless thequietparameter is set toTrue.When
detect_divergenceisTrue(default),numerical_inverse()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, ifadaptiveisTrue, these points will be excluded from further iterations and ifadaptiveisFalse,numerical_inverse()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
adaptiveisFalse) and such increases will be ignored.Note
Based on our testing using JWST NIRCAM images, setting
detect_divergencetoTruewill incur about 5-10% performance penalty with the larger penalty corresponding toadaptiveset toTrue. Because the benefits of enabling this feature outweigh the small performance penalty, especially whenadaptive=False, it is recommended to setdetect_divergencetoTrue, 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
divergentattribute of the raisedNoConvergenceexception object.
- Returns:
result – Returns a tuple of scalar or array values for each axis.
- Return type:
- Raises:
NoConvergence – The iterative method did not converge to a solution to the required accuracy within a specified number of maximum iterations set by the
maxiterparameter. To turn off this exception, setquiettoTrue. Indices of the points for which the requested accuracy was not achieved (if any) will be listed in theslow_convattribute of the raisedNoConvergenceexception object. SeeNoConvergencedocumentation for more details.NotImplementedError – Numerical inverse has not been implemented for this WCS.
ValueError – Invalid argument values.
Examples
>>> from astropy.utils.data import get_pkg_data_filename >>> from gwcs import NoConvergence >>> import asdf >>> import numpy as np
>>> filename = get_pkg_data_filename('data/nircamwcs.asdf', package='gwcs.tests') >>> with asdf.open(filename, lazy_load=False, ignore_missing_extensions=True) as af: ... w = af.tree['wcs']
>>> ra, dec = w([1,2,3], [1,1,1]) >>> assert np.allclose(ra, [5.927628, 5.92757069, 5.92751337]); >>> assert np.allclose(dec, [-72.01341247, -72.01341273, -72.013413])
>>> x, y = w.numerical_inverse(ra, dec) >>> assert np.allclose(x, [1.00000005, 2.00000005, 3.00000006]); >>> assert np.allclose(y, [1.00000004, 0.99999979, 1.00000015]);
>>> x, y = w.numerical_inverse(ra, dec, maxiter=3, tolerance=1.0e-10, quiet=False) Traceback (most recent call last): ... gwcs.wcs._exception.NoConvergence: 'WCS.numerical_inverse' failed to converge to the requested accuracy after 3 iterations.
>>> w.numerical_inverse( ... *w([1, 300000, 3], [2, 1000000, 5], with_bounding_box=False), ... adaptive=False, ... detect_divergence=True, ... quiet=False, ... with_bounding_box=False ... ) Traceback (most recent call last): ... gwcs.wcs._exception.NoConvergence: 'WCS.numerical_inverse' failed to converge to the requested accuracy. After 4 iterations, the solution is diverging at least for one input point.
>>> # Now try to use some diverging data: >>> divra, divdec = w([1, 300000, 3], [2, 1000000, 5], with_bounding_box=False) >>> assert np.allclose(divra, [5.92762673, 148.21600848, 5.92750827]) >>> assert np.allclose(divdec, [-72.01339464, -7.80968079, -72.01334172]) >>> try: ... x, y = w.numerical_inverse(divra, divdec, maxiter=20, ... tolerance=1.0e-4, adaptive=True, ... detect_divergence=True, ... quiet=False) ... except NoConvergence as e: ... print(f"Indices of diverging points: {e.divergent}") ... print(f"Indices of poorly converging points: {e.slow_conv}") ... print(f"Best solution:\n{e.best_solution}") ... print(f"Achieved accuracy:\n{e.accuracy}") Indices of diverging points: None Indices of poorly converging points: [1] Best solution: [[1.00000040e+00 1.99999841e+00] [6.33507833e+17 3.40118820e+17] [3.00000038e+00 4.99999841e+00]] Achieved accuracy: [[2.75925982e-05 1.18471543e-05] [3.65405005e+04 1.31364188e+04] [2.76552923e-05 1.14789013e-05]]
- WCS.out_of_bounds(pixel_arrays, fill_value=nan)¶
- WCS.outside_footprint(world_arrays)¶
- WCS.pipeline_between(from_frame, to_frame)¶
Return a pipeline between the two given frames.
- Parameters:
from_frame (
str|CoordinateFrameProtocol) – Initial coordinate frame name of object.to_frame (
str|CoordinateFrameProtocol) – End coordinate frame name or object.
- Returns:
A
DirectionalWCS(wcs, forward) where wcs is of the type of the calling object. The forward attribute indicates if the wcs/pipeline between the two frames is forward (True, from_frame -> to_frame) or backward (False, to_frame -> from_frame). Note that if from_frame and to_frame are the same, then None is returned.- Return type:
Optional[DirectionalWCS[Self]]
- WCS.pixel_to_world(*pixel_arrays)¶
Convert pixel coordinates to world coordinates (represented by high-level objects).
If a single high-level object is used to represent the world coordinates (i.e., if
len(wcs.world_axis_object_classes) == 1), it is returned as-is (not in a tuple/list), otherwise a tuple of high-level objects is returned. Seepixel_to_world_valuesfor pixel indexing and ordering conventions.
- WCS.pixel_to_world_values(*pixel_arrays)¶
Convert pixel coordinates to world coordinates.
This method takes
pixel_n_dimscalars or arrays as input, and pixel coordinates should be zero-based. Returnsworld_n_dimscalars or arrays in units given byworld_axis_units. Note that pixel coordinates are assumed to be 0 at the center of the first pixel in each dimension. If a pixel is in a region where the WCS is not defined, NaN can be returned. The coordinates should be specified in the(x, y)order, where for an image,xis the horizontal coordinate andyis the vertical coordinate.- Parameters:
pixel_arrays (
LowLevelInput)- Return type:
- WCS.set_transform(from_frame, to_frame, transform)¶
Set/replace the transform between two coordinate frames.
- Parameters:
from_frame (
str|CoordinateFrameProtocol) – Initial coordinate frame.to_frame (
str|CoordinateFrameProtocol) – End coordinate frame.transform (
Model) – Transform betweenfrom_frameandto_frame.
- Return type:
- WCS.to_fits(bounding_box=None, max_pix_error=0.25, degree=None, max_inv_pix_error=0.25, inv_degree=None, npoints=32, crpix=None, projection='TAN', bin_ext_name='WCS-TABLE', coord_col_name='coordinates', sampling=1, verbose=False)¶
Construct a FITS WCS
-TAB-based approximation to the WCS in the form of a FITS header and a binary table extension. For the description of the FITS WCS-TABconvention, see “Representations of spectral coordinates in FITS” in Greisen, E. W. et al. A&A 446 (2) 747-771 (2006) . If WCS contains celestial frame, PC/CD formalism will be used for the celestial axes.Note
SIP distortion fitting requires that the WCS object has only two celestial axes. When WCS does not contain celestial axes, SIP fitting parameters (
max_pix_error,degree,max_inv_pix_error,inv_degree, andprojection) are ignored. When a WCS, in addition to celestial frame, contains other types of axes, SIP distortion fitting is disabled (only linear terms are fitted for celestial frame).- Parameters:
bounding_box (tuple, optional) – Specifies the range of acceptable values for each input axis. The order of the axes is
axes_order. For two image axesbounding_boxis of the form((xmin, xmax), (ymin, ymax)).max_pix_error (float, optional) – Maximum allowed error over the domain of the pixel array. This error is the equivalent pixel error that corresponds to the maximum error in the output coordinate resulting from the fit based on a nominal plate scale.
degree (int, iterable, None, optional) –
Degree of the SIP polynomial. Default value
Noneindicates that all allowed degree values ([1...9]) will be considered and the lowest degree that meets accuracy requerements set bymax_pix_errorwill be returned. Alternatively,degreecan be an iterable containing allowed values for the SIP polynomial degree. This option is similar to defaultNonebut it allows caller to restrict the range of allowed SIP degrees used for fitting. Finally,degreecan be an integer indicating the exact SIP degree to be fit to the WCS transformation. In this casemax_pixel_erroris ignored.Note
When WCS object has When
degreeisNoneand the WCS object hasmax_inv_pix_error (float, optional) – Maximum allowed inverse error over the domain of the pixel array in pixel units. If None, no inverse is generated.
inv_degree (int, iterable, None, optional) – Degree of the SIP polynomial. Default value
Noneindicates that all allowed degree values ([1...9]) will be considered and the lowest degree that meets accuracy requerements set bymax_pix_errorwill be returned. Alternatively,degreecan be an iterable containing allowed values for the SIP polynomial degree. This option is similar to defaultNonebut it allows caller to restrict the range of allowed SIP degrees used for fitting. Finally,degreecan be an integer indicating the exact SIP degree to be fit to the WCS transformation. In this casemax_inv_pixel_erroris ignored.npoints (int, optional) – The number of points in each dimension to sample the bounding box for use in the SIP fit. Minimum number of points is 3.
crpix (list of float, None, optional) – Coordinates (1-based) of the reference point for the new FITS WCS. When not provided, i.e., when set to
None(default) the reference pixel will be chosen near the center of the bounding box for axes corresponding to the celestial frame.projection (str,
Pix2SkyProjection, optional) – Projection to be used for the created FITS WCS. It can be specified as a string of three characters specifying a FITS projection code from Table 13 in Representations of World Coordinates in FITS (Paper I), Greisen, E. W., and Calabretta, M. R., A & A, 395, 1061-1075, 2002. Alternatively, it can be an instance of one of the astropy’s Pix2Sky_* projection models inherited fromPix2SkyProjection.bin_ext_name (str, optional) – Extension name for the
BinTableHDUHDU for those axes groups that will be converted using FITW WCS’-TABalgorithm. Extension version will be determined automatically based on the number of separable group of axes.coord_col_name (str, optional) – Field name of the coordinate array in the structured array stored in
BinTableHDUdata. This corresponds toTTYPEifield in the FITS header of the binary table extension.sampling (float, tuple, optional) – The target “density” of grid nodes per pixel to be used when creating the coordinate array for the
-TABFITS WCS convention. It is equal to1/stepwherestepis the distance between grid nodes in pixels.samplingcan be specified as a single number to be used for all axes or as atupleof numbers that specify the sampling for each image axis.verbose (bool, optional) – Print progress of fits.
- Returns:
hdr (
Header) – Header with WCS-TAB information associated (to be used) with image data.hdulist (a list of
BinTableHDU) – A Python list of binary table extensions containing the coordinate array for TAB extensions; one extension per separable axes group.
- Raises:
ValueError – When
bounding_boxis not defined either through the inputbounding_boxparameter or this object’sbounding_boxproperty.ValueError – When
samplingis atupleof length larger than 1 that does not match the number of image axes.RuntimeError – If the number of image axes (
~gwcs.WCS.pixel_n_dim) is larger than the number of world axes (~gwcs.WCS.world_n_dim).
- WCS.to_fits_sip(bounding_box=None, max_pix_error=0.25, degree=None, max_inv_pix_error=0.25, inv_degree=None, npoints=32, crpix=None, projection='TAN', verbose=False)¶
Construct a SIP-based approximation to the WCS for the axes corresponding to the
CelestialFramein the form of a FITS header.The default mode in using this attempts to achieve roughly 0.25 pixel accuracy over the whole image.
- Parameters:
bounding_box (tuple, optional) – A pair of tuples, each consisting of two numbers Represents the range of pixel values in both dimensions ((xmin, xmax), (ymin, ymax))
max_pix_error (float, optional) – Maximum allowed error over the domain of the pixel array. This error is the equivalent pixel error that corresponds to the maximum error in the output coordinate resulting from the fit based on a nominal plate scale. Ignored when
degreeis an integer or a list with a single degree.degree (int, iterable, None, optional) – Degree of the SIP polynomial. Default value
Noneindicates that all allowed degree values ([1...9]) will be considered and the lowest degree that meets accuracy requerements set bymax_pix_errorwill be returned. Alternatively,degreecan be an iterable containing allowed values for the SIP polynomial degree. This option is similar to defaultNonebut it allows caller to restrict the range of allowed SIP degrees used for fitting. Finally,degreecan be an integer indicating the exact SIP degree to be fit to the WCS transformation. In this casemax_pixel_erroris ignored.max_inv_pix_error (float, optional) – Maximum allowed inverse error over the domain of the pixel array in pixel units. If None, no inverse is generated. Ignored when
degreeis an integer or a list with a single degree.inv_degree (int, iterable, None, optional) – Degree of the SIP polynomial. Default value
Noneindicates that all allowed degree values ([1...9]) will be considered and the lowest degree that meets accuracy requerements set bymax_pix_errorwill be returned. Alternatively,degreecan be an iterable containing allowed values for the SIP polynomial degree. This option is similar to defaultNonebut it allows caller to restrict the range of allowed SIP degrees used for fitting. Finally,degreecan be an integer indicating the exact SIP degree to be fit to the WCS transformation. In this casemax_inv_pixel_erroris ignored.npoints (int, optional) – The number of points in each dimension to sample the bounding box for use in the SIP fit. Minimum number of points is 3.
crpix (list of float, None, optional) – Coordinates (1-based) of the reference point for the new FITS WCS. When not provided, i.e., when set to
None(default) the reference pixel will be chosen near the center of the bounding box for axes corresponding to the celestial frame.projection (str,
Pix2SkyProjection, optional) –Projection to be used for the created FITS WCS. It can be specified as a string of three characters specifying a FITS projection code from Table 13 in Representations of World Coordinates in FITS (Paper I), Greisen, E. W., and Calabretta, M. R., A & A, 395, 1061-1075, 2002. Alternatively, it can be an instance of one of the astropy’s Pix2Sky_* projection models inherited from
Pix2SkyProjection.verbose (bool, optional) – Print progress of fits.
- Returns:
hdr – FITS header with all SIP WCS keywords
- Return type:
- Raises:
ValueError – If the WCS is not at least 2D, an exception will be raised. If the specified accuracy (both forward and inverse, both rms and maximum) is not achieved an exception will be raised.
Notes
Use of this requires a judicious choice of required accuracies. Attempts to use higher degrees (~7 or higher) will typically fail due to floating point problems that arise with high powers.
- WCS.to_fits_tab(bounding_box=None, bin_ext_name='WCS-TABLE', coord_col_name='coordinates', sampling=1)¶
Construct a FITS WCS
-TAB-based approximation to the WCS in the form of a FITS header and a binary table extension. For the description of the FITS WCS-TABconvention, see “Representations of spectral coordinates in FITS” in Greisen, E. W. et al. A&A 446 (2) 747-771 (2006) .- Parameters:
bounding_box (tuple, optional) – Specifies the range of acceptable values for each input axis. The order of the axes is
axes_order. For two image axesbounding_boxis of the form((xmin, xmax), (ymin, ymax)).bin_ext_name (str, optional) – Extension name for the
BinTableHDUHDU for those axes groups that will be converted using FITW WCS’-TABalgorithm. Extension version will be determined automatically based on the number of separable group of axes.coord_col_name (str, optional) – Field name of the coordinate array in the structured array stored in
BinTableHDUdata. This corresponds toTTYPEifield in the FITS header of the binary table extension.sampling (float, tuple, optional) – The target “density” of grid nodes per pixel to be used when creating the coordinate array for the
-TABFITS WCS convention. It is equal to1/stepwherestepis the distance between grid nodes in pixels.samplingcan be specified as a single number to be used for all axes or as atupleof numbers that specify the sampling for each image axis.
- Returns:
hdr (
Header) – Header with WCS-TAB information associated (to be used) with image data.bin_table_hdu (
BinTableHDU) – Binary table extension containing the coordinate array.
- Raises:
ValueError – When
bounding_boxis not defined either through the inputbounding_boxparameter or this object’sbounding_boxproperty.ValueError – When
samplingis atupleof length larger than 1 that does not match the number of image axes.RuntimeError – If the number of image axes (
~gwcs.WCS.pixel_n_dim) is larger than the number of world axes (~gwcs.WCS.world_n_dim).
- WCS.transform(from_frame, to_frame, *args, with_bounding_box=True, fill_value=nan, **kwargs)¶
Transform positions between two frames.
- Parameters:
from_frame (
str|CoordinateFrameProtocol) – Initial coordinate frame.to_frame (
str|CoordinateFrameProtocol) – Coordinate frame into which to transform.args (
float|ndarray) – Inputs infrom_frame, separate inputs for each dimension.with_bounding_box (
bool, default:True) – If True(default) values in the result which correspond to any of the inputs being outside the bounding_box are set tofill_value.fill_value (
float|number, default:nan) – Output value for inputs outside the bounding_box (default is np.nan).
- Return type:
- WCS.world_to_array_index(*world_objects)¶
Convert world coordinates (represented by Astropy objects) to array indices.
If
pixel_n_dimis1, this method returns a single scalar or array, otherwise a tuple of scalars or arrays is returned. Seeworld_to_array_index_valuesfor pixel indexing and ordering conventions. The indices should be returned as rounded integers.
- WCS.world_to_array_index_values(*world_arrays)¶
Convert world coordinates to array indices. This is the same as
world_to_pixel_valuesexcept that the indices should be returned in(i, j)order, where for an imageiis the row andjis the column (i.e. the opposite order topixel_to_world_values). The indices should be returned as rounded integers.- Parameters:
world_arrays (
LowLevelInput)- Return type:
- WCS.world_to_pixel(*world_objects)¶
Convert world coordinates (represented by Astropy objects) to pixel coordinates.
If
pixel_n_dimis1, this method returns a single scalar or array, otherwise a tuple of scalars or arrays is returned. Seeworld_to_pixel_valuesfor pixel indexing and ordering conventions.
- WCS.world_to_pixel_values(*world_arrays)¶
Convert world coordinates to pixel coordinates.
This method takes
world_n_dimscalars or arrays as input in units given byworld_axis_units. Returnspixel_n_dimscalars or arrays. Note that pixel coordinates are assumed to be 0 at the center of the first pixel in each dimension. If a world coordinate does not have a matching pixel coordinate, NaN can be returned. The coordinates should be returned in the(x, y)order, where for an image,xis the horizontal coordinate andyis the vertical coordinate.- Parameters:
world_arrays (
LowLevelInput)- Return type: