Pixels and Sky Coordinates
You’ve plate-solved an image, and now you want to know where a star you measured
sits on the sky, or where a catalog star should land on the sensor. The answer is
already in the FITS header. A plate solver writes a World Coordinate System (WCS)
there: a reference pixel, the sky position at that pixel, a matrix for scale and
rotation, and a projection. celestial-wcs reads those keywords and runs the
transformation in both directions.
Here’s an image of M81 opened with celestial-images and converted both ways:
use celestial_images::formats::image::Image;
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::coordinate::{CelestialCoord, PixelCoord};
use celestial_wcs::header::KeywordProvider;
struct Header<'a>(&'a Image);
impl KeywordProvider for Header<'_> {
fn get_string(&self, key: &str) -> Option<String> {
self.0.get_last(key).as_str().map(str::to_string)
}
fn get_float(&self, key: &str) -> Option<f64> {
self.0.get_last(key).as_f64()
}
fn get_int(&self, key: &str) -> Option<i64> {
self.0.get_last(key).as_i64()
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let image = Image::open("m81.fits")?;
let wcs = WcsBuilder::from_header(&Header(&image))?.build()?;
// A star you measured at pixel (1203.4, 377.9)
let star = wcs.pixel_to_celestial(PixelCoord::new(1203.4, 377.9))?;
println!("star: RA {:.5}°, Dec {:.5}°", star.alpha_deg(), star.delta_deg());
// Where a catalog star should land on the sensor
let catalog_star = CelestialCoord::new(149.1520, 68.9874);
let pixel = wcs.celestial_to_pixel(catalog_star)?;
println!("catalog star: x {:.2}, y {:.2}", pixel.x(), pixel.y());
// M82 is 37' north of M81, past the top edge of this 1600 x 1200 frame
let m82 = wcs.celestial_to_pixel(CelestialCoord::new(148.9685, 69.6797))?;
println!("M82: x {:.2}, y {:.2}", m82.x(), m82.y());
Ok(())
}
star: RA 148.47822°, Dec 69.02015°
catalog star: x 474.46, y 431.50
M82: x 1101.91, y 2420.99
The header in m81.fits holds a TAN projection centered on RA 148.8882°,
Dec 69.0653°, at 1.2″ per pixel.
celestial_to_pixel returned a position for M82 even though it’s off the
sensor. The WCS describes a plane that extends past the image, and it doesn’t
read NAXIS1 or NAXIS2. Compare the result with the image size yourself when
you need to know whether a target is in the frame.
Read the header through KeywordProvider
WcsBuilder::from_header doesn’t parse FITS files. It asks for keywords by name
through the KeywordProvider trait, so it works with any FITS reader you already
use. The trait has three methods, one per value type, and each returns None
when the keyword is absent:
| Method | Reads |
|---|---|
get_string | CTYPEi, CUNITi |
get_float | CRPIXj, CRVALi, CDi_j, PCi_j, PVi_m and the rest |
get_int | the SIP orders, A_ORDER and friends |
The Header wrapper above reads from a celestial_images Image. Its
as_f64 accepts integer cards as well as real ones, which matters because many
writers store CRPIX1 = 800 without a decimal point.
For tests and examples, celestial_wcs::header::KeywordMap is a small in-memory
header you fill with set_string, set_float and set_int:
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::coordinate::{CelestialCoord, PixelCoord};
use celestial_wcs::header::KeywordMap;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut header = KeywordMap::new();
header
.set_string("CTYPE1", "RA---TAN")
.set_string("CTYPE2", "DEC--TAN")
.set_float("CRPIX1", 800.5)
.set_float("CRPIX2", 600.5)
.set_float("CRVAL1", 148.8882)
.set_float("CRVAL2", 69.0653)
.set_float("CDELT1", -3.3333e-4)
.set_float("CDELT2", 3.3333e-4);
let wcs = WcsBuilder::from_header(&header)?.build()?;
// 100° from the field center, behind the tangent plane
let far = wcs.celestial_to_pixel(CelestialCoord::new(148.8882, -30.0));
println!("{far:?}");
let bad = wcs.pixel_to_celestial(PixelCoord::new(f64::NAN, 10.0));
println!("{bad:?}");
Ok(())
}
Err(Singularity { message: "TAN projection undefined at theta <= 0" })
Err(InvalidParameter { message: "pixel coordinates must be finite" })
Both conversions return WcsResult. The first call fails because TAN can’t show
a point 90° or more from the field center. The second fails because the pixel
is NaN. The crate returns an error for input like this instead of a NaN
coordinate, so bad values don’t travel silently into your photometry or
astrometry.
from_header follows the FITS defaults for keywords the header leaves out:
CRPIXj and CRVALi default to 0 and CDELTi to 1. A header with only
CTYPE1 and CTYPE2 therefore builds, at one degree per pixel. A header with
no CTYPE1 or CTYPE2 returns WcsError::MissingKeyword.
How the transformation works covers which other keywords the
reader understands.
Units and pixel conventions
Sky coordinates are f64 degrees. CelestialCoord::new(alpha_deg, delta_deg)
takes degrees, and alpha_deg() and delta_deg() return them. If your code
works in celestial_core::angle::Angle, alpha() and delta() return one.
The crate keeps degrees internally because the FITS WCS papers state their
equations in degrees, and a value like 148.8882° doesn’t survive a trip through
radians unchanged.
Pixel coordinates follow FITS: the center of the first pixel is (1, 1), and a pixel spans ±0.5 around its center. Rust arrays start at 0, so convert when you index pixel data:
use celestial_wcs::coordinate::PixelCoord;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let first = PixelCoord::from_array_index(0, 0);
println!("array [0][0] is FITS pixel ({}, {})", first.x(), first.y());
let (row, col) = PixelCoord::new(1203.4, 377.9).to_array_index()?;
println!("FITS pixel (1203.4, 377.9) is array [{row}][{col}]");
let off_frame = PixelCoord::new(0.2, 10.0).to_array_index();
println!("{off_frame:?}");
Ok(())
}
array [0][0] is FITS pixel (1, 1)
FITS pixel (1203.4, 377.9) is array [377][1202]
Err(OutOfBounds { message: "pixel 0.2 has no array index" })
to_array_index returns (row, column), which is (y, x). FITS pixel n
covers [n − 0.5, n + 0.5), so 0.5 is the first edge of index 0 and 1.5 is the
first edge of index 1. A coordinate below 0.5 on either axis has no index and
returns WcsError::OutOfBounds. It doesn’t check the upper edge, since it doesn’t know
the image size.
The range of the returned RA
pixel_to_celestial returns longitude in [0°, 360°] when CRVAL1 is zero or
positive, and in [-360°, 0°] when CRVAL1 is negative. This matches wcslib, and
it means the reference pixel always maps back to CRVAL1. A field that straddles
the 0° meridian shows the rule at work:
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::coordinate::PixelCoord;
use celestial_wcs::spherical::Projection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
for crval1 in [0.5, -0.5] {
let wcs = WcsBuilder::new()
.crpix(512.0, 512.0)
.crval(crval1, 20.0)
.cd_matrix([[-0.001, 0.0], [0.0, 0.001]])
.projection(Projection::tan())
.build()?;
let left = wcs.pixel_to_celestial(PixelCoord::new(1.0, 512.0))?;
let right = wcs.pixel_to_celestial(PixelCoord::new(1024.0, 512.0))?;
println!(
"CRVAL1 {crval1:>4}: left edge RA {:.4}°, right edge RA {:.4}°",
left.alpha_deg(),
right.alpha_deg()
);
}
Ok(())
}
CRVAL1 0.5: left edge RA 1.0438°, right edge RA 359.9552°
CRVAL1 -0.5: left edge RA -359.9562°, right edge RA -1.0448°
The two fields are 1° apart on the sky, but their RA values land in different
ranges. A point exactly on the 0° meridian can come back as either end of the
range. If you need RA in [0°, 360°), reduce the value yourself.
celestial_to_pixel accepts a longitude in any range, so you can pass a
reduced value back in.
Validation against wcslib
The crate is checked against wcslib 8.5 by a separate harness that links the C
library and compares results on the same input. Each result must be bit-equal
to wcslib’s, or at least as close as wcslib’s to the exact answer that the FITS
WCS papers define.
The harness is LGPL like wcslib, so it lives outside this workspace and isn’t
part of cargo test.
Where next
- Building a WCS in code: make a WCS from fitted parameters and write it back as header keywords.
- How the transformation works: the four stages between a pixel and the sky, and the header keywords that drive each one.
- Projections: the 26 projection codes and when you’d see each.
- Distortion: SIP and TPV: the polynomial corrections plate solvers add for optical distortion.