Building a WCS in Code
Sometimes there’s no header to read. Your own plate solver has fitted a scale,
a rotation and a field center, or you’re generating a synthetic star field and
need to know where each star falls. WcsBuilder takes the same pieces a header
holds and builds the same Wcs.
Here’s a 1.2″-per-pixel field with its axes rotated 12° from north:
use celestial_core::angle::Angle;
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::coordinate::PixelCoord;
use celestial_wcs::spherical::Projection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1.2"/pixel, axes rotated 12° from north
let scale = 1.2 / 3600.0;
let (sin_r, cos_r) = Angle::from_degrees(12.0).sin_cos();
let wcs = WcsBuilder::new()
.crpix(800.5, 600.5)
.crval(148.8882, 69.0653)
.pc_cdelt([[cos_r, -sin_r], [sin_r, cos_r]], [-scale, scale])
.projection(Projection::tan())
.build()?;
let corner = wcs.pixel_to_celestial(PixelCoord::new(1.0, 1.0))?;
println!("pixel (1, 1): RA {:.5}°, Dec {:.5}°", corner.alpha_deg(), corner.delta_deg());
println!("scale: {:.4}\"/pixel", wcs.pixel_scale() * 3600.0);
Ok(())
}
pixel (1, 1): RA 149.49452°, Dec 68.81335°
scale: 1.2000"/pixel
build needs three things, and returns WcsError::MissingBuilderField naming
the setter of the first one that’s absent, as in WcsBuilder is missing crval:
- a reference point:
crpix(x, y)for the pixel andcrval(lon, lat)for its sky position in degrees - a matrix:
cd_matrixorpc_cdelt - a projection:
projection(Projection::tan()), orproj_code("TAN")to name it by its FITS code
validate checks for all three without building, which helps when you fill a
builder in stages and want to report what’s missing before you try.
CD or PC and CDELT
The two matrix setters describe the same thing in different shapes. cd_matrix
takes the CD matrix directly, in degrees per pixel. pc_cdelt takes a
dimensionless rotation matrix PC and a per-axis scale CDELT, and multiplies
them: row i of PC is scaled by cdelt[i].
Use whichever matches where your numbers come from. A least-squares fit usually
produces a CD matrix. A known plate scale and camera angle are easier to write as
PC and CDELT, as in the example above. Either way, the Wcs stores a CD matrix,
and wcs.cd_matrix() returns it.
A negative CDELT1 (or a negative CD1_1 with no rotation) is the usual sky orientation: RA increases to the left, as it does when you look up at the sky with north at the top.
build rejects a matrix with a zero determinant, since that matrix has no
inverse and celestial_to_pixel couldn’t work. The error is
WcsError::NonInvertibleMatrix.
Optional settings
| Setter | Sets | Default |
|---|---|---|
lonpole(deg) | LONPOLE, the native longitude of the celestial pole | from Paper II §2.2 |
latpole(deg) | LATPOLE, picks between two possible pole positions | 90° |
pv(axis, m, value) | a PVi_m keyword | none |
coord_type(type) | the sky system to_keywords names in CTYPE | Equatorial |
distortion(model) | a SIP or TPV correction, see Distortion | none |
Most fields never need lonpole, latpole or pv.
How the transformation works explains
when they matter.
Set projection parameters with the Projection constructor, as in
Projection::azp(mu, gamma), or with proj_code plus pv(2, m, value). Don’t
do both: an explicit Projection already holds its parameters, so build
returns WcsError::InvalidParameter if you also set a PV2_m.
Other sky systems
The transformation doesn’t care what the sky coordinates mean. Galactic
longitude and latitude go through the same math as RA and Dec. coord_type
only changes the CTYPE prefix that to_keywords writes. Here’s a galactic
all-sky map in the CAR projection:
use celestial_wcs::builder::{CoordType, WcsBuilder};
use celestial_wcs::coordinate::{CelestialCoord, PixelCoord};
use celestial_wcs::spherical::Projection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A 3600 x 1800 all-sky map in galactic coordinates, 0.1° per pixel
let wcs = WcsBuilder::new()
.crpix(1800.5, 900.5)
.crval(0.0, 0.0)
.cd_matrix([[-0.1, 0.0], [0.0, 0.1]])
.projection(Projection::car())
.coord_type(CoordType::Galactic)
.build()?;
let left = wcs.pixel_to_celestial(PixelCoord::new(1.0, 900.5))?;
println!("left edge: l {:.2}°", left.alpha_deg());
let lmc = wcs.celestial_to_pixel(CelestialCoord::new(280.47, -32.89))?;
println!("LMC: x {:.1}, y {:.1}", lmc.x(), lmc.y());
Ok(())
}
left edge: l 179.95°
LMC: x 2595.8, y 571.6
CelestialCoord still calls the coordinates alpha and delta, whatever the
system. The CoordType variants and the prefixes they write:
CoordType | CTYPE prefixes |
|---|---|
Equatorial | RA, DEC |
Galactic | GLON, GLAT |
Ecliptic | ELON, ELAT |
Helioecliptic | HLON, HLAT |
Supergalactic | SLON, SLAT |
Generic | any other pair |
A Generic WCS read from a header writes that header’s own prefixes back. One
built in code with CoordType::Generic writes XLON and XLAT.
Write the WCS back as header keywords
to_keywords returns the keywords that describe a Wcs, ready to put in a FITS
header:
use celestial_wcs::builder::{WcsBuilder, WcsKeywordValue};
use celestial_wcs::spherical::Projection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let wcs = WcsBuilder::new()
.crpix(800.5, 600.5)
.crval(148.8882, 69.0653)
.cd_matrix([[-3.2604e-4, 6.930e-5], [6.930e-5, 3.2604e-4]])
.projection(Projection::tan())
.build()?;
for keyword in wcs.to_keywords() {
match keyword.value {
WcsKeywordValue::Real(v) => println!("{:<8} = {v}", keyword.name),
WcsKeywordValue::Integer(v) => println!("{:<8} = {v}", keyword.name),
WcsKeywordValue::String(v) => println!("{:<8} = '{v}'", keyword.name),
}
}
Ok(())
}
CTYPE1 = 'RA---TAN'
CTYPE2 = 'DEC--TAN'
CUNIT1 = 'deg'
CUNIT2 = 'deg'
CRPIX1 = 800.5
CRPIX2 = 600.5
CRVAL1 = 148.8882
CRVAL2 = 69.0653
CD1_1 = -0.00032604
CD1_2 = 0.0000693
CD2_1 = 0.0000693
CD2_2 = 0.00032604
LATPOLE = 69.0653
The matrix always comes out as CD, even when you built with pc_cdelt or read
a CROTA2 header. LONPOLE and LATPOLE appear only when they differ from
what a reader would assume. Here LATPOLE is the declination of the native
pole, which for a zenithal projection is CRVAL2. PVi_m keywords appear only
for projection parameters that differ from their defaults, and distortion
terms follow at the end.
celestial-images writes these for you: an AstroImage given .wcs(&wcs) adds
them to the file that write_fits or write_xisf saves.
A header written by to_keywords reads back to the same transformation. This
converts the keywords into a KeywordMap and builds again:
use celestial_wcs::builder::{Wcs, WcsBuilder, WcsKeywordValue};
use celestial_wcs::coordinate::PixelCoord;
use celestial_wcs::header::KeywordMap;
use celestial_wcs::spherical::Projection;
fn to_header(wcs: &Wcs) -> KeywordMap {
let mut header = KeywordMap::new();
for keyword in wcs.to_keywords() {
match keyword.value {
WcsKeywordValue::Real(v) => header.set_float(keyword.name, v),
WcsKeywordValue::Integer(v) => header.set_int(keyword.name, v),
WcsKeywordValue::String(v) => header.set_string(keyword.name, v),
};
}
header
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let wcs = WcsBuilder::new()
.crpix(800.5, 600.5)
.crval(148.8882, 69.0653)
.cd_matrix([[-3.2604e-4, 6.930e-5], [6.930e-5, 3.2604e-4]])
.projection(Projection::zea())
.build()?;
let reread = WcsBuilder::from_header(&to_header(&wcs))?.build()?;
let pixel = PixelCoord::new(1203.4, 377.9);
println!("{}", wcs.pixel_to_celestial(pixel)? == reread.pixel_to_celestial(pixel)?);
println!("{}", reread.projection_code());
Ok(())
}
true
ZEA
Read a WCS back out
A built Wcs reports its parameters, which is useful for showing a plate
solution to a user:
| Method | Returns |
|---|---|
crpix() | [x, y] reference pixel |
crval() | [lon, lat] in degrees |
cd_matrix() | the CD matrix in degrees per pixel |
pixel_scale() | √|det CD|, degrees per pixel |
projection_code() | the three-letter code, "TAN" for a TPV header |
coord_type() | the CoordType |
native_reference() | (φ0, θ0), the native coordinates of the reference point |
projection() | the Projection |
rotation() | the SphericalRotation |
pixel_scale is the side of a square pixel with the same area on the sky. For
a field with different x and y scales, take the lengths of the CD matrix’s
columns instead.
Where next
- Projections: pick a projection and set its parameters.
- Distortion: SIP and TPV: add a polynomial correction.
- How the transformation works: what each builder setting does to a coordinate.