Rotate wcs to north Up and reproject data to it in a Python function. Wcs uses pc
- User
Rotate wcs to north Up and reproject data to it in a Python function. Wcs uses pc
- Assistant
Rotate wcs to north Up and reproject data to it in a Python function. Wcs uses pc
Certainly! Below is a comprehensive Python function that rotates a World Coordinate System (WCS) to have North up and reprojects the associated data accordingly. This function leverages the astropy and reproject libraries, which are powerful tools for astronomical data manipulation.
Understanding the WCS Rotation:
PC or CD matrices) to map pixel coordinates to world coordinates.Steps Involved:
PC matrix.Ensure you have the necessary libraries installed:
pip install astropy reproject numpy
import numpy as np
from astropy.wcs import WCS
from astropy.io import fits
from reproject import reproject_interp
from astropy.wcs.utils import proj_plane_pixel_scales
from astropy.coordinates import Angle
def rotate_wcs_to_north_up(input_wcs, input_data, shape_out=None):
"""
Rotate WCS to have North up and reproject the associated data accordingly.
Parameters
----------
input_wcs : astropy.wcs.WCS
The original WCS with PC or CD matrix.
input_data : 2D ndarray
The input 2D data array (e.g., image).
shape_out : tuple of ints, optional
The shape of the output array. If None, it defaults to the input data shape.
Returns
-------
output_data : 2D ndarray
The reprojected data with North up.
output_wcs : astropy.wcs.WCS
The new WCS with North up.
"""
# Step 1: Extract the PC matrix
pc = input_wcs.pixel_matrix # This retrieves the PC matrix
if pc is None:
raise ValueError("Input WCS does not have a PC or CD matrix.")
# Step 2: Calculate the current rotation angle
# Assuming the PC matrix is a pure rotation + scaling
# theta = arctan2(m21, m11)
theta = np.arctan2(pc[1, 0], pc[0, 0])
# Convert rotation angle from radians to degrees
theta_deg = np.degrees(theta)
# Step 3: Create a rotation matrix to cancel the current rotation
# Rotation by -theta
rot_matrix = np.array([
[np.cos(-theta), -np.sin(-theta)],
[np.sin(-theta), np.cos(-theta)]
])
# Step 4: Compute the new PC matrix with rotation canceled
new_pc = np.dot(rot_matrix, pc)
# Ensure that the new PC matrix has no rotation:
# For North up, new_pc should have PC2_1 ~ 0 and PC1_2 ~ -0
# Due to numerical precision, we can zero out small values
new_pc[1, 0] = 0.0 # PC2_1
new_pc[0, 1] = 0.0 # PC1_2
# Step 5: Create the new WCS with North up
new_wcs = input_wcs.deepcopy()
new_wcs.wcs.pc = new_pc
# Alternatively, set CD matrix if CD is used instead of PC
# Check if CD matrix is present
if hasattr(new_wcs.wcs, 'cd'):
new_cd = np.dot(rot_matrix, new_wcs.wcs.cd)
new_wcs.wcs.cd = new_cd
# Step 6: Define output shape
if shape_out is None:
shape_out = input_data.shape
# Step 7: Reproject the data to the new WCS
output_data, footprint = reproject_interp((input_data, input_wcs), new_wcs, shape_out=shape_out)
return output_data, new_wcs
Extracting the PC Matrix:
pixel_matrix attribute retrieves the PC matrix (CD matrix if present).Calculating the Rotation Angle:
θ is extracted using the arctan2 function from the PC matrix elements.Creating the Rotation Correction Matrix:
-θ), effectively aligning the North upward.Updating the PC Matrix:
PC matrix to obtain a new PC matrix with no rotation.PC matrix should ideally be zero. Small numerical errors are handled by explicitly setting them to zero.Handling the CD Matrix:
CD matrix instead of a PC matrix, the same rotation correction is applied to the CD matrix.Reprojecting the Data:
reproject_interp function reprojects the input data to the new WCS with North up.shape_out parameter allows specifying the shape of the output array. By default, it matches the input data's shape.Here's how you can use the rotate_wcs_to_north_up function with FITS data:
from astropy.io import fits
# Load your FITS file
with fits.open('input_image.fits') as hdulist:
input_data = hdulist[0].data
input_header = hdulist[0].header
input_wcs = WCS(input_header)
# Rotate WCS to North up and reproject data
output_data, output_wcs = rotate_wcs_to_north_up(input_wcs, input_data)
# Update FITS header with the new WCS
output_header = output_wcs.to_header()
# Optionally, you can copy other header keywords from the original
for key in input_header.keys():
if key not in output_header:
output_header[key] = input_header[key]
# Save the reprojected data to a new FITS file
hdu = fits.PrimaryHDU(data=output_data, header=output_header)
hdu.writeto('output_image_north_up.fits', overwrite=True)
Make sure to import the necessary modules and handle any exceptions or special cases as needed for your specific data.
This function provides a robust way to rotate a WCS to have North up and reproject the corresponding data. By leveraging astropy and reproject, it ensures that the transformation maintains the integrity of the celestial coordinates while presenting the data in a standard orientation.
Not yet included in a published release.