Celestial
Celestial is a set of Rust crates for astronomy software: time scales, the IAU coordinate chain, ephemerides, images, WCS, telescope pointing models, a star catalog and a plate solver.
Everything runs in pure Rust, with no C or Fortran underneath. The IAU precession, nutation and Earth orientation models are tested against ERFA output with exact equality. For those models you get the same numbers as ERFA, in a binary you can cross-compile without a C toolchain and step through in a debugger.
A first example
Here’s a star going from its catalog position to azimuth and elevation at Keck:
use celestial_coords::eop::EopProvider;
use celestial_coords::frames::cirs::CIRSPosition;
use celestial_coords::frames::icrs::ICRSPosition;
use celestial_coords::transforms::CoordinateFrame;
use celestial_core::constants::MJD_ZERO_POINT;
use celestial_core::location::Location;
use celestial_time::julian::JulianDate;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// EOP tables are indexed by UTC MJD; precession and nutation take TT.
let mjd = 60000.35;
let utc = UTC::from_julian_date(JulianDate::new(MJD_ZERO_POINT, mjd));
let epoch = utc.to_tai()?.to_tt()?;
let eop = EopProvider::bundled()?.get(mjd)?;
let keck = Location::from_degrees(19.8283, -155.4783, 4145.0)?;
let sirius = ICRSPosition::from_hours_degrees(6.7525, -16.716)?;
let cirs = CIRSPosition::from_icrs(&sirius, &epoch)?;
let hour_angle = cirs.to_hour_angle(&keck, &eop)?;
let horizon = hour_angle.to_topocentric()?;
println!(
"HA = {:.3} h, az = {:.2}°, el = {:.2}°",
hour_angle.hour_angle().hours(),
horizon.azimuth().degrees(),
horizon.elevation().degrees()
); // HA = 1.595 h, az = 214.36°, el = 46.53°
Ok(())
}
Each step takes the input its physics needs. Precession and nutation need a TT epoch, the Earth’s rotation needs Earth orientation parameters, and the horizon needs a site. Each frame is its own type, so you can’t skip a step by accident. EopProvider::bundled() reads the IERS tables that ship with celestial-coords, so this works offline.
The crates
| Crate | Use it to |
|---|---|
celestial-core | work with angles, vectors and rotation matrices, and run the IAU precession, nutation and Earth orientation models |
celestial-time | convert between UTC, TAI, TT, UT1, GPS, TDB, TCB and TCG, and compute sidereal time |
celestial-coords | move positions through ICRS, GCRS, CIRS, TIRS and ITRS to hour angle and azimuth/elevation |
celestial-ephemeris | compute Sun, Moon and planet positions from VSOP2013 and ELP/MPP02, or read JPL SPK kernels |
celestial-wcs | convert between pixel and sky coordinates with FITS WCS headers |
celestial-images | read and write FITS, XISF, SER, PNG and TIFF |
celestial-catalog | run cone searches on a Gaia DR3 and Hipparcos star catalog |
celestial-solver | plate-solve an image and write the WCS solution back to its header |
celestial-pointing | fit and apply pointing models for equatorial mounts |
celestial-core depends on no other crate in the workspace. time and wcs build on core, and the rest build on those. The plate solver uses the most: coords, wcs, images and catalog.
What this book covers
Each section starts with the problem its crate solves. Each crate’s README has a short example and the API details.
- To use angles, vectors and rotation matrices, read Angles and Vectors & Rotation Matrices.
- To understand why catalog coordinates need precession and nutation, and how the CIO-based and equinox-based chains relate, read Precession, Nutation & Obliquity and The CIO and the Equinox. Ecliptic Coordinates and Observer Locations cover the other frames and the observer.
- To pick the right time scale, handle leap seconds or compute sidereal time, start with Time Scales.
- To turn a catalog position into where a star appears in your sky, read From Catalog to Horizon, or go straight to Find the Altitude and Azimuth of a Star.
- To find where a planet, the Sun or the Moon is, start with Planets, Sun and Moon. Accuracy says how close the built-in series come to the JPL ephemerides, and JPL SPK Kernels covers reading a kernel when you need more.
- To convert between pixels and sky coordinates with a FITS WCS, read Pixels and Sky Coordinates.
- To read or write FITS, XISF or SER files, start with Open and Save Images.
- To find the stars around a sky position, or to choose and download a catalog file, start with Star Catalog.
- To find where an image points, follow Solve Your First Image.
- To build a pointing model from a night of observations, start with Pointing Models. The pointing crate is still experimental.
Angles
Astronomy mixes angle units constantly. Right ascension comes in hours, declination in
degrees, catalog errors in arcseconds, and every trig function wants radians. A bare
f64 doesn’t say which one it holds, so a degree value passed where radians belong
compiles fine and gives a wrong answer.
Angle fixes that by making the unit part of the type. You build one from whatever unit
your data uses and read it back in whatever unit you need:
use celestial_core::angle::Angle;
let dec = Angle::from_degrees(-16.7161);
let ra = Angle::from_hours(6.752472);
let (sin_dec, cos_dec) = dec.sin_cos(); // no manual conversion to radians
ra.degrees(); // 101.28708
Angle stores radians in a single f64. It’s Copy, so you pass it by value everywhere.
All of its trig methods call the pure-Rust libm crate instead of the platform math
library.
Create an angle
There’s one constructor per unit:
use celestial_core::angle::Angle;
use celestial_core::constants::QUARTER_PI;
let a = Angle::from_degrees(45.0);
let b = Angle::from_radians(QUARTER_PI);
let c = Angle::from_hours(3.0); // 1h = 15°
let d = Angle::from_arcseconds(162000.0); // 3600" per degree
let e = Angle::from_arcminutes(2700.0); // 60' per degree
from_radians is the only const fn constructor, because radians need no conversion.
Use it to define angle constants:
use celestial_core::angle::Angle;
use celestial_core::constants::HALF_PI;
const RIGHT_ANGLE: Angle = Angle::from_radians(HALF_PI);
Take PI, HALF_PI, TWOPI and friends from celestial_core::constants, not
std::f64::consts. The library uses its own constants everywhere, so your values match
the ones its code computes with.
Angle also has three associated constants: Angle::ZERO, Angle::PI (180°) and
Angle::HALF_PI (90°).
Shorthand functions
The angle module has short free functions that call the matching constructor:
use celestial_core::angle::{arcmin, arcsec, deg, hours, rad};
use celestial_core::constants::QUARTER_PI;
let a = deg(45.0); // Angle::from_degrees
let b = rad(QUARTER_PI); // Angle::from_radians
let c = hours(3.0); // Angle::from_hours
let d = arcsec(162000.0);
let e = arcmin(2700.0);
Read an angle in another unit
Every constructor has a matching accessor:
use celestial_core::angle::Angle;
let angle = Angle::from_degrees(45.0);
angle.radians(); // 0.7853981633974483
angle.degrees(); // 45.0
angle.hours(); // 3.0
angle.arcseconds(); // 162000.0
angle.arcminutes(); // 2700.0
Right ascension is measured in hours of time, and 24 hours make a full circle. One hour is 15°, one minute of time is 15 arcminutes, and one second of time is 15 arcseconds.
use celestial_core::angle::Angle;
// Sirius RA: 6h 45m 8.9s
let ra = Angle::from_hours(6.0 + 45.0 / 60.0 + 8.9 / 3600.0);
ra.degrees(); // 101.28708333333333
ra.hours(); // 6.752472222222222
Trigonometry
sin, cos and tan return f64. sin_cos returns both as a (sin, cos) tuple,
which is what rotation matrices and coordinate transforms usually need.
use celestial_core::angle::Angle;
let angle = Angle::from_degrees(30.0);
angle.sin(); // 0.5
angle.cos(); // 0.8660254037844386
angle.tan(); // 0.5773502691896258
let (sin, cos) = angle.sin_cos();
Wrap an angle into a standard range
270° and -90° point the same way, but conventions differ on which one to report. Right ascension and azimuth are conventionally positive. Hour angles and longitude differences read better as the short way round. Two methods cover both:
use celestial_core::angle::Angle;
let angle = Angle::from_degrees(-90.0);
angle.normalized()?.degrees(); // 270.0, range [0°, 360°)
angle.wrapped()?.degrees(); // -90.0, range -180° to +180°
Both return Result and fail on NaN or infinity, so a bad input stops at the wrap
instead of spreading through later math. One edge case: wrapped() turns exactly +180°
into -180° and exactly -180° into +180°.
Arithmetic results are never wrapped for you. Call normalized() or wrapped() when
you need a result in a standard range.
abs() returns the absolute value:
use celestial_core::angle::Angle;
Angle::from_degrees(-45.0).abs().degrees(); // 45.0
Wrap raw radians
When you have a bare f64 in radians, wrap_0_2pi and wrap_pm_pi do the same job.
Both return Result<f64, AstroError> and fail on NaN or infinity.
use celestial_core::angle::{wrap_0_2pi, wrap_pm_pi};
wrap_0_2pi(-1.0)?; // 5.283185307179586
wrap_pm_pi(5.0)?; // -1.2831853071795862
Validate an angle
User input and file headers can hold anything. The validators check that an angle makes
sense for what it claims to be. Each returns Result<Angle, AstroError> and rejects NaN
and infinity.
| Method | Accepts | On success returns |
|---|---|---|
validate_right_ascension() | any finite angle | the angle wrapped to [0°, 360°) |
validate_declination(false) | [-90°, +90°] | the angle unchanged |
validate_declination(true) | [-180°, +180°] | the angle unchanged |
validate_latitude() | [-90°, +90°] | the angle unchanged |
use celestial_core::angle::Angle;
let ra = Angle::from_degrees(400.0).validate_right_ascension()?;
ra.degrees(); // 40.00000000000001
let dec = Angle::from_degrees(100.0);
dec.validate_declination(false).is_err(); // true
dec.validate_declination(true)?; // ok
Right ascension is cyclic, so its validator wraps instead of rejecting. 2π has no exact
f64 value, which is why 400° comes back one bit above 40°.
The beyond_pole flag on validate_declination widens the range to ±180°. German
equatorial mounts report declinations past the pole when they track through it.
There is no longitude validator. Longitude is cyclic, so use normalized().
The same checks exist as free functions that take the angle as an argument:
use celestial_core::angle::{
validate_declination, validate_latitude, validate_right_ascension, Angle,
};
let angle = Angle::from_degrees(45.0);
validate_right_ascension(angle)?;
validate_declination(angle, false)?;
validate_latitude(angle)?;
Parse an angle from a string
The angle module has two parsers. They accept different notations, so pick by where
your strings come from.
Units you know: AngleUnits
When you know what a string holds, the AngleUnits trait on str reads it directly.
Every method returns Result<Angle, AstroError>.
use celestial_core::angle::AngleUnits;
// Decimal numbers in a named unit
let a = "45.5".deg()?;
let b = "0.785".rad()?;
let c = "12.5".hours()?;
let d = "60.0".arcmin()?;
let e = "3600.0".arcsec()?;
// Sexagesimal
let ra = "12:34:56".hms()?;
let dec = "-45:30:15".dms()?;
// Letter markers and spelled-out units
let ra2 = "12h34m56s".hms()?;
let ra3 = "12 hours 34 minutes 56 seconds".hms()?;
let dec2 = "45d30m15s".dms()?;
let dec3 = "45 degrees 30 arcmin 15 arcsec".dms()?;
.hms() and .dms() need all three fields. "12h30m" is an error. The free functions
parse_hms and parse_dms do the same parsing as these two methods.
Units you don’t know: ParseAngle
For free-form input, ParseAngle::to_angle tries HMS, then DMS, then decimal degrees:
use celestial_core::angle::ParseAngle;
"12:34:56".to_angle()?.hours(); // 12.582222222222223, read as HMS
"45d30m15s".to_angle()?.degrees(); // 45.50416666666667, read as DMS
"45.5".to_angle()?.degrees(); // 45.5, read as decimal degrees
A colon string like 12:34:56 could be hours or degrees, and to_angle always picks
hours. Call .dms() when you know the string is a declination.
Symbol notation: parse_angle
parse_angle splits on marker characters, including °, ', " and the superscripts
ʰ ᵐ ˢ. It reads the output of DmsFmt and HmsFmt (below), which the AngleUnits
methods reject. It returns a ParsedAngle, whose angle field holds the result.
use celestial_core::angle::parse_angle;
let ra = parse_angle("05h14m32.27s")?.angle;
ra.hours(); // 5.242297222222223
let dec = parse_angle("-08°12'05.9\"")?.angle;
dec.degrees(); // -8.201638888888889
parse_angle reads a string as HMS when it has an h, ʰ or :, and as DMS otherwise.
A bare number such as "45.5" is 45.5°. A colon string such as "12:30:15" comes back
in hours, so call .dms() from AngleUnits when a colon string holds degrees.
Format an angle for display
DmsFmt writes degrees, arcminutes and arcseconds, for declination, latitude and
altitude. The sign is always shown. frac_digits sets the decimal places on the
arcseconds.
use celestial_core::angle::{Angle, DmsFmt};
let dec = Angle::from_degrees(-23.4392);
DmsFmt { frac_digits: 0 }.fmt(dec); // -23° 26' 21"
DmsFmt { frac_digits: 2 }.fmt(dec); // -23° 26' 21.12"
HmsFmt writes hours, minutes and seconds with the superscript markers ʰ ᵐ ˢ, for
right ascension and hour angles. It wraps negative angles into [0h, 24h).
use celestial_core::angle::{Angle, HmsFmt};
let fmt = HmsFmt { frac_digits: 1 };
fmt.fmt(Angle::from_hours(14.5)); // 14ʰ 30ᵐ 0.0ˢ
fmt.fmt(Angle::from_hours(-1.5)); // 22ʰ 30ᵐ 0.0ˢ
Display prints decimal degrees with six decimal places:
use celestial_core::angle::Angle;
format!("{}", Angle::from_degrees(45.123456789)); // 45.123457°
Arithmetic
Angles add, subtract and negate, and multiply or divide by an f64:
use celestial_core::angle::Angle;
let a = Angle::from_degrees(30.0);
let b = Angle::from_degrees(15.0);
(a + b).degrees(); // 45.00000000000001
(a - b).degrees(); // 15.000000000000002
(a * 2.0).degrees(); // 60.00000000000001
(a / 2.0).degrees(); // 15.000000000000002
(-a).degrees(); // -30.000000000000004
The trailing digits come from the round trip through radians. Each degree value is converted to radians on the way in and back on the way out, and each conversion rounds. Compare angles with a tolerance, or keep your values in radians, when the last bit matters.
Where next
- Vectors and rotation matrices for turning angles into directions and transforming them between frames.
Vectors and rotation matrices
Almost every coordinate transform in the library works the same way. It turns a position on the sky into a 3D unit vector, rotates that vector into another frame, and turns it back into two angles. Precession, nutation and frame bias are each a rotation matrix. Applying several of them in a row means multiplying the matrices.
celestial_core::matrix provides the two types behind this: Vector3 for directions
and positions, and RotationMatrix3 for the rotations. Here is the whole loop:
use celestial_core::matrix::{RotationMatrix3, Vector3};
let mut frame = RotationMatrix3::identity();
frame.rotate_z(0.1);
let star = Vector3::from_spherical(1.2, 0.3); // RA, Dec in radians
let (ra, dec) = (frame * star).to_spherical();
All angles in this module are plain f64 radians. Use Angle::radians() to get them
from an Angle.
Vector3
A 3D Cartesian vector with public x, y and z fields.
Create a vector
use celestial_core::matrix::Vector3;
let v = Vector3::new(1.0, 2.0, 3.0);
let x = Vector3::x_axis(); // [1, 0, 0]
let y = Vector3::y_axis(); // [0, 1, 0]
let z = Vector3::z_axis(); // [0, 0, 1]
let zero = Vector3::zeros();
let v = Vector3::from_array([1.0, 2.0, 3.0]);
let arr: [f64; 3] = v.to_array();
Convert to and from spherical coordinates
from_spherical(ra, dec) returns the unit vector pointing at that RA and Dec:
use celestial_core::constants::HALF_PI;
use celestial_core::matrix::Vector3;
Vector3::from_spherical(0.0, 0.0); // [1, 0, 0]
Vector3::from_spherical(HALF_PI, 0.0); // [6.123233995736766e-17, 1, 0]
Vector3::from_spherical(0.0, HALF_PI); // [6.123233995736766e-17, 0, 1], the north pole
The tiny x components are real. HALF_PI is slightly less than the true π/2, so its cosine
is not quite zero.
to_spherical goes the other way and returns (theta, phi):
thetais the angle from +X toward +Y, like RA, in(-π, π].phiis the elevation above the XY plane, like Dec, in[-π/2, π/2].
use celestial_core::matrix::Vector3;
let (theta, phi) = Vector3::new(0.0, 0.0, 1.0).to_spherical();
// theta = 0.0, phi = π/2
The vector doesn’t need unit length, because only its direction matters. The zero
vector returns (0.0, 0.0). The names follow the astronomy convention, where phi is
elevation. Physics texts often swap the two names.
Length and normalization
use celestial_core::matrix::Vector3;
let v = Vector3::new(3.0, 4.0, 0.0);
v.magnitude(); // 5.0
v.magnitude_squared(); // 25.0, skips the square root
let unit = v.normalize()?; // [0.6000000000000001, 0.8, 0.0]
normalize returns an error for a zero-length or non-finite vector. It multiplies by
1/|v| rather than dividing, as ERFA’s pn does, which is why x lands one bit above
0.6.
Dot and cross products
For unit vectors, the dot product is the cosine of the angle between them. The cross product gives the axis perpendicular to both, by the right-hand rule.
use celestial_core::matrix::Vector3;
let a = Vector3::x_axis();
let b = Vector3::y_axis();
a.dot(&b); // 0.0
a.cross(&b); // [0, 0, 1], the z axis
Vector3::new(1.0, 2.0, 3.0).dot(&Vector3::new(4.0, 5.0, 6.0)); // 32.0
Read and write components
Read and write the fields directly. get and set take an index instead, and return an
error for any index outside 0 to 2.
use celestial_core::matrix::Vector3;
let mut v = Vector3::new(1.0, 2.0, 3.0);
v.x = 10.0;
v.get(0)?; // 10.0
v.set(1, 20.0)?;
v.get(3); // Err: index out of bounds
Arithmetic
use celestial_core::matrix::Vector3;
let a = Vector3::new(1.0, 2.0, 3.0);
let b = Vector3::new(4.0, 5.0, 6.0);
a + b; // [5, 7, 9]
b - a; // [3, 3, 3]
a * 2.0; // [2, 4, 6]
3.0 * a; // [3, 6, 9]
a / 2.0; // [0.5, 1, 1.5]
-a; // [-1, -2, -3]
let mut v = Vector3::new(10.0, 20.0, 30.0);
v /= 2.0; // [5, 10, 15]
Display a vector
Display prints nine decimal places:
use celestial_core::matrix::Vector3;
println!("{}", Vector3::new(1.0, -2.5, 3.0));
// Vector3(1.000000000, -2.500000000, 3.000000000)
RotationMatrix3
A 3x3 rotation matrix stored row-major. The elements are private, and every
constructor either builds a rotation or checks that its input is one. Read the elements
with elements().
Create a matrix
Start from the identity and add rotations, or pass the elements in:
use celestial_core::matrix::RotationMatrix3;
let m = RotationMatrix3::identity();
let m = RotationMatrix3::from_array([
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
])?;
from_array checks its input. It returns an error unless every element is finite and
the matrix is a proper rotation. That means M * M^T within 1e-12 of the identity and a
determinant within 1e-12 of +1. A scaling matrix such as diag(2, 1, 1) fails.
Deserializing with serde runs the same check.
There is no per-element setter, for the same reason.
Build a rotation
rotate_x, rotate_y and rotate_z each rotate the matrix in place about one axis.
Each call replaces the matrix self with R_axis(angle) * self, so later calls apply
after earlier ones:
use celestial_core::matrix::RotationMatrix3;
let mut m = RotationMatrix3::identity();
m.rotate_z(0.1); // m = Rz
m.rotate_y(-0.05); // m = Ry * Rz
m.rotate_x(0.02); // m = Rx * Ry * Rz
Rotations follow the ERFA convention. A positive angle rotates the coordinate frame counterclockwise, seen from the positive axis looking toward the origin. Because the frame turns and the vector stays put, the vector’s coordinates move the opposite way:
use celestial_core::constants::HALF_PI;
use celestial_core::matrix::RotationMatrix3;
let mut m = RotationMatrix3::identity();
m.rotate_z(HALF_PI);
m.apply_to_vector([1.0, 0.0, 0.0]); // [6.123233995736766e-17, -1.0, 0.0]
Apply a matrix to a vector
apply_to_vector works on [f64; 3]. The * operator works on Vector3, with the
matrix by value or by reference.
use celestial_core::matrix::{RotationMatrix3, Vector3};
let mut m = RotationMatrix3::identity();
m.rotate_z(0.5);
let out: [f64; 3] = m.apply_to_vector([1.0, 0.0, 0.0]);
let v = Vector3::new(1.0, 0.0, 0.0);
let out: Vector3 = m * v;
let out: Vector3 = &m * v;
Compose rotations
Multiplying two matrices composes their rotations. The rightmost matrix acts first.
use celestial_core::matrix::RotationMatrix3;
let mut rx = RotationMatrix3::identity();
rx.rotate_x(0.1);
let mut rz = RotationMatrix3::identity();
rz.rotate_z(0.2);
// Apply rx, then rz
let combined = rz * rx;
let combined = rz.multiply(&rx); // same result
* accepts every mix of owned and borrowed operands: m * m, m * &m, &m * m and
&m * &m.
Transform RA and Dec in one call
transform_spherical converts to a unit vector, applies the matrix and converts back:
use celestial_core::constants::QUARTER_PI;
use celestial_core::matrix::RotationMatrix3;
let mut m = RotationMatrix3::identity();
m.rotate_z(QUARTER_PI);
let (ra, dec) = m.transform_spherical(0.0, 0.0);
// ra = -0.7853981633974483 (-45°), dec = 0.0
Input and output are in radians. Output RA is in (-π, π] and output Dec is in
[-π/2, π/2]. Wrap the RA with wrap_0_2pi if you need it positive.
Invert a rotation
The inverse of a rotation matrix is its transpose. transpose() only swaps elements,
so it adds no rounding error:
use celestial_core::matrix::RotationMatrix3;
let mut m = RotationMatrix3::identity();
m.rotate_z(0.5);
m.rotate_x(0.3);
let rotated = m.apply_to_vector([1.0, 2.0, 3.0]);
let restored = m.transpose().apply_to_vector(rotated);
// restored = [1.0, 2.0, 2.9999999999999996]
The round trip lands within a bit of the start because each apply_to_vector rounds.
Check and compare matrices
use celestial_core::matrix::RotationMatrix3;
let mut m = RotationMatrix3::identity();
m.rotate_z(0.5);
m.is_rotation_matrix(1e-14); // true: orthogonal with determinant +1, within the tolerance
m.determinant(); // 1.0
let a = RotationMatrix3::identity();
a.max_difference(&m); // largest absolute element-wise difference
Read the elements
use celestial_core::matrix::RotationMatrix3;
let m = RotationMatrix3::identity();
let elems: &[[f64; 3]; 3] = m.elements();
elems[0][0]; // 1.0
Display a matrix
Display prints the matrix over several lines with nine decimal places:
use celestial_core::matrix::RotationMatrix3;
println!("{}", RotationMatrix3::identity());
// RotationMatrix3:
// [ 1.000000000 0.000000000 0.000000000]
// [ 0.000000000 1.000000000 0.000000000]
// [ 0.000000000 0.000000000 1.000000000]
Precession, nutation and obliquity
A star catalog gives positions on a fixed frame, the ICRS. Your telescope’s equatorial mount points along the Earth’s spin axis, and that axis doesn’t stay put. Take Polaris’s catalog position, ask where it sits relative to today’s pole and equinox, and the answer has moved by almost 9 arcminutes:
use celestial_core::angle::Angle;
use celestial_core::constants::MJD_ZERO_POINT;
use celestial_core::math::angular_separation;
use celestial_core::matrix::Vector3;
use celestial_core::nutation::NutationIAU2006A;
use celestial_core::precession::PrecessionIAU2006;
use celestial_core::utils::jd_to_centuries;
// 2026 January 1, 0h TT, as a two-part Julian date
let (jd1, jd2) = (MJD_ZERO_POINT, 61041.0);
// Polaris in the ICRS: RA 37.95456°, Dec +89.26411°
let (ra0, dec0) = (
Angle::from_degrees(37.95456067).radians(),
Angle::from_degrees(89.26410897).radians(),
);
let polaris = Vector3::from_spherical(ra0, dec0);
let nutation = NutationIAU2006A::new().compute(jd1, jd2)?;
let npb = PrecessionIAU2006::new().npb_matrix_iau2006a(
jd_to_centuries(jd1, jd2),
nutation.delta_psi,
nutation.delta_eps,
)?;
let (ra, dec) = (npb * polaris).to_spherical();
println!(
"RA {:.4}°, Dec {:.4}°",
Angle::from_radians(ra).degrees(),
Angle::from_radians(dec).degrees()
);
// RA 46.3615°, Dec 89.3736°
let moved = angular_separation(ra0, dec0, ra, dec);
println!("{:.2}'", Angle::from_radians(moved).arcminutes());
// 8.88'
The star didn’t move. The coordinate grid did. This page explains why, and which parts
of celestial-core model each piece of that motion.
The example above leaves out proper motion, aberration and light deflection.
celestial-coords applies those and calls these same functions underneath, so reach
for it when you want an apparent place. Use the functions on this page when you need
the rotation matrices themselves.
Why the pole and the equinox move
Right ascension and declination are measured against two references: the celestial pole, where the Earth’s axis points, and the equinox, where the equator crosses the ecliptic. Both drift, for three reasons.
Precession. The Sun and Moon pull on the Earth’s equatorial bulge and try to tip it into the ecliptic. The spinning Earth responds the way a top does: its axis sweeps a slow cone around the ecliptic pole, once every 26,000 years or so. The equinox slides west along the ecliptic by about 50″ a year, which is the 5038.48″ per century in the IAU 2006 precession polynomial.
Nutation. The same torques vary as the Moon’s orbit and the Earth’s orbit change geometry, so the pole wobbles around its precessing mean position. The largest term has the 18.6-year period of the Moon’s orbital nodes and an amplitude of about 9″ in obliquity. The full series sums well over a thousand smaller terms.
Obliquity. The tilt between the equator and the ecliptic is about 23.44° and shrinks by about 47″ per century. It sets the geometry for converting between equatorial and ecliptic coordinates, and it is one of the angles in the precession matrix.
Two words carry through the rest of the library. Mean means precession only: the mean equator and equinox of date. True means precession plus nutation: the true equator and equinox of date.
The models
celestial-core implements the IAU models that ERFA implements, and tests each one
against ERFA output with exact equality.
| Quantity | Type or function | Model |
|---|---|---|
| Precession | PrecessionIAU2006 | IAU 2006, Fukushima-Williams angles |
| Precession | PrecessionIAU2000 | Lieske et al. (1977) angles with the IAU 2000 rate corrections |
| Nutation | NutationIAU2006A | IAU 2000A, scaled for use with IAU 2006 precession |
| Nutation | NutationIAU2000A | IAU 2000A: 678 lunisolar and 687 planetary terms |
| Nutation | NutationIAU2000B | IAU 2000B: the first 77 lunisolar terms plus a fixed planetary offset |
| Mean obliquity | iau_2006_mean_obliquity | IAU 2006 |
| Mean obliquity | iau_1980_mean_obliquity | IAU 1980 |
For new work, use IAU 2006 precession with NutationIAU2006A. That pairing is what
celestial-time uses for sidereal time and what celestial-coords uses for the CIRS.
NutationIAU2006A runs the IAU 2000A series and then scales Δψ and Δε by factors of a
few parts per million, so the nutation agrees with the IAU 2006 precession rate.
NutationIAU2000B trades accuracy for speed. The IERS Conventions (2003) describe it as
a model for users who need the pole only at the 1 mas level, and say it stays within
1 mas of IAU 2000A over 1995 to 2050. It evaluates 77 terms where IAU 2000A evaluates
1365.
The IAU 2000 precession and IAU 1980 obliquity are here for matching older software and published values that used them.
Precession
compute takes a TT date and returns three rotation matrices in a PrecessionResult:
use celestial_core::angle::Angle;
use celestial_core::constants::MJD_ZERO_POINT;
use celestial_core::matrix::Vector3;
use celestial_core::precession::PrecessionIAU2006;
let (jd1, jd2) = (MJD_ZERO_POINT, 61041.0);
let polaris = Vector3::from_spherical(
Angle::from_degrees(37.95456067).radians(),
Angle::from_degrees(89.26410897).radians(),
);
let p = PrecessionIAU2006::new().compute(jd1, jd2)?;
// p.bias_matrix: GCRS to mean equator and equinox of J2000.0 (fixed)
// p.precession_matrix: mean J2000.0 to mean equator and equinox of date
// p.bias_precession_matrix: the two combined, GCRS to mean of date
let (ra, dec) = (p.bias_precession_matrix * polaris).to_spherical();
println!(
"RA {:.4}°, Dec {:.4}°",
Angle::from_radians(ra).degrees(),
Angle::from_radians(dec).degrees()
);
// RA 46.4616°, Dec 89.3716°
This is the mean place. It differs from the opening example’s 46.3615°, 89.3736° by the nutation that example included.
The frame bias is a fixed rotation of a few tens of milliarcseconds. The ICRS axes are set by distant radio sources, and they don’t line up exactly with the mean equator and equinox of J2000.0. The bias matrix rotates from one to the other. You’ll rarely need it on its own, but it’s there for checking against published tables.
PrecessionIAU2000 returns the same three matrices from the older model. For IAU 2006,
fukushima_williams_angles(t) also returns the four angles the matrix is built from,
with t in Julian centuries of TT since J2000.0.
Nutation
Each nutation model returns a NutationResult with two angles in radians: delta_psi
(Δψ), the nutation in longitude, and delta_eps (Δε), the nutation in obliquity.
use celestial_core::constants::{ARCSEC_PER_RAD, MJD_ZERO_POINT};
use celestial_core::nutation::{NutationIAU2000B, NutationIAU2006A};
let (jd1, jd2) = (MJD_ZERO_POINT, 61041.0);
let full = NutationIAU2006A::new().compute(jd1, jd2)?;
let short = NutationIAU2000B::new().compute(jd1, jd2)?;
println!("Δψ = {:.4}\" Δε = {:.4}\"", full.delta_psi * ARCSEC_PER_RAD, full.delta_eps * ARCSEC_PER_RAD);
// Δψ = 5.4206" Δε = 8.0656"
let mas = 1000.0 * ARCSEC_PER_RAD;
println!(
"2000B - 2006A: Δψ {:.3} mas, Δε {:.3} mas",
(short.delta_psi - full.delta_psi) * mas,
(short.delta_eps - full.delta_eps) * mas
);
// 2000B - 2006A: Δψ 0.528 mas, Δε -0.175 mas
On that date the short model is half a milliarcsecond off in longitude. For pointing a telescope that’s nothing. For VLBI or reducing Gaia-grade astrometry, use the full model.
Combine precession and nutation
PrecessionIAU2006::npb_matrix_iau2006a builds a single matrix from the GCRS to the
true equator and equinox of date. It adds Δψ and Δε to the Fukushima-Williams angles
before building the rotation, which is how ERFA builds its IAU 2006/2000A matrix. The
opening example uses it.
This method takes Julian centuries of TT, not a two-part date. Convert with
celestial_core::utils::jd_to_centuries(jd1, jd2).
Obliquity
Both obliquity functions return the mean obliquity in radians. Add Δε for the true obliquity:
use celestial_core::angle::{Angle, DmsFmt};
use celestial_core::constants::MJD_ZERO_POINT;
use celestial_core::nutation::NutationIAU2006A;
use celestial_core::obliquity::{iau_1980_mean_obliquity, iau_2006_mean_obliquity};
let (jd1, jd2) = (MJD_ZERO_POINT, 61041.0);
let fmt = DmsFmt { frac_digits: 3 };
let mean = iau_2006_mean_obliquity(jd1, jd2)?;
let true_eps = mean + NutationIAU2006A::new().compute(jd1, jd2)?.delta_eps;
println!("mean {}", fmt.fmt(Angle::from_radians(mean)));
println!("true {}", fmt.fmt(Angle::from_radians(true_eps)));
println!("1980 {}", fmt.fmt(Angle::from_radians(iau_1980_mean_obliquity(jd1, jd2)?)));
// mean +23° 26' 9.228"
// true +23° 26' 17.294"
// 1980 +23° 26' 9.276"
The two mean values differ by 48 mas. Most of that is a different value at J2000.0, 84381.406″ for IAU 2006 against 84381.448″ for IAU 1980.
Dates and time scales
Every function here takes Terrestrial Time (TT). Passing UTC puts you about 69 seconds
off, which shifts nutation by a negligible amount but is still the wrong input. If you
hold a celestial_time::scales::tt::TT, its to_julian_date() returns a JulianDate
with jd1() and jd2().
Dates go in as two parts, jd1 + jd2, and the models never add them before subtracting
J2000. That keeps the time of day precise in jd2. Two splits work well: J2000_JD
plus days since J2000, or MJD_ZERO_POINT plus the Modified Julian Date. Both
constants are in celestial_core::constants.
The polynomials in these models are fitted to observations near J2000.0 and diverge far
from it. Every compute call, both obliquity functions and the CIO locator reject
dates more than MAX_CENTURIES_FROM_J2000 (20 centuries) from J2000.0, and they reject
NaN and infinite dates:
use celestial_core::constants::J2000_JD;
use celestial_core::precession::PrecessionIAU2006;
let err = PrecessionIAU2006::new().compute(J2000_JD, 1.0e6).unwrap_err();
println!("{err}");
// Math error in model epoch (out of range): Epoch 27.4 centuries from J2000.0 is outside the model range
Edge cases
fukushima_williams_anglesandnpb_matrix_iau2006atake Julian centuries directly. They return an error for NaN or infinite input, but they don’t apply the 20-century limit, so the date check happens in the nutationcomputecall you make to get Δψ and Δε.NutationResultholds the nutation alone. The IAU 2000A frame bias and precession-rate corrections are inside the precession models, not added to Δψ and Δε.
Where next
- The CIO and the equinox turns the matrix from this page into the frame the Earth rotates in.
- Ecliptic coordinates covers the fixed ecliptic frame the planetary theories use.
- Vectors and rotation matrices explains how to apply and compose the matrices.
The CIO and the equinox
To get from a catalog position to where a star is in the sky above you, you need the star’s position relative to the Earth’s true pole of date, and an angle that says how far the Earth has turned. Right ascension has to be measured from some origin on the true equator, and the Earth’s rotation is measured from the same origin. There are two choices of origin, and they lead to two equivalent chains:
| Equinox-based | CIO-based | |
|---|---|---|
| Origin of right ascension | true equinox of date | Celestial Intermediate Origin (CIO) |
| Matrix from the GCRS | npb_matrix_iau2006a | gcrs_to_cirs_matrix(x, y, s) |
| Frame of date | true equator and equinox | CIRS |
| Earth rotation | Greenwich apparent sidereal time (GAST) | Earth rotation angle (ERA) |
Both use the same pole, so they agree on declination. Right ascensions differ by the equation of the origins (EO), the arc between the two origins:
use celestial_core::angle::Angle;
use celestial_core::cio::{gcrs_to_cirs_matrix, CioSolution};
use celestial_core::constants::{ARCSEC_PER_RAD, MJD_ZERO_POINT};
use celestial_core::matrix::Vector3;
use celestial_core::nutation::NutationIAU2006A;
use celestial_core::precession::PrecessionIAU2006;
use celestial_core::utils::jd_to_centuries;
let (jd1, jd2) = (MJD_ZERO_POINT, 61041.0); // 2026 January 1, 0h TT
let t = jd_to_centuries(jd1, jd2);
let polaris = Vector3::from_spherical(
Angle::from_degrees(37.95456067).radians(),
Angle::from_degrees(89.26410897).radians(),
);
let nutation = NutationIAU2006A::new().compute(jd1, jd2)?;
let npb = PrecessionIAU2006::new().npb_matrix_iau2006a(t, nutation.delta_psi, nutation.delta_eps)?;
let cio = CioSolution::calculate(&npb, t)?;
let gcrs_to_cirs = gcrs_to_cirs_matrix(cio.cip.x, cio.cip.y, cio.s)?;
// Equinox-based: RA measured from the true equinox of date
let (ra_equinox, dec_equinox) = (npb * polaris).to_spherical();
// CIO-based: RA measured from the CIO
let (ra_cio, dec_cio) = (gcrs_to_cirs * polaris).to_spherical();
println!("Dec difference: {}\"", (dec_cio - dec_equinox) * ARCSEC_PER_RAD);
println!("RA difference: {:.6}\"", (ra_cio - ra_equinox) * ARCSEC_PER_RAD);
println!("EO: {:.6}\"", cio.equation_of_origins * ARCSEC_PER_RAD);
// Dec difference: 0"
// RA difference: -1204.241814"
// EO: -1204.241814"
In 2026 the two origins are about 20 arcminutes apart. When you turn the Earth, that offset cancels: GAST is ERA minus EO, so the hour angle comes out the same either way.
Why there are two
The equinox is where the true equator crosses the ecliptic. It moves along the equator with precession and nutation, so sidereal time, which is measured from it, mixes the Earth’s rotation with the motion of the equinox. Computing GAST means evaluating the precession and nutation models inside the rotation angle.
The CIO is defined so that it has no motion along the equator as the pole moves. The angle from it to the Earth’s reference meridian, the ERA, is a linear function of UT1 and nothing else. That separates the Earth’s spin from the motion of its axis. IAU Resolution B1.8 (2000) recommends this non-rotating origin, and the IERS Conventions build their celestial-to-terrestrial transformation on it.
The equinox-based chain stays useful because so much else uses it: sidereal time on a
mount controller, apparent places in almanacs, and older software you need to match.
celestial-coords builds its CIRS with the CIO-based matrix. celestial-time computes
GAST as ERA minus the EO from CioSolution.
The CIO quantities
Three numbers locate the CIRS against the GCRS:
- X and Y are the coordinates of the Celestial Intermediate Pole (CIP), the pole of
date, in the GCRS. They are elements
[2][0]and[2][1]of the NPB matrix. - s, the CIO locator, places the CIO on the CIP’s equator. It comes from a series in time plus a −XY/2 term.
- EO, the equation of the origins, is the arc from the CIO to the true equinox.
CioSolution::calculate takes the NPB matrix and the date in Julian centuries of TT,
and returns all three:
use celestial_core::cio::CioSolution;
use celestial_core::constants::{ARCSEC_PER_RAD, MJD_ZERO_POINT};
use celestial_core::nutation::NutationIAU2006A;
use celestial_core::precession::PrecessionIAU2006;
use celestial_core::utils::jd_to_centuries;
let (jd1, jd2) = (MJD_ZERO_POINT, 61041.0);
let t = jd_to_centuries(jd1, jd2);
let nutation = NutationIAU2006A::new().compute(jd1, jd2)?;
let npb = PrecessionIAU2006::new().npb_matrix_iau2006a(t, nutation.delta_psi, nutation.delta_eps)?;
let cio = CioSolution::calculate(&npb, t)?;
println!("{}", cio.cip);
println!("s = {:.6}\"", cio.s * ARCSEC_PER_RAD);
println!("EO = {:.3}\"", cio.equation_of_origins * ARCSEC_PER_RAD);
// CIP(X=523.244", Y=6.525")
// s = -0.007643"
// EO = -1204.242"
X grows by about 2000″ per century as the pole precesses. Near the present, Y is a few arcseconds and s is a few milliarcseconds.
Each piece is also available on its own:
CipCoordinates::from_npb_matrixreads X and Y out of the matrix. It returns an error if either is beyond 0.2 radians, because no NPB matrix within the models’ 20-century range puts the pole that far off. At 20 centuries from J2000.0, X reaches about 0.19.CioLocator::iau2006a(t).calculate(x, y)evaluates s with the IAU 2006/2000A series: 66 periodic terms across five powers of t.equation_of_origins(&npb, s)computes EO from the matrix.
gcrs_to_cirs_matrix(x, y, s) then builds the rotation from the GCRS to the CIRS.
Earth orientation corrections
The nutation models leave out effects that can’t be predicted, such as the free core
nutation. The IERS publishes the observed offsets of the pole as dX and dY, in
milliarcseconds. celestial-core doesn’t read IERS data, so CioSolution gives the
model’s X and Y. celestial-coords adds dX and dY from its bundled IERS tables before
it calls gcrs_to_cirs_matrix. To apply your own, add them to cio.cip.x and
cio.cip.y and pass the sums.
Edge cases
gcrs_to_cirs_matrixreturns an error when X² + Y² exceeds 1 orsisn’t finite. The CIP must lie on the unit sphere.CioSolution::calculateneeds the GCRS-to-true-of-date matrix that includes frame bias. The bias-freeprecession_matrixfromPrecessionResultgives the wrong X and Y.
Where next
- Precession, nutation and obliquity covers the models behind the NPB matrix.
- Vectors and rotation matrices explains
rotate_zand the other rotationsgcrs_to_cirs_matrixcomposes.
Ecliptic coordinates
Planetary theories work in the plane of the Earth’s orbit, because that’s where the
planets are. VSOP2013 gives its positions on the ecliptic and equinox of J2000.0, and
everything else in the library works on ICRS axes. celestial_core::ecliptic converts
between the two:
use celestial_core::angle::Angle;
use celestial_core::ecliptic::vsop2013_to_icrs;
use celestial_core::matrix::Vector3;
// The June solstice point: ecliptic longitude 90°, latitude 0°
let solstice = Vector3::from_spherical(Angle::from_degrees(90.0).radians(), 0.0);
let (ra, dec) = vsop2013_to_icrs(&solstice).to_spherical();
println!(
"RA {:.9}°, Dec {:.9}°",
Angle::from_radians(ra).degrees(),
Angle::from_radians(dec).degrees()
);
// RA 89.999985589°, Dec 23.439280933°
The declination is the obliquity of the frame, 84381.41136″. The right ascension misses 90° by 0.052″, which is the second angle in the rotation.
The VSOP2013 frame
The VSOP2013 paper (eq. 3) defines its ecliptic frame from the ICRS with two rotations:
ecliptic = R1(ε) R3(φ) ICRS
ε = 84381.41136″ VSOP2013_OBLIQUITY_RAD
φ = -0.05188″ VSOP2013_PHI_RAD
ε tilts the equator into the ecliptic. φ is a small rotation about the pole, because the
dynamical equinox of J2000.0 is not exactly at the ICRS origin of right ascension. Both
constants are in celestial_core::constants.
This frame is fixed. It’s the J2000.0 ecliptic, so the obliquity here is a constant and
is not the IAU 2006 mean obliquity of any date. That makes it the right frame for
heliocentric positions from the planetary theories and the wrong one for an “ecliptic
longitude of date”. For ecliptic coordinates of date, celestial-coords has
EclipticPosition, which uses iau_2006_mean_obliquity from
the obliquity models.
Convert both ways
vsop2013_to_icrs and icrs_to_vsop2013 take and return a Vector3. Any length works,
so you can pass positions in AU, velocities in AU/day or unit vectors:
use celestial_core::ecliptic::{icrs_to_vsop2013, vsop2013_to_icrs};
use celestial_core::matrix::Vector3;
// Pluto's heliocentric position in the VSOP2013 frame, in AU
let ecliptic = Vector3::new(-9.8753625435, -27.958861371, 5.8504463318);
let icrs = vsop2013_to_icrs(&ecliptic);
println!("{icrs}");
// Vector3(-9.875369581, -27.978926225, -5.753711825)
assert_eq!(icrs_to_vsop2013(&icrs), ecliptic);
Pluto sits 5.85 AU above the ecliptic but 5.75 AU south of the equator. A sign change like this is a quick check that you applied the rotation in the right direction.
The round trip is exact for this vector, but don’t count on that in general. Each direction rounds, and many vectors come back a few bits away from where they started. Compare with a tolerance when you test a round trip of your own.
Where next
- Planets, Sun and Moon uses this rotation to return VSOP2013 positions on ICRS axes.
- Precession, nutation and obliquity covers the obliquity of date and the models that move the equator.
Observer locations
Anything you compute for a telescope, such as hour angle, altitude or the Moon’s parallax,
depends on where the telescope is. Location holds that: a geodetic latitude, longitude
and height on the WGS84 ellipsoid, the same coordinates a GPS receiver reports.
use celestial_core::location::Location;
// Mauna Kea: latitude, longitude (east positive), height above the WGS84 ellipsoid
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
site.latitude_degrees(); // 19.8207
site.longitude_degrees(); // -155.4681
site.height(); // 4205.0, meters
site.latitude(); // 0.34593647505004005, radians
site.latitude_angle(); // an Angle
Location is Copy. You build it once per site and pass it to celestial-coords and
celestial-time wherever they need an observer.
Conventions
- Latitude is north positive, from -90° to +90°.
- Longitude is east positive, from -180° to +180°. West longitudes are negative.
- Height is in meters above the WGS84 ellipsoid, not above sea level. The two differ by the local geoid height, which can be tens of meters. For most astronomy that error doesn’t matter, but use the ellipsoid height from a GPS fix when you have it.
Location stores radians. new(latitude, longitude, height) takes radians directly, and
from_degrees converts with correct rounding, so 45° becomes exactly the f64 nearest
π/4.
East longitudes from 0° to 360°
Some observatory lists give longitude east from 0° to 360°. from_degrees accepts that
form and stores the equivalent value in the -180° to +180° range:
use celestial_core::location::Location;
let west = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let east = Location::from_degrees(19.8207, 204.5319, 4205.0)?;
east.longitude_degrees(); // -155.4681
west == east; // true
new doesn’t do this. Radians outside -π to π are an error.
Validation
Both constructors check their input and return an AstroError for anything that
isn’t a place an observer could be:
use celestial_core::location::Location;
let err = Location::from_degrees(95.0, 10.0, 0.0).unwrap_err();
println!("{err}");
// Math error in location_validation (out of range): Latitude outside valid range [-90°, +90°]
let err = Location::from_degrees(19.8207, -155.4681, f64::NAN).unwrap_err();
println!("{err}");
// Math error in location_validation (not finite): Height must be finite
Height must fall between -12,000 m and 100,000 m. That covers the floor of the Mariana Trench and balloon altitudes. It won’t catch a height given in feet or kilometers, because those usually land inside the range too.
With the serde feature, deserializing runs the same checks. The fields are latitude,
longitude and height, in radians and meters. A file written in degrees usually
fails to load instead of loading as the wrong place:
use celestial_core::location::Location;
let json = r#"{"latitude": 0.3459, "longitude": -2.7134, "height": 4205.0}"#;
let site: Location = serde_json::from_str(json)?;
let bad = r#"{"latitude": 19.8, "longitude": -155.5, "height": 4205.0}"#;
assert!(serde_json::from_str::<Location>(bad).is_err()); // degrees, not radians
Position relative to the Earth’s center
Geodetic latitude is the angle of the ellipsoid’s surface normal, not the angle from the Earth’s center. Because the Earth bulges at the equator, the two differ by up to about 11 arcminutes. Parallax needs the second kind: where the observer is in space.
to_geocentric_meters and to_geocentric_km return that position as (u, v): u is
the distance from the rotation axis and v the distance from the equatorial plane,
positive north.
use celestial_core::location::Location;
use celestial_core::matrix::Vector3;
use celestial_core::angle::Angle;
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let (u, v) = site.to_geocentric_km();
println!("u = {u:.3} km, v = {v:.3} km");
// u = 6006.552 km, v = 2150.460 km
let (_, geocentric_lat) = Vector3::new(u, 0.0, v).to_spherical();
println!("{:.4}°", Angle::from_radians(geocentric_lat).degrees());
// 19.6983°
At Mauna Kea the geocentric latitude is 0.12° south of the geodetic one. For the Moon,
whose diurnal parallax reaches about 1°, that offset matters. celestial-coords uses
to_geocentric_meters for its diurnal parallax correction.
The conversion matches ERFA’s gd2gce on the WGS84 ellipsoid. For Cartesian
coordinates in an Earth-fixed frame, rotate by longitude: x = u·cos(lon),
y = u·sin(lon), z = v.
Edge cases
Location::greenwich()returns latitude 0, longitude 0 and height 0. That point is on the Greenwich meridian at the equator, not at the Royal Observatory, which is at about 51.48° N.- Longitudes from 180° to 360° are wrapped by
from_degreesonly. Values below -180° are an error in both constructors.
Where next
- Angles for
latitude_angle()andlongitude_angle(), and for parsing site coordinates from strings. - Precession, nutation and obliquity for the Earth-side models that combine with a location to give hour angle and altitude.
Time scales
The timestamp in your image header is UTC. Precession and nutation want Terrestrial Time. Sidereal time wants UT1 for the Earth’s rotation. A planetary theory wants Barycentric Dynamical Time. All four name the same instant, and they disagree by more than a minute:
use celestial_time::julian::JulianDate;
use celestial_time::scales::conversions::tcb_tdb::TdbToTcb;
use celestial_time::scales::conversions::tt_tdb::ToTDB;
use celestial_time::scales::conversions::utc_ut1::ToUT1WithDUT1;
use celestial_time::scales::conversions::{ToGPS, ToTAI, ToTCG, ToTT};
use celestial_time::scales::utc::UTC;
let utc: UTC = "2026-03-20T14:46:00Z".parse()?;
let tai = utc.to_tai()?;
let tt = tai.to_tt()?;
let gps = tai.to_gps()?;
let ut1 = utc.to_ut1_with_dut1(0.0624)?; // UT1 - UTC, from IERS data
let tcg = tt.to_tcg()?;
let tdb = tt.to_tdb_greenwich()?;
let tcb = tdb.tdb_to_tcb()?;
let utc_jd = utc.to_julian_date();
let ahead = |jd: JulianDate| (jd - utc_jd) * 86400.0;
println!("TAI - UTC = {:.6} s", ahead(tai.to_julian_date()));
println!("GPS - UTC = {:.6} s", ahead(gps.to_julian_date()));
println!("TT - UTC = {:.6} s", ahead(tt.to_julian_date()));
println!("UT1 - UTC = {:.6} s", ahead(ut1.to_julian_date()));
println!("TDB - UTC = {:.6} s", ahead(tdb.to_julian_date()));
println!("TCG - UTC = {:.6} s", ahead(tcg.to_julian_date()));
println!("TCB - UTC = {:.6} s", ahead(tcb.to_julian_date()));
// TAI - UTC = 37.000000 s
// GPS - UTC = 18.000000 s
// TT - UTC = 69.184000 s
// UT1 - UTC = 0.062400 s
// TDB - UTC = 69.185580 s
// TCG - UTC = 70.266396 s
// TCB - UTC = 93.266663 s
Pass UTC where TT belongs and nutation is computed for a moment 69 seconds away. Pass
TT where UT1 belongs and the sky is rotated by about 17 arcminutes. celestial-time
turns these mistakes into compile errors. Each scale is its own type, and functions
such as GMST::from_ut1_and_tt(&UT1, &TT) ask for the scale they need.
Why there are so many
Each scale answers a different question, and no single clock answers all of them.
How much time has passed? Atomic clocks answer this. TAI (International Atomic Time) is the average of hundreds of them, kept by the BIPM. It never jumps, so it’s the scale to subtract when you want an interval. GPS time is TAI minus a fixed 19 seconds, set when GPS started in 1980.
What time is it on the wall? Civil time follows the Sun, and the Sun follows the Earth’s rotation, which is irregular and slowly getting longer. UTC ticks atomic seconds like TAI, but the IERS adds a leap second now and then to keep it within 0.9 s of the Earth’s rotation. TAI - UTC was 10 s in 1972 and has been 37 s since 2017. UTC and leap seconds covers how that works.
Which way is the Earth facing? UT1 is the Earth’s rotation angle expressed as a time. It can’t be predicted far ahead, so the IERS measures it and publishes UT1 - UTC, called DUT1. Sidereal time uses it.
What time argument do the theories use? Equations of motion need a uniform time.
TT (Terrestrial Time) is the one for geocentric work: TAI plus exactly 32.184 s, an
offset chosen to continue the older Ephemeris Time. The precession and nutation models
in celestial-core take TT.
What about relativity? A clock’s rate depends on its speed and the gravity around it, so “uniform time” depends on where you put the clock. Three more scales handle that:
- TCG (Geocentric Coordinate Time) is the time of a clock at the Earth’s center, outside the Earth’s gravity. It runs faster than TT by the defining rate L_G = 6.969290134e-10, about 22 ms a year.
- TCB (Barycentric Coordinate Time) is the same idea at the solar system’s center of mass. It runs faster than TDB by L_B = 1.550519768e-8, about 0.49 s a year.
- TDB (Barycentric Dynamical Time) is TCB rescaled so it keeps pace with TT on
average. TDB - TT oscillates by about 1.7 ms over a year and never drifts away. The
theories in
celestial-ephemeristake TDB.
TCG and TCB matter for relativistic modeling such as pulsar timing and VLBI. For most work you need UTC to read your timestamps, TT for the IAU models, UT1 for the Earth’s rotation and TDB for the ephemerides.
How the scales connect
Every conversion goes through a trait method. Some pairs are fixed offsets or defined rates and need nothing else. The rest need data you supply:
UTC --(leap second table)-- TAI --(32.184 s)-- TT --(series)-- TDB --(L_B)-- TCB
| | |
| (19 s) (L_G)
| | |
| GPS TCG
|
+--(DUT1)-- UT1 --(Delta T)-- TT
A conversion with no direct trait goes through TAI or TT. GPS to TT is
gps.to_tai()?.to_tt()?. UTC to TDB is utc.to_tai()?.to_tt()?.to_tdb_greenwich()?.
The table lists every trait. They’re all in celestial_time::scales::conversions; a
prefix such as utc_ut1:: is the submodule that defines the traits in that row.
| From and to | Traits | You supply |
|---|---|---|
| UTC and TAI | ToTAI, ToUTC | nothing |
| TAI and TT | ToTT, ToTAI | nothing |
| TAI or TT and TCG | ToTCG, ToTAI, ToTT | nothing |
| TAI and GPS | ToGPS, ToTAI | nothing |
| UTC and UT1 | utc_ut1::ToUT1WithDUT1, ToUTCWithDUT1 | DUT1 in seconds |
| TAI and UT1 | ut1_tai::ToUT1WithOffset, ToTAIWithOffset | UT1 - TAI in seconds |
| TT and UT1 | ut1_tai::ToUT1WithDeltaT, ToTTWithDeltaT | Delta T in seconds |
| TT and TDB | tt_tdb::ToTDB, ToTTFromTDB | observer location, Greenwich, or TDB - TT |
| TDB and TCB | tcb_tdb::TdbToTcb, TcbToTdb | nothing |
The crate ships no Earth orientation data. That’s why the UT1 conversions take an offset argument: DUT1 changes every day, and only you know which IERS bulletin you trust. Delta T (TT - UT1) is the same quantity from the other side, and the form you’ll find in tables of historical values.
TT to TDB depends on where you are
TDB - TT is mostly an annual term from the Earth’s elliptical orbit, but a clock on the
Earth’s surface also moves with the Earth’s spin. The series this crate uses, by
Fairhead and Bretagnon (1990), has 787 terms plus a few small terms that depend on the
observer. That’s why ToTDB asks where you are:
use celestial_core::location::Location;
use celestial_time::scales::conversions::tt_tdb::ToTDB;
use celestial_time::scales::tt::tt_from_calendar;
let mauna_kea = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
for month in [1, 4, 7, 10] {
let tt = tt_from_calendar(2026, month, 1, 0, 0, 0.0)?;
let at_greenwich = tt.to_tdb_greenwich()?.to_julian_date() - tt.to_julian_date();
let at_site = tt.to_tdb_with_location(&mauna_kea)?.to_julian_date() - tt.to_julian_date();
println!(
"2026-{month:02}-01 TDB - TT = {:+.6} ms, site - Greenwich = {:+.1} ns",
at_greenwich * 86400.0e3,
(at_site - at_greenwich) * 86400.0e9
);
}
// 2026-01-01 TDB - TT = -0.082117 ms, site - Greenwich = -817.1 ns
// 2026-04-01 TDB - TT = +1.629221 ms, site - Greenwich = -299.3 ns
// 2026-07-01 TDB - TT = +0.118783 ms, site - Greenwich = -905.4 ns
// 2026-10-01 TDB - TT = -1.629318 ms, site - Greenwich = -1136.5 ns
The site term is about a microsecond. For a planet position that’s nothing, and
to_tdb_greenwich() is fine. It uses the Royal Observatory at 51.477928° N, 0°, 46 m.
For pulsar timing or anything else at the microsecond level, pass your location.
The observer terms also need UT1 to know the local solar time. The location methods
take UT1 = TT, which moves the result by about 10 ns. When that matters, call
to_tdb_with_location_and_ut1_offset(&location, ut1_minus_tt) with UT1 - TT in
seconds (that is, minus Delta T). When you already have TDB - TT from elsewhere, such
as a JPL kernel, to_tdb_with_offset(seconds) applies it as given.
TDB has no to_tt(). ToTTFromTDB has the same four methods in the other direction,
so a TDB value can’t come back to TT without someone choosing a location.
Edge cases
UTC::j2000()and the other scales’j2000()return JD 2451545.0 on that scale. The J2000.0 epoch is defined in TT, soUTC::j2000()is 64.184 s after it andTAI::j2000()is 32.184 s after it.- Conversions reject a
JulianDatewith a NaN or infinite part, and reject NaN or infinite offsets such as DUT1, with aTimeError. ToTTFromTDBevaluates TDB - TT at the TDB date rather than the TT date. The two are 1.7 ms apart at most, which moves the result by less than a picosecond.
Where next
- UTC and leap seconds covers 23:59:60, the leap second table and Unix time.
- Two-part Julian dates explains how every scale stores an instant.
- Sidereal time turns UT1 and TT into the Earth’s rotation.
- Create and format times covers parsing strings, calendar fields and the system clock.
UTC and leap seconds
The last leap second so far came at the end of 2016. That night, clocks running UTC read
23:59:59, then 23:59:60, then 00:00:00. The minute had 61 seconds. Most software can’t
represent that second at all. celestial-time can:
use celestial_time::scales::conversions::{ToTAI, ToUTC};
use celestial_time::scales::utc::UTC;
for s in [
"2016-12-31T23:59:59Z",
"2016-12-31T23:59:60Z",
"2016-12-31T23:59:60.5Z",
"2017-01-01T00:00:00Z",
] {
let utc: UTC = s.parse()?;
let tai = utc.to_tai()?;
println!("{s} {tai} back: {}", tai.to_utc()?.to_iso8601()?);
}
// 2016-12-31T23:59:59Z TAI JD 2457753.5 + 1.0004050925925927 back: 2016-12-31T23:59:59.000
// 2016-12-31T23:59:60Z TAI JD 2457753.5 + 1.0004166666666667 back: 2016-12-31T23:59:60.000
// 2016-12-31T23:59:60.5Z TAI JD 2457753.5 + 1.0004224537037036 back: 2016-12-31T23:59:60.500
// 2017-01-01T00:00:00Z TAI JD 2457754.5 + 0.00042824074074074075 back: 2017-01-01T00:00:00.000
Each UTC instant maps to its own TAI instant and back, including the half second in the middle of the leap second.
Why UTC has leap seconds
UTC is a compromise between two kinds of time. Atomic clocks tick perfectly even seconds. The Earth’s rotation, which sets sunrise and noon, doesn’t: tides slow it down, and the core and atmosphere make it wander. TAI and UT1 roughly agreed in 1958; by 2017 they were 37 s apart.
UTC ticks atomic seconds, the same as TAI, and the IERS inserts a leap second at the end of June or December whenever UT1 (the Earth’s rotation) is about to get more than 0.9 s away. So UTC is always within a second of the sky, and TAI - UTC is a whole number of seconds that grows by one with each leap second: 10 s in 1972, 37 s since 2017.
The cost is that UTC isn’t uniform. A day that ends in a leap second is 86,401 s long.
Measure intervals in TAI
A UTC Julian date on a leap second day counts fractions of an 86,401 s day, so subtracting two UTC dates across the leap second gives the wrong answer:
use celestial_time::scales::conversions::ToTAI;
use celestial_time::scales::utc::UTC;
let before: UTC = "2016-12-31T23:59:59Z".parse()?;
let after: UTC = "2017-01-01T00:00:00Z".parse()?;
let utc_days = after.to_julian_date() - before.to_julian_date();
let tai_days = after.to_tai()?.to_julian_date() - before.to_tai()?.to_julian_date();
println!("UTC: {:.9} s", utc_days * 86400.0);
println!("TAI: {:.9} s", tai_days * 86400.0);
// UTC: 1.999976852 s
// TAI: 2.000000000 s
Two seconds passed: 23:59:59 to 23:59:60, then to 00:00:00. TAI gets it right. The UTC difference is off by 23 µs because the two dates fall in days of different lengths.
ERFA uses the same convention, and UTC Julian dates from this crate match its values
bit for bit. The rule that follows: convert to TAI or TT before you subtract, and use add_seconds on a TAI or TT value rather than a UTC one when you step across a
day that might end in a leap second.
Where 23:59:60 is allowed
A seconds value of 60 or more is accepted only in the last minute of a day that ends with a leap second, and only for UTC:
use celestial_time::scales::tai::TAI;
use celestial_time::scales::utc::{utc_from_calendar, UTC};
println!("{:?}", utc_from_calendar(2016, 12, 31, 23, 59, 60.0).is_ok());
println!("{:?}", "2026-12-31T23:59:60Z".parse::<UTC>());
println!("{:?}", "2016-12-31T23:59:60".parse::<TAI>());
// true
// Err(InvalidDate("time 23:59:60 is out of range"))
// Err(InvalidDate("time 23:59:60 is out of range"))
The other seven scales have no leap seconds, so every one of their days is 86,400 s.
The leap second table
The crate has a built-in table of TAI - UTC that starts on 1960-01-01, when UTC began.
Its last entry is 2017-01-01, after the leap second at the end of 2016.
get_tai_utc_offset reads it for a date and a fraction of the day:
use celestial_time::scales::common::get_tai_utc_offset;
for (year, month, day, fraction) in [
(1968, 6, 1, 0.5),
(1972, 1, 1, 0.0),
(2016, 12, 31, 0.0),
(2017, 1, 1, 0.0),
(2026, 3, 20, 0.0),
] {
let offset = get_tai_utc_offset(year, month, day, fraction)?;
println!("{year}-{month:02}-{day:02} + {fraction}: TAI - UTC = {offset} s");
}
// 1968-06-01 + 0.5: TAI - UTC = 6.50061 s
// 1972-01-01 + 0: TAI - UTC = 10 s
// 2016-12-31 + 0: TAI - UTC = 36 s
// 2017-01-01 + 0: TAI - UTC = 37 s
// 2026-03-20 + 0: TAI - UTC = 37 s
println!("{}", get_tai_utc_offset(1959, 12, 31, 0.0).unwrap_err());
// Invalid date: 1959-12-31: UTC is not defined before 1960-01-01
Dates before 1960 return an error, from this function and from every UTC conversion, because there was no UTC to convert to.
Before 1972, UTC worked differently. Its seconds were stretched slightly so that UTC followed the Earth’s rotation continuously, and it stepped by fractions of a second at irregular dates. TAI - UTC wasn’t a whole number, and it changed through each day. The table holds those rates for the 14 entries from 1960 to 1968, and the conversions apply them, which is why 1968-06-01 at noon gives 6.50061 s.
Every date after 2017-01-01 gets 37 s, which is still the correct value today. When the
IERS announces another leap second, the TAI_UTC_OFFSETS table in
celestial-time/src/constants.rs needs a new entry. Until it has one, UTC conversions
for dates after that leap second are off by a second. ERFA’s eraDat also returns 37 s
for late dates, and adds a warning status for years more than five after its release
year. This crate has no such warning.
Convert to and from Unix time
Unix time counts seconds since 1970-01-01 as if every day had 86,400 s. It has no value
for 23:59:60, so the timestamp after 23:59:59 on a leap second day is 00:00:00 the next
day. UTC::new and to_unix convert both ways:
use celestial_time::scales::utc::UTC;
let new_year = UTC::new(1_483_228_800, 0)?;
println!("{}", new_year.to_iso8601()?);
println!("{:?}", new_year.to_unix()?);
let leap: UTC = "2016-12-31T23:59:60.5Z".parse()?;
println!("{}", leap.to_unix().unwrap_err());
// 2017-01-01T00:00:00.000
// (1483228800, 0)
// Conversion error: 2016-12-31 86400.5 s after midnight is in the day's extra time, which Unix time cannot represent
to_unix returns an error for any instant inside a leap second rather than guessing
which neighbor you wanted. For every (seconds, nanos) that UTC::new accepts,
to_unix gives back the same pair.
Edge cases
- UT1 to UTC on 1960-01-01 still works. Its search for a nearby leap second reads the
day before as 0 s, as ERFA’s
eraUt1utcdoes, so it treats the start of UTC as a 0.94 s step. A UT1 date before 1960 returns an error. - The pre-1972 rates make
ToUTCiterate. It runs three steps, and the round trip from UTC to TAI and back comes within 20 ps. - UTC to UT1 takes TAI - UTC at 0h on the date, as ERFA does. Before 1972 that differs from the value at the time itself by up to 2.6 ms, so a UTC to UT1 to UTC round trip on those dates can be off by up to 2.6 ms, and by up to 0.11 s on a day that ends in a step. From 1972 on, the round trip is exact to within 1 ulp.
to_iso8601formats a pre-1972 day on an 86,400 s clock, even when that day ended in a fractional step.
Where next
- Sidereal time covers UT1 and DUT1, the other half of what leap seconds are about.
- Create and format times has the full parsing rules.
- Two-part Julian dates explains the
JD a + bvalues above.
Two-part Julian dates
Astronomers count time in days. The Julian date (JD) is the number of days since noon
on January 1, 4713 BC, in the Julian calendar, so a date this century is around 2.46 million. That’s a
convenient number for arithmetic and a bad one for a 64-bit float. An f64 near
2.46 million can only step in increments of about 40 microseconds, and anything smaller
rounds away:
use celestial_time::julian::JulianDate;
let start = JulianDate::from_calendar(2026, 3, 20, 14, 46, 0.0)?;
println!("{start}");
let later = start.add_seconds(1.0e-6);
println!("two parts: {:.3} µs", (later - start) * 86400.0e6);
let single = start.to_f64();
let single_later = single + 1.0e-6 / 86400.0;
println!("single f64: {:.3} µs", (single_later - single) * 86400.0e6);
let spacing = f64::from_bits(single.to_bits() + 1) - single;
println!("f64 spacing: {:.3} µs", spacing * 86400.0e6);
// JD 2461119.5 + 0.6152777777777778
// two parts: 1.000 µs
// single f64: 0.000 µs
// f64 spacing: 40.233 µs
The single f64 lost the microsecond entirely. JulianDate kept it, because it holds
the date as two f64 values, jd1 and jd2, whose sum is the Julian date. The large
part stays put and the small part carries the time of day with full precision. ERFA
and SOFA use the same representation, and every time scale in this crate stores its
instant this way.
How a date is split
Any split is valid: JD 2461120.0 is (2461120.0, 0.0), (2461119.5, 0.5) or
(2400000.5, 61119.5). Precision comes from keeping the large, round number in one
part and the small, detailed one in the other. Three splits are common:
| Split | Example | Made by |
|---|---|---|
| Midnight plus time of day | (2461119.5, 0.6152777777777778) | from_calendar, *_from_calendar, parsing |
| MJD zero point plus MJD | (2400000.5, 61132.3125) | from_julian_year |
| J2000.0 plus days | (2451545.0, 9570.115) | you, with JulianDate::new |
MJD_ZERO_POINT (2400000.5) and J2000_JD (2451545.0) are in
celestial_core::constants.
The models in celestial-core never add the two parts before subtracting J2000. They
compute (jd1 - J2000) + jd2, which keeps the low bits of jd2. Conversions between
scales change only the smaller part, so the split you start with survives a chain like
UTC to TAI to TT to TDB.
Create and read a date
use celestial_time::julian::JulianDate;
let a = JulianDate::new(2451545.0, 9570.115);
let b = JulianDate::from_calendar(2026, 3, 20, 14, 46, 0.0)?;
let c = JulianDate::from_julian_year(2026.25);
println!("{} {}", a.jd1(), a.jd2());
println!("{}", b.to_f64());
println!("{}", c);
println!("{}", b.to_julian_year());
// 2451545 9570.115
// 2461120.115277778
// JD 2400000.5 + 61132.3125
// 2026.2152369001444
to_f64() adds the parts. Use it for display or for code that only takes one number,
and expect to lose precision below about 40 µs.
j2000() returns JD 2451545.0 and unix_epoch() returns JD 2440587.5, the start of
1970-01-01.
from_calendar reads the date as Gregorian, with astronomical year numbering: year 0 is
1 BC and year -1 is 2 BC. It doesn’t apply leap seconds. Use it, or the scale-specific
tt_from_calendar and friends, for every scale except UTC, and utc_from_calendar for
UTC. Create and format times covers those.
Arithmetic
add_days and add_seconds return a new date. Whole days go into jd1 and the
fraction into jd2, so jd2 stays small after many steps:
use celestial_time::julian::JulianDate;
let start = JulianDate::new(2461119.5, 0.75);
println!("{}", start.add_days(1.5));
println!("{}", start.add_seconds(3600.0));
// JD 2461121.5 + 0.25
// JD 2461119.5 + 0.7916666666666666
Subtracting one JulianDate from another gives the difference in days as an f64. It
subtracts part by part, so a short interval between two large dates keeps its
precision.
Equality compares the dates, not the splits. Two values are equal when jd1 + jd2 is
the same number:
use celestial_time::julian::JulianDate;
println!("{}", JulianDate::new(2461119.5, 0.5) == JulianDate::new(2461120.0, 0.0));
// true
From a date to a time scale
A bare JulianDate doesn’t say which scale it’s on. The scale types wrap one and add
that meaning:
use celestial_time::julian::JulianDate;
use celestial_time::scales::tt::TT;
let jd = JulianDate::new(2451545.0, 9570.115);
let tt = TT::from_julian_date(jd);
let same: TT = jd.into();
println!("{tt}");
println!("{}", tt == same);
println!("{}", tt.to_julian_date().jd2());
// TT JD 2451545 + 9570.115
// true
// 9570.115
Every scale has from_julian_date, From<JulianDate>, to_julian_date, add_days
and add_seconds. To hand a date to a celestial-core model, read the parts back with
tt.to_julian_date().jd1() and .jd2().
Edge cases
JulianDate::newaccepts anyf64, including NaN. Conversions, sidereal time andTT::centuries_since_j2000return aTimeErrorfor a date with a non-finite part.julian_to_calendarworks for JD -68569.5 to 1e9, which reaches back to -4900-03-01. Building a date from calendar fields needs a year of -4799 or later. Both are ERFA’s limits (eraJd2calanderaCal2jd), so a date in the years -4900 to -4800 converts to a calendar date but not back.- On a UTC day that ends in a leap second, a UTC Julian date counts fractions of an 86,401 s day. UTC and leap seconds explains why to subtract in TAI.
Where next
- Time scales covers what the dates mean on each scale.
- Precession, nutation and obliquity shows the core
models that take
jd1andjd2.
Sidereal time
To point a telescope at a star, you need its hour angle: how far west of your meridian it is right now. Right ascension is fixed to the stars, so the hour angle is the right ascension subtracted from the local sidereal time, which is the right ascension crossing your meridian at that moment. Sidereal time is the Earth’s rotation measured against the stars instead of the Sun.
use celestial_core::location::Location;
use celestial_time::scales::conversions::utc_ut1::ToUT1WithDUT1;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
use celestial_time::sidereal::last::LAST;
let mauna_kea = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let utc: UTC = "2026-03-20T08:30:00Z".parse()?;
let tt = utc.to_tai()?.to_tt()?;
let ut1 = utc.to_ut1_with_dut1(0.0624)?; // UT1 - UTC, from IERS data
let last = LAST::from_ut1_tt_and_location(&ut1, &tt, &mauna_kea)?;
println!("{last}");
// Betelgeuse: RA 5h 55m 10.3s
let hour_angle = last.hour_angle_to_target(5.0 + 55.0 / 60.0 + 10.3 / 3600.0)?;
println!("hour angle {hour_angle:.4} h");
// LAST 9.994945h at (19.8207°, -155.4681°)
// hour angle 4.0754 h
hour_angle_to_target takes the right ascension in hours and returns the hour angle in
hours, from -12 up to but not including +12. Positive means west of the meridian: the
star has already transited. The example passes a catalog right ascension. For pointing
to the arcsecond, pass the apparent right ascension that the
coords apparent-place pages compute.
The rest of this page covers the two inputs, UT1 and TT, and the four kinds of sidereal time the crate computes.
UT1: where the Earth is pointing
Sidereal time follows the Earth’s actual rotation, and UT1 is the time scale that measures it. UT1 drifts against atomic time in ways nobody can predict far ahead, so the IERS measures it and publishes UT1 - UTC, called DUT1, in Bulletin A. Leap seconds keep DUT1 between -0.9 s and +0.9 s.
The crate ships no Earth orientation data, so you pass DUT1 yourself. Each second of
UT1 error rotates the sky by about 15 arcseconds, and leaving DUT1 at zero can put
you up to 13.5″ off. celestial-coords bundles IERS tables (see the
coords Earth orientation pages), or you can read Bulletin A directly.
use celestial_time::scales::conversions::utc_ut1::ToUT1WithDUT1;
use celestial_time::scales::conversions::ut1_tai::ToUT1WithDeltaT;
use celestial_time::scales::tt::tt_from_calendar;
use celestial_time::scales::utc::UTC;
// Modern dates: DUT1 from IERS Bulletin A
let utc: UTC = "2026-03-20T08:30:00Z".parse()?;
let ut1 = utc.to_ut1_with_dut1(0.0624)?;
// Historical dates: Delta T = TT - UT1, from a table of past values
let tt = tt_from_calendar(1900, 1, 1, 0, 0, 0.0)?;
let ut1_1900 = tt.to_ut1_with_delta_t(-2.7)?;
For dates before UTC existed, or far in the future, you’ll find Earth rotation as
Delta T (TT - UT1) instead. ToUT1WithDeltaT and ToTTWithDeltaT convert with it.
A third pair, ToUT1WithOffset and ToTAIWithOffset, takes UT1 - TAI.
Four kinds of sidereal time
Two choices give four types:
| Mean equinox | True equinox | |
|---|---|---|
| At Greenwich | GMST | GAST |
| At your longitude | LMST | LAST |
Greenwich or local is only a longitude offset. The local types add your east
longitude, and they keep the Location they were built with.
Mean or apparent is about which equinox the right ascension is measured from. Apparent sidereal time measures from the true equinox of date, which includes nutation. Mean sidereal time measures from the mean equinox, which leaves nutation out. To get the hour angle of an apparent place (the position after precession, nutation and aberration), use LAST. LMST is for comparing with older systems and published mean values.
The two differ by the equation of the equinoxes, about a second of time at most.
use celestial_core::constants::ARCSEC_PER_RAD;
use celestial_core::location::Location;
use celestial_time::scales::conversions::utc_ut1::ToUT1WithDUT1;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
use celestial_time::sidereal::gast::GAST;
use celestial_time::sidereal::gmst::GMST;
let mauna_kea = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let utc: UTC = "2026-03-20T08:30:00Z".parse()?;
let tt = utc.to_tai()?.to_tt()?;
let ut1 = utc.to_ut1_with_dut1(0.0624)?;
let gmst = GMST::from_ut1_and_tt(&ut1, &tt)?;
let gast = GAST::from_ut1_and_tt(&ut1, &tt)?;
println!("{gmst}");
println!("{gast}");
println!("{}", gmst.to_lmst(&mauna_kea)?);
println!("{}", gast.to_last(&mauna_kea)?);
let equation_of_equinoxes = (gast.radians() - gmst.radians()) * ARCSEC_PER_RAD;
println!("GAST - GMST = {equation_of_equinoxes:.4}\"");
// GMST 20.359379h
// GAST 20.359485h
// LMST 9.994839h at (19.8207°, -155.4681°)
// LAST 9.994945h at (19.8207°, -155.4681°)
// GAST - GMST = 5.7374"
Each type reads back as hours(), degrees() or radians(), or as a SiderealAngle
with angle(). All four have from_hours, from_degrees and from_radians too, for
sidereal times you read from a mount controller or a log; the local types also take a
&Location. Values wrap into 0 to 24 hours.
Going back is a longitude subtraction: LMST::to_gmst() and LAST::to_gast(). Moving
between mean and apparent needs the date, so LAST::to_lmst(&tt) and
LAST::to_gmst(&tt) take a &TT.
The Earth rotation angle
Sidereal time mixes two motions: the Earth spinning, and the equinox drifting along the equator with precession and nutation. The Earth rotation angle (ERA) is the spin alone. It’s a linear function of UT1:
use celestial_time::scales::conversions::utc_ut1::ToUT1WithDUT1;
use celestial_time::scales::utc::UTC;
use celestial_time::transforms::rotation::earth_rotation_angle;
let utc: UTC = "2026-03-20T08:30:00Z".parse()?;
let ut1 = utc.to_ut1_with_dut1(0.0624)?;
let era = earth_rotation_angle(&ut1.to_julian_date())?;
println!("ERA = {era:.9} rad");
// ERA = 5.324210701 rad
earth_rotation_angle takes the UT1 Julian date, not a UT1, and returns radians in
0 to 2π. The ERA is measured from the Celestial Intermediate Origin rather than the
equinox. The CIO and the equinox explains the
difference.
That’s also how the crate builds sidereal time from it, following the IAU 2006 definitions:
- GMST is the ERA plus a polynomial in TT for the accumulated precession of the
equinox. That’s why
from_ut1_and_tttakes both scales. - GAST is the ERA minus the equation of the origins, the arc from the CIO to the
true equinox. It computes that from the IAU 2006 precession and the IAU 2000A
nutation, scaled for IAU 2006, using
celestial-core’sCioSolution.
Both match ERFA’s eraGmst06 and eraGst06a to the last bit in the crate’s tests.
Nutation and precession from a TT
GAST needs nutation and precession for its TT date. The same calculations are available
on any TT value, so you don’t have to split the date into jd1 and jd2 yourself:
use celestial_core::constants::ARCSEC_PER_RAD;
use celestial_time::scales::tt::tt_from_calendar;
use celestial_time::transforms::nutation::NutationCalculator;
use celestial_time::transforms::precession::PrecessionCalculator;
let tt = tt_from_calendar(2026, 1, 1, 0, 0, 0.0)?;
let nutation = tt.nutation()?;
println!(
"{:?}: Δψ = {:.4}\" Δε = {:.4}\"",
nutation.model(),
nutation.nutation_longitude() * ARCSEC_PER_RAD,
nutation.nutation_obliquity() * ARCSEC_PER_RAD
);
let precession = tt.precession()?;
println!("{:?}", precession.model);
println!("{}", precession.bias_precession_matrix);
// IAU2006A: Δψ = 5.4206" Δε = 8.0656"
// IAU2006
// RotationMatrix3:
// [ 0.999979907 -0.005814188 -0.002526077]
// [ 0.005814188 0.999983097 -0.000007278]
// [ 0.002526077 -0.000007409 0.999996809]
nutation() uses IAU 2006A and precession() uses IAU 2006. The traits also have
nutation_iau2000a, nutation_iau2000b and precession_iau2000 for matching older
software. They call the celestial-core models described in
Precession, nutation and obliquity.
Edge cases
- GMST, GAST and the nutation and precession methods reject a TT date more than 20
centuries from J2000.0 with
TimeError::InvalidEpoch, because the IAU polynomials aren’t valid there. hour_angle_to_targetreturns -12 h, not +12 h, for a star exactly opposite the meridian.- A
from_radiansvalue in 0 to 2π is kept exactly as given, including 2π itself, so a value from ERFA’sanpreads back unchanged.hours()anddegrees()still wrap it to 0. - With the
serdefeature, deserializing a sidereal angle goes throughfrom_radiansorfrom_hours, so a stored value outside 0 to 24 h wraps the same way.
Where next
- Observer locations covers the
Locationthe local types take. - The CIO and the equinox explains ERA, GAST and the equation of the origins.
- The coords pages on the CIRS and observed places use ERA and UT1 to turn catalog positions into altitude and azimuth.
Create and format times
Timestamps arrive in different shapes: an ISO 8601 string in a FITS header, a Unix timestamp from a camera driver, year-month-day fields from a log, or the system clock. Each time scale type can be built from all of them, and the scale you build is the scale the timestamp is read on. Nothing converts behind your back.
use celestial_time::scales::tt::TT;
use celestial_time::scales::utc::UTC;
let utc: UTC = "2026-03-20T04:30:00Z".parse()?;
let tt: TT = "2026-03-20T04:30:00".parse()?;
println!("{utc}");
println!("{tt}");
// UTC JD 2461119.5 + 0.1875
// TT JD 2461119.5 + 0.1875
Both hold the same Julian date, and they’re different instants: 69.184 s apart. If
your string is UTC, which it almost always is, parse it as UTC and convert. See
Time scales for the conversions.
Parse a string
All eight scales implement FromStr. They accept one format:
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.fff...
±YYYYY-MM-DDTHH:MM:SS
- The separator between date and time is
T,tor a space. - Every field has a fixed width, with leading zeros:
03, not3. - A plain year has four digits. For years before 0 or after 9999, use the ISO 8601
expanded form: a sign and four or more digits, such as
-0500or+12000. Years run from -4799 to 2147483647. - The fraction of a second can have any number of digits.
- Leading and trailing whitespace is ignored.
UTCaccepts a trailingZorz. RFC 3339 allows either case forZandT. The other scales rejectZ, because it means UTC.- A seconds value of 60 is valid only for
UTC, on a day that ends in a leap second.
Everything else is an error. Here’s what the parser says about common mistakes:
use celestial_time::scales::tt::TT;
use celestial_time::scales::utc::UTC;
for s in [
"2026-03-20 04:30:00.123456789",
"2026-3-20T04:30:00",
"2026-03-20T04:30",
"2026-03-20T04:30:00+02:00",
"2026-02-30T00:00:00",
"2026-03-20T24:00:00",
"2026-03-20",
"2026-03-20T04:30:00Zx",
"-4800-01-01T00:00:00",
] {
println!("{s:?} -> {:?}", s.parse::<UTC>().map(|utc| utc.to_string()));
}
println!("{:?}", "2026-03-20T04:30:00Z".parse::<TT>());
// "2026-03-20 04:30:00.123456789" -> Ok("UTC JD 2461119.5 + 0.18750142889802085")
// "2026-3-20T04:30:00" -> Err(ParseError("Invalid month: '3'"))
// "2026-03-20T04:30" -> Err(ParseError("Invalid time format: '04:30'. Expected HH:MM:SS"))
// "2026-03-20T04:30:00+02:00" -> Err(ParseError("Invalid time format: '04:30:00+02:00'. Expected HH:MM:SS"))
// "2026-02-30T00:00:00" -> Err(InvalidDate("2026-02-30: day is out of range"))
// "2026-03-20T24:00:00" -> Err(ParseError("Hour out of range: 24"))
// "2026-03-20" -> Err(ParseError("Invalid datetime format: '2026-03-20'. Expected YYYY-MM-DDTHH:MM:SS"))
// "2026-03-20T04:30:00Zx" -> Err(ParseError("Unexpected text 'x' after the Z suffix: '2026-03-20T04:30:00Zx'"))
// "-4800-01-01T00:00:00" -> Err(ParseError("Year -4800 is out of range: years must be from -4799 to 2147483647"))
// Err(ParseError("Only UTC takes a Z suffix: '2026-03-20T04:30:00Z'"))
Time zone offsets aren’t supported. Convert the timestamp to UTC before you parse it.
An expanded year parses on every scale, but UTC began in 1960, so only the other scales can hold the year -500:
use celestial_time::scales::tt::TT;
use celestial_time::scales::utc::UTC;
println!("{}", "-0500-03-01T00:00:00".parse::<TT>()?);
println!("{}", "-0500-03-01T00:00:00Z".parse::<UTC>().unwrap_err());
// TT JD 1538497.5 + 0
// Invalid date: -0500-03-01: UTC is not defined before 1960-01-01
Build from calendar fields
Each scale module has a *_from_calendar function that takes year, month, day, hour,
minute and seconds:
use celestial_time::scales::tdb::tdb_from_calendar;
use celestial_time::scales::tt::tt_from_calendar;
use celestial_time::scales::utc::utc_from_calendar;
let utc = utc_from_calendar(2026, 3, 20, 4, 30, 0.0)?;
let tt = tt_from_calendar(2026, 3, 20, 4, 30, 0.0)?;
let tdb = tdb_from_calendar(2026, 3, 20, 4, 30, 0.0)?;
The others are tai_from_calendar, gps_from_calendar, ut1_from_calendar,
tcg_from_calendar and tcb_from_calendar. Each reads the fields on its own scale.
The year uses astronomical numbering, where year 0 is 1 BC. Dates are Gregorian, back to
the year -4799. utc_from_calendar also rejects dates before 1960-01-01.
utc_from_calendar is the one that knows about leap seconds. It accepts 23:59:60 on a
leap second day and stretches that day to 86,401 s. The other seven read every day as
86,400 s.
Build from a Unix timestamp
new(seconds, nanos) takes a count of seconds and nanoseconds since 1970-01-01:
use celestial_time::scales::tai::TAI;
use celestial_time::scales::utc::UTC;
let utc = UTC::new(1_774_000_000, 250_000_000)?;
println!("{}", utc.to_iso8601()?);
println!("{:?}", utc.to_unix()?);
let tai = TAI::new(1_774_000_000, 250_000_000);
println!("{tai}");
// 2026-03-20T09:46:40.250
// (1774000000, 250000000)
// TAI JD 2461119.5 + 0.40741030092592595
For UTC, this is Unix time: every day counts as 86,400 s, and the count skips leap
seconds. UTC::new returns an error if nanos is a billion or more. to_unix()
converts back, and UTC and leap seconds
covers what happens inside a leap second.
For the other scales, new reads the count on that scale and can’t fail. TAI::new(0, 0)
is 1970-01-01 00:00:00 TAI, not the Unix epoch. Use it when your source counts seconds
on that scale, and use UTC::new for an ordinary Unix timestamp.
Read the system clock
use celestial_time::scales::utc::UTC;
let now = UTC::now()?;
println!("{}", now.to_iso8601()?);
UTC::now() reads SystemTime and builds the value with UTC::new. It’s only as
accurate as your computer’s clock. System clocks count Unix time, and operating systems
handle a leap second in different ways, so a reading taken near one can be off by up to
a second.
Format a time
UTC::to_iso8601() writes the calendar date and time, rounded to the millisecond, and
shows a leap second as 60:
use celestial_time::scales::utc::UTC;
for s in ["2026-03-20T04:30:00.9996Z", "2016-12-31T23:59:60.25Z", "2026-12-31T23:59:59.9996Z"] {
let utc: UTC = s.parse()?;
println!("{}", utc.to_iso8601()?);
}
// 2026-03-20T04:30:01.000
// 2016-12-31T23:59:60.250
// 2027-01-01T00:00:00.000
The output has no Z, and no other scale has to_iso8601. A year after 9999 comes out
in the expanded form, such as +10000-01-01T00:00:00.000, so the parser reads every
string to_iso8601 writes. Every scale implements
Display, which prints the scale name and the two parts of the Julian date. For the
calendar date on another scale, julian_to_calendar returns the year, month, day and
fraction of the day:
use celestial_time::scales::conversions::utc_tai::julian_to_calendar;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
let utc: UTC = "2026-03-20T04:30:00Z".parse()?;
let tt = utc.to_tai()?.to_tt()?;
println!("{tt}");
let jd = tt.to_julian_date();
let (year, month, day, fraction) = julian_to_calendar(jd.jd1(), jd.jd2())?;
println!("{year}-{month:02}-{day:02} + {:.6} s", fraction * 86400.0);
// TT JD 2461119.5 + 0.18830074074074074
// 2026-03-20 + 16269.184000 s
With the serde feature, JulianDate, every scale type and the sidereal types
implement Serialize and Deserialize. A date serializes as its two parts.
Errors
Every fallible call returns TimeResult<T>, an alias for Result<T, TimeError>. Both
are at the crate root. TimeError has five variants:
| Variant | Returned for |
|---|---|
ParseError | a string that doesn’t match the format |
InvalidDate | a date or time that doesn’t exist, such as February 30 or 23:59:60 on a normal day, or a UTC date before 1960 |
ConversionError | a non-finite argument, a Julian date out of the calendar range, or a leap second sent to Unix time |
InvalidEpoch | a non-finite Julian date, or a TT date beyond the IAU models’ 20-century range |
CalculationError | a failure reported by a celestial-core model |
Where next
- Time scales shows how to convert what you’ve built.
- UTC and leap seconds explains 23:59:60.
- Two-part Julian dates explains the
JD a + binDisplayoutput.
From catalog to horizon
A star catalog gives you a direction in the ICRS, a frame centered on the solar
system’s barycenter and tied to distant quasars. Your telescope points in a frame fixed
to the ground under it. Between the two are the star’s own motion, the bending of light
by the Sun, the Earth’s orbital and rotational velocity, the motion of the Earth’s axis,
the Earth’s rotation and the atmosphere. celestial-coords gives each of those a step,
and each frame along the way its own type.
Here is every step for Barnard’s Star, seen from Mauna Kea before dawn on 2026 April 10, with how far each step moves it:
use celestial_coords::aberration::apply_light_deflection;
use celestial_coords::astrom::earth::EarthRotation;
use celestial_coords::astrom::Astrom;
use celestial_coords::eop::EopProvider;
use celestial_coords::frames::icrs::ICRSPosition;
use celestial_coords::frames::topocentric::refraction::Refraction;
use celestial_coords::proper_motion::CatalogStar;
use celestial_core::angle::Angle;
use celestial_core::constants::{J2000_JD, MJD_ZERO_POINT};
use celestial_core::location::Location;
use celestial_core::math::angular_separation;
use celestial_core::matrix::Vector3;
use celestial_time::julian::JulianDate;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::tt::TT;
use celestial_time::scales::utc::UTC;
// Angle between two directions, in arcseconds.
fn shift(a: Vector3, b: Vector3) -> f64 {
let ((ra1, dec1), (ra2, dec2)) = (a.to_spherical(), b.to_spherical());
Angle::from_radians(angular_separation(ra1, dec1, ra2, dec2)).arcseconds()
}
// When and where
let utc: UTC = "2026-04-10T14:00:00Z".parse()?;
let tt = utc.to_tai()?.to_tt()?;
let jd = utc.to_julian_date();
let eop = EopProvider::bundled()?.get((jd.jd1() - MJD_ZERO_POINT) + jd.jd2())?;
let mauna_kea = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
// Barnard's Star at the Gaia DR3 epoch, J2016.0
let barnard = CatalogStar {
ra: Angle::from_degrees(269.44850252543),
dec: Angle::from_degrees(4.73942005111),
pm_ra_cos_dec_mas_per_year: -801.551,
pm_dec_mas_per_year: 10362.394,
parallax_mas: 546.976,
radial_velocity_km_per_s: -110.47,
};
let j2016 = TT::from_julian_date(JulianDate::new(J2000_JD, 5844.0));
// 1. Proper motion: the star's ICRS place on the date
let moved = barnard.propagate(&j2016, &tt)?;
let catalog = ICRSPosition::new(barnard.ra, barnard.dec)?;
let icrs = ICRSPosition::new(moved.ra, moved.dec)?;
// 2 and 3. Light deflection, then aberration, seen from the site
let astrom = Astrom::for_site(&tt, &eop, &mauna_kea)?;
let deflected = apply_light_deflection(
icrs.unit_vector(),
astrom.sun_to_observer(),
astrom.sun_distance_au(),
);
let gcrs = astrom.icrs_to_gcrs(&icrs)?;
let geocentric = Astrom::with_eop(&tt, &eop)?.icrs_to_gcrs(&icrs)?;
// 4. Precession-nutation: GCRS to CIRS
let cirs = astrom.gcrs_to_cirs(&gcrs)?;
// 5. Earth rotation: hour angle, then the horizon
let hour_angle = EarthRotation::new(&tt, &eop)?.cirs_to_hour_angle(&cirs, &mauna_kea)?;
let horizon = hour_angle.to_topocentric()?;
// 6. Refraction
let air = Refraction::new(615.0, 2.0, 0.3, 0.55)?;
let observed = horizon.with_refraction(&air);
println!("proper motion {:9.3}\"", shift(catalog.unit_vector(), icrs.unit_vector()));
println!("light deflection {:9.3}\"", shift(icrs.unit_vector(), deflected));
println!("annual aberration {:9.3}\"", shift(deflected, geocentric.unit_vector()));
println!("diurnal aberration {:9.3}\"", shift(geocentric.unit_vector(), gcrs.unit_vector()));
println!("precession-nutation {:9.3}\"", shift(gcrs.unit_vector(), cirs.unit_vector()));
println!("refraction {:9.3}\"", (observed.elevation() - horizon.elevation()).arcseconds());
println!();
println!("HA {:.4} h, Dec {:.4}°", hour_angle.hour_angle().hours(), hour_angle.declination().degrees());
println!("az {:.4}°, el {:.4}°", observed.azimuth().degrees(), observed.elevation().degrees());
// proper motion 106.835"
// light deflection 0.003"
// annual aberration 11.471"
// diurnal aberration 0.289"
// precession-nutation 45.641"
// refraction 14.664"
//
// HA -1.0950 h, Dec 4.7630°
// az 131.1203°, el 68.0376°
The rest of this page goes through those steps in order. If you want the recipe without the tour, Find the altitude and azimuth of a star has it.
The frames
Each stage of the chain is a type in celestial_coords::frames:
| Type | Module | What the frame includes |
|---|---|---|
ICRSPosition | frames::icrs | The catalog place: barycentric, ICRS axes |
GCRSPosition | frames::gcrs | Light deflection and aberration, ICRS axes |
CIRSPosition | frames::cirs | Frame bias, precession and nutation |
HourAnglePosition | frames::topocentric | Earth rotation and the site’s longitude |
TopocentricPosition | frames::topocentric | The site’s latitude: azimuth and elevation |
TIRSPosition | frames::tirs | Earth rotation, as Cartesian x, y, z |
ITRSPosition | frames::itrs | Polar motion: Earth-fixed x, y, z |
The types keep you from mixing stages. A method that needs an apparent place takes a
GCRSPosition or CIRSPosition, so you can’t pass it a catalog place by mistake. Every
frame below the ICRS also stores its epoch, so a later step can check that the position
and the Earth orientation it applies belong to the same moment.
Proper motion
Stars move across the sky. Barnard’s Star moves 10.4″ a year, so by 2026 it’s 107″ from
its Gaia DR3 position at J2016.0. CatalogStar::propagate moves a catalog entry from one
epoch to another using its proper motion, parallax and radial velocity. It models a
straight-line path through space, with the light-time and special-relativistic terms,
and its tests match ERFA’s eraPmsafe exactly.
Propagation happens before the chain, because ICRSPosition holds a direction and an
optional distance but no motion. Propagate the catalog entry to the date, then build the
ICRSPosition from the result’s ra and dec.
A star with a zero, negative or tiny parallax still propagates. Like eraPmsafe,
propagate raises such a parallax to a value that keeps the star’s implied speed well
below the speed of light.
Light deflection
The Sun’s gravity bends starlight, by about 1.75″ for a ray that grazes the solar limb and by about 4 milliarcseconds 90° away. Barnard’s Star is far from the Sun in April, so the shift is 3 mas. Very close to the Sun’s center, well inside the limb, the correction is tapered to zero so it doesn’t blow up.
aberration::apply_light_deflection exposes this step on its own. The chain applies it
inside Astrom::icrs_to_gcrs and Astrom::icrs_to_cirs.
Aberration
Light arrives from a slightly different direction when you’re moving across its path.
The Earth’s orbital speed of about 30 km/s shifts stars by up to about 20.5″. That’s
annual aberration, and the 11.5″ above is its value for this star on this date. The
crate computes the Earth’s barycentric velocity from the series in
aberration::compute_earth_state, which its tests check against ERFA’s eraEpv00, and
applies the full relativistic formula.
The Earth’s rotation also carries the telescope eastward, at up to 465 m/s on the
equator. That adds diurnal aberration of up to 0.32″. It depends on where you stand, so
only Astrom::for_site includes it. The geocentric conversions leave it out.
Precession and nutation
The GCRS to CIRS step rotates the axes to the Earth’s true pole of date, with the right ascension origin at the Celestial Intermediate Origin (CIO). It uses the IAU 2006/2000A precession-nutation matrix and the CIO locator s. How far it moves a star depends on where the star is: 45.6″ for Barnard’s Star in 2026. Precession, nutation and obliquity covers the models, and The CIO and the equinox explains why the CIRS measures right ascension from the CIO rather than the equinox.
When you pass Earth orientation data, Astrom::with_eop and Astrom::for_site add the
observed pole offsets dX and dY to the model pole. In the 2026 data those offsets are
below a milliarcsecond.
Earth rotation
The Earth rotation angle (ERA) is a linear function of UT1, the time scale that follows the Earth’s actual rotation. UT1 drifts away from UTC in ways nobody can predict, so the IERS measures UT1-UTC and publishes it. Earth orientation parameters covers where those values come from.
EarthRotation::new(&tt, &eop) computes the ERA once for an epoch. Its
cirs_to_hour_angle measures the hour angle from the site’s meridian, which is at ERA
plus the site’s east longitude. HourAnglePosition::to_topocentric then turns hour angle
and declination into azimuth, measured from north through east, and elevation.
HourAnglePosition has a few helpers for planning:
parallactic_angle()is the angle between the directions to the pole and to the zenith, at the star.is_circumpolar()andnever_rises()compare the declination with the site’s latitude.
Earth-fixed Cartesian frames
The TIRS and ITRS are the same rotation as Cartesian vectors. cirs.to_tirs(&eop) turns
the CIRS by the ERA. tirs.to_itrs(&eop) then applies polar motion, the drift of the
Earth’s crust relative to its rotation axis by a few tenths of an arcsecond. The polar
motion matrix uses the IERS 2003 model of the TIO locator s′. ITRSPosition converts to
and from WGS84 geodetic longitude, latitude and height with to_geodetic and
from_geodetic.
Refraction
The positions so far are where the star would be with no air. The atmosphere raises it,
by 14.7″ here at 68° elevation. with_refraction applies that. Atmospheric
refraction covers the models and the weather inputs they take.
Convert one position or a catalog
Every frame that needs only an epoch to reach the ICRS implements the CoordinateFrame
trait in celestial_coords::transforms:
pub trait CoordinateFrame: Sized {
fn to_icrs(&self, epoch: &TT) -> CoordResult<ICRSPosition>;
fn from_icrs(icrs: &ICRSPosition, epoch: &TT) -> CoordResult<Self>;
}
CIRSPosition::from_icrs(&star, &tt) is the shortest way from a catalog place to the
CIRS. Each call builds the Earth’s state and the precession-nutation matrix for the
epoch from scratch, though. For more than a few stars at one time, build an Astrom
once and reuse it. The constructors differ in what they include:
| Call | Light deflection and annual aberration | dX, dY | Diurnal aberration |
|---|---|---|---|
CIRSPosition::from_icrs(&star, &tt) | yes | no | no |
Astrom::new(&tt) | yes | no | no |
Astrom::with_eop(&tt, &eop) | yes | yes | no |
Astrom::for_site(&tt, &eop, &site) | yes | yes | yes |
EarthRotation does the same for the steps below the CIRS. CIRSPosition::to_hour_angle
and to_tirs build one per call. Build one yourself to reuse it across positions.
TIRSPosition, ITRSPosition, HourAnglePosition and TopocentricPosition don’t
implement CoordinateFrame, because they need Earth orientation data or a site as well
as an epoch.
Go back the other way
Every step has an inverse, so you can turn an encoder reading into a catalog place:
without_refraction, TopocentricPosition::to_hour_angle, HourAnglePosition::to_cirs,
Astrom::cirs_to_icrs and CoordinateFrame::to_icrs. Removing light deflection and
aberration has no closed form, so the inverses iterate a fixed number of times, as ERFA’s
eraAticq does. A round trip from ICRS to CIRS and back comes back within about
1e-13 rad.
Diurnal parallax
A star is far enough away that it looks the same from anywhere on Earth. The Moon isn’t:
from the surface you see it up to about a degree away from where it is in the geocentric
sky. TopocentricPosition corrects for this when it has a distance:
use celestial_coords::distance::Distance;
use celestial_coords::frames::topocentric::TopocentricPosition;
use celestial_core::angle::Angle;
use celestial_core::location::Location;
use celestial_time::scales::tt::TT;
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
// The Moon's geocentric place, turned to this site's horizon
let geocentric = TopocentricPosition::with_distance(
Angle::from_degrees(120.0),
Angle::from_degrees(30.0),
site,
TT::j2000(),
Distance::from_kilometers(384_400.0)?,
)?;
let seen = geocentric.with_diurnal_parallax()?;
println!("el {:.4}° -> {:.4}°", geocentric.elevation().degrees(), seen.elevation().degrees());
println!("az {:.4}° -> {:.4}°", geocentric.azimuth().degrees(), seen.azimuth().degrees());
println!("distance {:.0} km", seen.distance().map_or(0.0, |d| d.kilometers()));
println!("horizontal parallax {:.2}'", geocentric.horizontal_parallax()?.map_or(0.0, |p| p.arcminutes()));
// el 30.0000° -> 29.1701°
// az 120.0000° -> 119.9980°
// distance 381244 km
// horizontal parallax 57.04'
The site’s position comes from Location::to_geocentric_meters, so the correction uses
the WGS84 ellipsoid, as Observer locations describes.
without_diurnal_parallax goes the other way, and diurnal_parallax returns the change
in elevation. A position without a distance comes back unchanged, and the angle-returning
methods return None.
What the chain leaves out
- Annual parallax. The chain treats every
ICRSPositionas a direction from the barycenter and never moves it to the Earth’s position. A distance set on the position travels with it through the conversions, but it doesn’t change the direction. For Barnard’s Star that leaves out up to 0.55″. For stars with parallaxes of a few milliarcseconds or less, the omission is below most other errors. - Polar motion in hour angle and azimuth.
cirs_to_hour_angleuses UT1-UTC from the EOP record but not the polar motion x and y. Polar motion is applied only on the TIRS to ITRS step. The values are a few tenths of an arcsecond, and the hour angle, azimuth and elevation are off by up to that much. - Solar-system bodies. Light deflection treats the source as infinitely far away, and nothing in the chain corrects for light time. The Moon and planets need a geocentric position from an ephemeris, and the Moon needs the diurnal parallax correction above.
Edge cases
AstromandEarthRotationreject a position whose epoch differs from their own, instead of applying the Earth’s orientation from a different moment.GCRSPosition,CIRSPositionandEclipticPositionstore their epoch, and theirto_icrsuses it in place of theepochargument.cirs.to_tirsscales the vector by the distance in AU when the position has one. The way back,tirs.to_cirs, returns a direction without a distance.HourAnglePosition::newaccepts declinations past ±90° for German equatorial mounts after a pier flip, and folds them back over the pole, 12 hours of hour angle away.- The Earth rotation steps reject an EOP record more than one day from the epoch. See Earth orientation parameters.
Where next
- Find the altitude and azimuth of a star for the short recipe.
- Earth orientation parameters for UT1-UTC and polar motion data.
- Atmospheric refraction for the last step.
- Ecliptic and Galactic coordinates for the other frames that convert through the ICRS.
Find the altitude and azimuth of a star
Use this when you have a catalog entry, such as a Gaia or Hipparcos star, and need to know where it appears in your sky at a given moment. The example finds Barnard’s Star from Mauna Kea at 14:00 UTC on 2026 April 10, with refraction for the summit’s weather:
use celestial_coords::astrom::earth::EarthRotation;
use celestial_coords::astrom::Astrom;
use celestial_coords::eop::EopProvider;
use celestial_coords::frames::icrs::ICRSPosition;
use celestial_coords::frames::topocentric::refraction::weather::Weather;
use celestial_coords::frames::topocentric::refraction::Refraction;
use celestial_coords::proper_motion::CatalogStar;
use celestial_core::angle::Angle;
use celestial_core::constants::{J2000_JD, MJD_ZERO_POINT};
use celestial_core::location::Location;
use celestial_time::julian::JulianDate;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::tt::TT;
use celestial_time::scales::utc::UTC;
// 1. The time, as TT and as a UTC Modified Julian Date
let utc: UTC = "2026-04-10T14:00:00Z".parse()?;
let tt = utc.to_tai()?.to_tt()?;
let jd = utc.to_julian_date();
let mjd = (jd.jd1() - MJD_ZERO_POINT) + jd.jd2();
// 2. Earth orientation for that moment
let eop = EopProvider::bundled()?.get(mjd)?;
println!("{eop}");
// 3. The star's place on the date
let barnard = CatalogStar {
ra: Angle::from_degrees(269.44850252543),
dec: Angle::from_degrees(4.73942005111),
pm_ra_cos_dec_mas_per_year: -801.551,
pm_dec_mas_per_year: 10362.394,
parallax_mas: 546.976,
radial_velocity_km_per_s: -110.47,
};
let j2016 = TT::from_julian_date(JulianDate::new(J2000_JD, 5844.0));
let on_date = barnard.propagate(&j2016, &tt)?;
let star = ICRSPosition::new(on_date.ra, on_date.dec)?;
// 4. The apparent place, seen from the site
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let cirs = Astrom::for_site(&tt, &eop, &site)?.icrs_to_cirs(&star)?;
// 5. Turn it to the horizon
let horizon = EarthRotation::new(&tt, &eop)?
.cirs_to_hour_angle(&cirs, &site)?
.to_topocentric()?;
// 6. Add refraction
let weather = Weather::new(615.0, 2.0, 0.3, 0.55)?.with_location(&site)?;
let observed = horizon.with_refraction(&Refraction::from_weather(&weather)?);
println!("az {:.4}°, el {:.4}°", observed.azimuth().degrees(), observed.elevation().degrees());
// EOP(MJD=61140.6, xp=0.140612", yp=0.413757", UT1-UTC=0.0474262s)
// az 131.1203°, el 68.0376°
Azimuth runs from north through east, so 131° is southeast.
What each step needs
- The time. The coordinate models take Terrestrial Time (TT). The IERS tables are indexed by the UTC date, so you need the UTC Modified Julian Date as well. Converting from UTC goes through TAI, because TT is defined from TAI.
- Earth orientation.
EopProvider::bundled()reads the IERS tables built into the crate, so this works offline. Dates past the end of the table return an error. See Earth orientation parameters to load newer data. - The star’s place on the date. Skip
propagatefor a catalog that already gives positions at the date you want, or for a star whose proper motion you don’t care about. Gaia DR3 positions are at J2016.0, which is 5844 days after J2000.0. - The apparent place.
Astrom::for_siteapplies light deflection, annual and diurnal aberration, precession and nutation. - The horizon.
EarthRotationturns the Earth by the rotation angle for that UT1, andto_topocentricgives azimuth and elevation. - Refraction. Use the pressure and temperature at the telescope, not the sea-level values from a weather report. Atmospheric refraction explains the inputs.
A shorter version
If arcsecond-level accuracy is enough, the CoordinateFrame trait gets you there in
fewer lines:
use celestial_coords::eop::EopProvider;
use celestial_coords::frames::cirs::CIRSPosition;
use celestial_coords::frames::icrs::ICRSPosition;
use celestial_coords::transforms::CoordinateFrame;
use celestial_core::constants::MJD_ZERO_POINT;
use celestial_core::location::Location;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
let utc: UTC = "2026-04-10T14:00:00Z".parse()?;
let tt = utc.to_tai()?.to_tt()?;
let jd = utc.to_julian_date();
let eop = EopProvider::bundled()?.get((jd.jd1() - MJD_ZERO_POINT) + jd.jd2())?;
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let star = ICRSPosition::from_degrees(269.4485, 4.7394)?;
let horizon = CIRSPosition::from_icrs(&star, &tt)?
.to_hour_angle(&site, &eop)?
.to_topocentric()?;
println!("{horizon}");
// Topocentric(Az=131.17° SE, El=68.01°)
This version skips three things. It uses the J2016.0 catalog position, which is 107″ from where Barnard’s Star is in 2026. It leaves out diurnal aberration, 0.29″ here. And it has no refraction, which at this elevation is 15″.
Many stars at the same moment
Astrom and EarthRotation hold everything that depends on the time and the site. Build
them once and reuse them for every star:
use celestial_coords::astrom::earth::EarthRotation;
use celestial_coords::astrom::Astrom;
use celestial_coords::eop::EopProvider;
use celestial_coords::frames::icrs::ICRSPosition;
use celestial_coords::frames::topocentric::refraction::weather::Weather;
use celestial_coords::frames::topocentric::refraction::Refraction;
use celestial_core::constants::MJD_ZERO_POINT;
use celestial_core::location::Location;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
let utc: UTC = "2026-04-10T14:00:00Z".parse()?;
let tt = utc.to_tai()?.to_tt()?;
let jd = utc.to_julian_date();
let eop = EopProvider::bundled()?.get((jd.jd1() - MJD_ZERO_POINT) + jd.jd2())?;
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let weather = Weather::new(615.0, 2.0, 0.3, 0.55)?.with_location(&site)?;
let astrom = Astrom::for_site(&tt, &eop, &site)?;
let rotation = EarthRotation::new(&tt, &eop)?;
let air = Refraction::from_weather(&weather)?;
let stars = [
("Vega", 279.23473479, 38.78368896),
("Deneb", 310.35797975, 45.28033881),
("Regulus", 152.09296244, 11.96720878),
];
for (name, ra, dec) in stars {
let cirs = astrom.icrs_to_cirs(&ICRSPosition::from_degrees(ra, dec)?)?;
let horizon = rotation.cirs_to_hour_angle(&cirs, &site)?.to_topocentric()?;
if !horizon.is_above_horizon() {
println!("{name:8} below the horizon");
continue;
}
let observed = horizon.with_refraction(&air);
println!(
"{name:8} az {:8.4}° el {:7.4}°",
observed.azimuth().degrees(),
observed.elevation().degrees()
);
}
// Vega az 44.2397° el 60.5599°
// Deneb az 47.5402° el 36.8141°
// Regulus below the horizon
Refraction::from_weather runs a numerical ray trace, so build it once per change in the
weather, not once per star.
Edge cases
- The check for the horizon runs before refraction. A star a fraction of a degree below the true horizon can still be visible, because refraction near the horizon is about half a degree.
- Refraction on a
TopocentricPositionis held at its value for 2.9° elevation below that height. Don’t trust observed elevations under about 3°. - The result doesn’t include annual parallax or polar motion. For Barnard’s Star the first is up to 0.55″. What the chain leaves out has the details.
Where next
- From catalog to horizon explains each step.
- Earth orientation parameters covers the data behind step 2.
- Atmospheric refraction compares the refraction models.
Earth orientation parameters
The models for precession and nutation tell you where the Earth’s axis points. They can’t tell you how far the Earth has turned, or where the crust is relative to that axis. The Earth’s rotation speeds up and slows down with tides, winds and the motion of its core, and the crust wanders around the rotation axis. The International Earth Rotation and Reference Systems Service (IERS) measures both and publishes the results as Earth orientation parameters (EOP).
Leave them out and the sky turns to the wrong place. On 2026 April 10, UT1-UTC is 0.047 s, which moves the Earth rotation angle by 0.71″:
use celestial_coords::astrom::earth::EarthRotation;
use celestial_coords::eop::EopProvider;
use celestial_core::angle::Angle;
use celestial_core::constants::MJD_ZERO_POINT;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
let utc: UTC = "2026-04-10T14:00:00Z".parse()?;
let tt = utc.to_tai()?.to_tt()?;
let jd = utc.to_julian_date();
let mjd = (jd.jd1() - MJD_ZERO_POINT) + jd.jd2();
let eop = EopProvider::bundled()?.get(mjd)?;
println!("{eop}");
let mut no_eop = eop.clone();
no_eop.ut1_utc = 0.0;
let era = EarthRotation::new(&tt, &eop)?.era();
let era_without = EarthRotation::new(&tt, &no_eop)?.era();
println!("{:.3}\"", Angle::from_radians(era - era_without).arcseconds());
// EOP(MJD=61140.6, xp=0.140612", yp=0.413757", UT1-UTC=0.0474262s)
// 0.713"
UT1-UTC is kept within 0.9 s by leap seconds, so ignoring it can cost up to 13.5″ in hour angle.
What a record holds
EopProvider::get returns an EopParameters for a UTC Modified Julian Date. Its fields
are public:
| Field | Unit | Used by |
|---|---|---|
ut1_utc | seconds | The Earth rotation angle: hour angle, TIRS |
x_p, y_p | arcseconds | Polar motion: the TIRS to ITRS step |
dx, dy | milliarcseconds | Pole offsets in Astrom::with_eop and Astrom::for_site |
lod | seconds | Not used by the coordinate chain |
xrt, yrt | arcseconds per day | Not used by the coordinate chain |
mjd | days | The date the values apply to |
flags | The source and which optional columns are present |
lod, dx, dy, xrt and yrt are Options, because not every source has them. A
missing dX or dY counts as zero when Astrom adds them to the pole.
Where the data comes from
The celestial-eop-data crate builds two IERS series into your binary, so the default
provider needs no files and no network:
- IERS C04: the IERS reference series of daily observed values, starting in 1962.
- finals2000A: the IERS rapid series, which runs closer to the present than C04 and continues with predictions about a year ahead.
EopProvider::bundled() uses C04 where it has data and finals2000A values after C04 ends:
use celestial_coords::eop::bundled::bundled_timestamp;
use celestial_coords::eop::EopProvider;
let provider = EopProvider::bundled()?;
let (first, last) = provider.time_span();
println!("built {}: MJD {first} to {last}, {} records", bundled_timestamp(), provider.record_count());
for mjd in [51544.0, 61100.0, 61500.0] {
let p = provider.get(mjd)?;
println!("MJD {mjd}: {:?}, UT1-UTC {:+.7} s, dX {:?} mas", p.flags.source, p.ut1_utc, p.dx);
}
let err = provider.get(last + 10.0).unwrap_err();
println!("{err}");
// built 2026-11-29: MJD 37665 to 61547, 23883 records
// MJD 51544: IersC04, UT1-UTC +0.3554724 s, dX Some(-0.137) mas
// MJD 61100: IersC04, UT1-UTC +0.0672285 s, dX Some(0.403) mas
// MJD 61500: IersFinals, UT1-UTC +0.0324861 s, dX None mas
// Data not available: MJD 61557.0 is after last available record (MJD 61547.0)
Your dates and counts depend on the celestial-eop-data release in your Cargo.lock.
Newer releases carry newer data, and cargo update -p celestial-eop-data picks them up.
The predicted rows at the end of finals2000A have no dX and dY, so MJD 61500 shows
None.
The table is parsed once per process and shared, so calling bundled() again is cheap.
EopProvider::bundled_c04() gives C04 alone, without finals2000A or predictions.
Newer data from the IERS
Predictions drift from what the Earth does. A telescope that runs for months on one build
should load a fresh finals2000A file, which the IERS publishes at
https://datacenter.iers.org/data/9/finals2000A.all:
use celestial_coords::eop::EopProvider;
// The bundled tables, with every finals2000A row after the end of C04 replaced
let provider = EopProvider::bundled_with_update("finals2000A.all")?;
// The file alone
let provider = EopProvider::from_finals_file("finals2000A.all")?;
// finals2000A text you already have in memory
let provider = EopProvider::from_finals_str(&text)?;
bundled_with_update keeps C04 as the reference where it exists and takes only the
file’s rows after C04 ends. The crate doesn’t download anything itself. The
eop_update example in celestial-coords/examples shows one way to fetch and cache the
file.
Your own values
Build records by hand for testing, or when your EOP come from somewhere else:
use celestial_coords::eop::interpolate::InterpolationMethod;
use celestial_coords::eop::record::EopRecord;
use celestial_coords::eop::EopProvider;
// IERS C04 values: MJD, x_p (arcsec), y_p (arcsec), UT1-UTC (s)
let records = vec![
EopRecord::new(61138.0, 0.136880, 0.413544, 0.0477627)?,
EopRecord::new(61139.0, 0.138546, 0.413709, 0.0477158)?,
EopRecord::new(61140.0, 0.139773, 0.413664, 0.0475928)?,
EopRecord::new(61141.0, 0.141211, 0.413823, 0.0473072)?,
EopRecord::new(61142.0, 0.142395, 0.414232, 0.0468578)?.with_cip_offsets(0.373, -0.130)?,
];
let linear = EopProvider::from_records(records.clone())?;
let lagrange = EopProvider::from_records(records)?.with_interpolation(InterpolationMethod::Lagrange5);
let a = linear.get(61140.5)?;
let b = lagrange.get(61140.5)?;
println!("linear UT1-UTC {:.7} s, dX {:?}", a.ut1_utc, a.dx);
println!("Lagrange UT1-UTC {:.7} s, dX {:?}", b.ut1_utc, b.dx);
// linear UT1-UTC 0.0474500 s, dX None
// Lagrange UT1-UTC 0.0474724 s, dX None
with_lod, with_cip_offsets and with_pole_rates add the optional columns.
EopRecord::new rejects polar motion beyond 6″ and UT1-UTC beyond 1 s, which catches
values entered in the wrong unit. Records store each value rounded to 1e-7 arcsec,
1e-7 s or 1e-4 mas.
Between table rows
The tables have one row a day, and get interpolates between them. A date that matches a
row exactly returns that row.
- Linear interpolation is the default. It uses the two rows around the date.
- Lagrange5 fits a polynomial through the five nearest rows, so it follows the curvature of the series between rows. In the example above the two methods differ by 22 µs in UT1-UTC, which is 0.34 mas of Earth rotation.
UT1-UTC jumps by a whole second at each leap second. The interpolation runs on UT1-TAI, which has no jumps, and converts back with the TAI-UTC in force on the requested date. That keeps a leap second between two rows from leaking into the result.
An optional column comes back as Some only when every row the interpolation used has
it. In the example, only one row has dX, so the interpolated dX is None.
Rows more than 5 days apart are treated as a gap, and a date inside one returns an error.
How fresh the record must be
EarthRotation and the methods built on it, such as CIRSPosition::to_hour_angle, check
the record’s mjd against the position’s epoch. A record more than one day away is
refused:
use celestial_coords::eop::EopProvider;
use celestial_coords::frames::cirs::CIRSPosition;
use celestial_core::location::Location;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
let tt = "2026-04-10T14:00:00Z".parse::<UTC>()?.to_tai()?.to_tt()?;
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let last_week = EopProvider::bundled()?.get(61133.0)?;
let cirs = CIRSPosition::from_degrees(269.4, 4.76, tt)?;
let err = cirs.to_hour_angle(&site, &last_week).unwrap_err();
println!("{err}");
// Data not available: EOP record at MJD 61133 is more than 1 day from the epoch
UT1-UTC changes by up to a few milliseconds a day, so a stale record would put the Earth rotation angle tens of milliarcseconds off without any sign that something was wrong. Look up the record for each observation time, or at least once a day.
Edge cases
- Pass the UTC MJD to
get. The tables are indexed by UTC date. Passing the TT MJD shifts the lookup by about 69 seconds, which changes the interpolated values very little, but the freshness check compares against TT. - In the bundled tables, a value of exactly zero in the LOD, dX or dY column reads as absent, because the packed data stores blank columns as zero.
getreturnsCoordError::DataUnavailablefor dates outside the table. Handle it if your program runs past the end of the bundled predictions.- With
InterpolationMethod::Lagrange5,getneeds at least five records and returns an error with fewer.
Where next
- From catalog to horizon shows where each parameter enters the chain.
- The CIO and the equinox explains the pole offsets dX and dY.
- Time Scales and UTC and Leap Seconds cover UTC, UT1 and leap seconds.
Atmospheric refraction
Light bends as it enters the atmosphere, so every star appears higher than it is. At the zenith the effect is zero. At 45° it’s about a minute of arc at sea level, and near the horizon it grows fast. Thinner air bends light less, so a mountain site sees less of it:
use celestial_coords::frames::topocentric::refraction::Refraction;
use celestial_coords::frames::topocentric::TopocentricPosition;
use celestial_core::location::Location;
use celestial_time::scales::tt::TT;
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
// Pressure (hPa), temperature (°C), relative humidity (0-1), wavelength (µm)
let sea_level = Refraction::new(1013.25, 10.0, 0.5, 0.55)?;
let summit = Refraction::new(615.0, 2.0, 0.3, 0.55)?;
for elevation in [90.0, 60.0, 30.0, 10.0, 5.0, 2.0] {
let observed = TopocentricPosition::from_degrees(180.0, elevation, site, TT::j2000())?;
println!(
"el {elevation:4.0}° sea level {:7.1}\" summit {:7.1}\"",
observed.atmospheric_refraction(&sea_level).arcseconds(),
observed.atmospheric_refraction(&summit).arcseconds(),
);
}
// el 90° sea level 0.0" summit 0.0"
// el 60° sea level 33.6" summit 21.0"
// el 30° sea level 100.5" summit 62.8"
// el 10° sea level 318.2" summit 198.7"
// el 5° sea level 568.0" summit 354.0"
// el 2° sea level 643.1" summit 396.8"
The value at 2° is too small. Refraction on a TopocentricPosition is held at its value
for about 2.9° elevation below that height, as ERFA’s refraction is, because the
two-constant formula below stops working near the horizon. Refraction there also depends
on the air along the line of sight more than on any model.
Two constants
Away from the horizon, refraction follows a two-term formula in the observed zenith distance z:
refraction = A tan z + B tan³ z
Refraction holds A and B, in radians. You get them from the weather, through a
refraction model:
Refraction::new(pressure_hpa, temperature_c, relative_humidity, wavelength_um)uses the closed-form model.Refraction::from_weather(&weather)runs a numerical ray trace through a model atmosphere.Refraction::from_model(&model, &weather)takes anyRefractionModel.
Once you have a Refraction, applying it costs a few multiplications, so compute it
once per change in the weather.
Choose a model
use celestial_coords::frames::topocentric::refraction::closed_form::ClosedForm;
use celestial_coords::frames::topocentric::refraction::ray_trace::{RayTrace, Refractivity};
use celestial_coords::frames::topocentric::refraction::weather::Weather;
use celestial_coords::frames::topocentric::refraction::Refraction;
use celestial_core::constants::ARCSEC_PER_RAD;
use celestial_core::location::Location;
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let weather = Weather::new(615.0, 2.0, 0.3, 0.55)?.with_location(&site)?;
let models: [(&str, Refraction); 3] = [
("closed form", Refraction::from_model(&ClosedForm, &weather)?),
("ray trace, Ciddor", Refraction::from_weather(&weather)?),
(
"ray trace, H&S",
Refraction::from_model(&RayTrace::new(Refractivity::HohenkerkSinclair), &weather)?,
),
];
for (name, r) in models {
println!(
"{name:18} A = {:.4}\" B = {:.6}\"",
r.a() * ARCSEC_PER_RAD,
r.b() * ARCSEC_PER_RAD
);
}
// closed form A = 36.3711" B = -0.041347"
// ray trace, Ciddor A = 36.3588" B = -0.040597"
// ray trace, H&S A = 36.3668" B = -0.040607"
The three agree to about 0.01″ in A. They differ in cost and in what they take into account.
ClosedForm computes A and B from formulas, with no integration. It uses the formulas
ERFA’s eraRefco uses, and it’s the model behind Refraction::new. It reads pressure,
temperature, humidity and wavelength, and ignores the site’s height, latitude and lapse
rate. Each input is clamped to the range the formulas hold over.
RayTrace integrates the bending along a ray through the two-layer atmosphere of
Hohenkerk and Sinclair (NAO Technical Note 63). Temperature falls at a constant lapse
rate up to the tropopause at 11 km and stays constant above it, and the stratosphere is
dry. The integral runs to 80 km and stops when successive estimates agree to 1e-8 rad.
The ray trace then fits A and B so they’re exact at tan z = 1 and tan z = 4, which is
z = 45° and z = 76°. It takes longer than the closed form, but it uses the site’s height
and latitude.
The ray trace takes one of two formulas for the refractive index of air at optical wavelengths:
Refractivity::Ciddor, the default, uses Ciddor (1996) as given in the NIST Engineering Metrology Toolbox, with 450 µmol/mol of carbon dioxide. It needs a wavelength of at least 0.3 µm.Refractivity::HohenkerkSinclairuses the refractivity of NAO Technical Note 63. Its tests agree with a SLALIB-compatiblesla_REFCOto within 2e-9 rad in A, so use it when you need to match older SLALIB-based software.
Above 100 µm both refractivities give way to the radio formula of Rueger (2002), and the closed form switches to its radio formulas at the same wavelength.
Weather and site
Weather::new(pressure_hpa, temperature_c, relative_humidity, wavelength_um) holds the
conditions at the telescope. Relative humidity runs from 0 to 1. Use the station pressure
at the telescope, not the sea-level pressure a weather service reports. The two differ by
about 40% on Mauna Kea.
The ray trace also reads three properties of the site, with defaults for a sea-level site at the equator:
with_location(&site)sets the height and latitude from aLocation.with_site(height_m, latitude)sets them directly.with_lapse_rate(kelvin_per_metre)sets the temperature gradient. The default is 0.0065 K/m, the standard tropospheric value. The sign is ignored.
Apply it
with_refraction takes the place you’d see with no atmosphere, which is what the
coordinate chain gives you, and returns where you see the star.
without_refraction goes back:
use celestial_coords::frames::topocentric::refraction::Refraction;
use celestial_coords::frames::topocentric::TopocentricPosition;
use celestial_core::location::Location;
use celestial_time::scales::tt::TT;
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let air = Refraction::new(615.0, 2.0, 0.3, 0.55)?;
// The place with no atmosphere, from the coordinate chain
let true_place = TopocentricPosition::from_degrees(250.0, 20.0, site, TT::j2000())?;
let observed = true_place.with_refraction(&air);
let back = observed.without_refraction(&air);
println!("true {:.6}°", true_place.elevation().degrees());
println!("observed {:.6}°", observed.elevation().degrees());
println!("back {:.6}°", back.elevation().degrees());
// true 20.000000°
// observed 20.027479°
// back 20.000000°
Only the elevation changes. atmospheric_refraction returns the amount itself, and
expects the observed place, as the first example on this page does.
Refraction at one zenith distance
On this site, A and B stay within 0.3″ of the full ray trace out to a zenith distance of
80°. Past that, use the RefractionModel trait’s refraction_at, which gives the
model’s own value at one zenith distance. For RayTrace that’s a full ray trace, which stays accurate where the
two-term formula doesn’t:
use celestial_coords::frames::topocentric::refraction::ray_trace::RayTrace;
use celestial_coords::frames::topocentric::refraction::weather::Weather;
use celestial_coords::frames::topocentric::refraction::RefractionModel;
use celestial_core::angle::Angle;
use celestial_core::constants::ARCSEC_PER_RAD;
use celestial_core::location::Location;
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
let weather = Weather::new(615.0, 2.0, 0.3, 0.55)?.with_location(&site)?;
let trace = RayTrace::default();
let (a, b) = trace.constants(&weather)?;
for zd in [45.0, 75.0, 85.0, 89.0] {
let z = Angle::from_degrees(zd);
let t = z.tan();
println!(
"z {zd:2.0}° ray trace {:8.2}\" A tan z + B tan³ z {:8.2}\"",
trace.refraction_at(&weather, z.radians())? * ARCSEC_PER_RAD,
(a * t + b * t * t * t) * ARCSEC_PER_RAD,
);
}
// z 45° ray trace 36.32" A tan z + B tan³ z 36.32"
// z 75° ray trace 133.57" A tan z + B tan³ z 133.58"
// z 85° ray trace 368.66" A tan z + B tan³ z 354.96"
// z 89° ray trace 896.99" A tan z + B tan³ z -5550.68"
Both angles are radians. refraction_at takes the observed zenith distance, and
observed_zenith_distance solves the other way, from the zenith distance with no
atmosphere to the observed one. For ClosedForm, refraction_at is the two-term
formula itself, so it has the same problem near the horizon.
Airmass
Airmass is how much atmosphere you look through, relative to looking straight up. It
sets how much extinction dims a star. TopocentricPosition has three empirical
formulas:
use celestial_coords::frames::topocentric::TopocentricPosition;
use celestial_core::location::Location;
use celestial_time::scales::tt::TT;
let site = Location::from_degrees(19.8207, -155.4681, 4205.0)?;
for elevation in [90.0, 30.0, 10.0, 3.0, 0.0] {
let p = TopocentricPosition::from_degrees(180.0, elevation, site, TT::j2000())?;
println!(
"el {elevation:2.0}° Rozenberg {:6.3} Kasten-Young {:6.3} Pickering {:6.3}",
p.air_mass(),
p.air_mass_kasten_young(),
p.air_mass_pickering()
);
}
// el 90° Rozenberg 1.000 Kasten-Young 1.000 Pickering 1.000
// el 30° Rozenberg 2.000 Kasten-Young 1.994 Pickering 1.993
// el 10° Rozenberg 5.639 Kasten-Young 5.586 Pickering 5.581
// el 3° Rozenberg 15.062 Kasten-Young 15.148 Pickering 15.262
// el 0° Rozenberg 40.000 Kasten-Young 38.000 Pickering 38.749
air_mass is the Rozenberg formula. They agree to about 1% above 10° elevation. At and
below the horizon, Rozenberg returns 40 and Kasten-Young returns 38. Pickering’s
formula stays finite down to about -1.1° and returns infinity below that.
Edge cases
Weather::newand its builders reject NaN and infinite values. The ray trace also rejects a negative pressure, humidity outside 0 to 1, a temperature at or below absolute zero, a zero lapse rate, a site at or above the 11 km tropopause, and conditions that would cool the tropopause below absolute zero.- A pressure of zero gives no refraction from the ray trace.
Refractivity::Ciddorrejects wavelengths below 0.3 µm, where its dispersion formula has poles nearby. UseRefractivity::HohenkerkSinclairorClosedFormthere.refraction_atandobserved_zenith_distancetake zenith distances from 0 to 90° only.observed_zenith_distancereturns an error if it hasn’t converged after 50 iterations.
Where next
- From catalog to horizon for the steps that come before refraction.
- Find the altitude and azimuth of a star for refraction in a complete example.
Ecliptic and Galactic coordinates
Equatorial coordinates suit a telescope, because they follow the Earth’s axis. Other
questions read better in other frames. Is this comet near the plane of the planets? Is
this nebula in the Milky Way’s disk? celestial-coords has two frames for those:
EclipticPosition, on the ecliptic and equinox of date, and GalacticPosition, on the
plane of the Galaxy. Both convert through the ICRS with the CoordinateFrame trait.
use celestial_coords::frames::galactic::GalacticPosition;
use celestial_coords::frames::icrs::ICRSPosition;
use celestial_coords::transforms::CoordinateFrame;
use celestial_time::scales::tt::TT;
let epoch = TT::j2000(); // the Galactic frame ignores it
let center = GalacticPosition::galactic_center().to_icrs(&epoch)?;
println!("l = 0, b = 0 RA {:.6}°, Dec {:.6}°", center.ra().degrees(), center.dec().degrees());
let pole = GalacticPosition::north_galactic_pole().to_icrs(&epoch)?;
println!("b = 90° RA {:.6}°, Dec {:.6}°", pole.ra().degrees(), pole.dec().degrees());
let deneb = ICRSPosition::from_degrees(310.35797975, 45.28033881)?;
let g = deneb.to_galactic(&epoch)?;
println!("Deneb l {:.4}°, b {:.4}°", g.longitude().degrees(), g.latitude().degrees());
println!("near the plane: {}", g.is_near_galactic_plane());
// l = 0, b = 0 RA 266.404995°, Dec -28.936174°
// b = 90° RA 192.859480°, Dec 27.128250°
// Deneb l 84.2847°, b 1.9975°
// near the plane: true
Galactic coordinates
Galactic longitude l runs along the plane of the Milky Way from the direction of the
Galactic center, and latitude b runs from that plane. The frame is fixed, so the epoch
argument to to_icrs and from_icrs doesn’t change the result.
The rotation is the one the Hipparcos Catalogue (ESA 1997, vol. 1 §1.5.3) ties to the
ICRS, with the north Galactic pole at RA 192.85948°, Dec 27.12825°, as the example shows.
The tests match ERFA’s eraIcrs2g and eraG2icrs exactly.
GalacticPosition has constructors for the center, the anticenter and both poles, and
a few rough classifiers for survey work:
is_near_galactic_plane()is true for |b| < 10°.is_in_galactic_bulge()is true for |b| < 10° and l within 30° of the center.is_near_galactic_pole()is true for |b| > 80°.
Ecliptic coordinates of date
Ecliptic longitude λ runs along the plane of the Earth’s orbit from the equinox, and latitude β runs from that plane. The equinox moves with precession, so ecliptic longitudes of date grow by about 50″ a year:
use celestial_coords::frames::icrs::ICRSPosition;
use celestial_core::constants::{J2000_JD, MJD_ZERO_POINT};
use celestial_time::julian::JulianDate;
use celestial_time::scales::tt::TT;
let regulus = ICRSPosition::from_degrees(152.09296244, 11.96720878)?;
for (label, epoch) in [
("J2000.0 ", TT::j2000()),
("2026-01-01", TT::from_julian_date(JulianDate::new(MJD_ZERO_POINT, 61041.0))),
("J2100.0 ", TT::from_julian_date(JulianDate::new(J2000_JD, 36525.0))),
] {
let e = regulus.to_ecliptic(&epoch)?;
println!("{label} λ {:.4}°, β {:+.4}°", e.lambda().degrees(), e.beta().degrees());
}
// J2000.0 λ 149.8291°, β +0.4648°
// 2026-01-01 λ 150.1924°, β +0.4663°
// J2100.0 λ 151.2264°, β +0.4703°
Regulus is 0.46° from the ecliptic, close enough that the Moon passes in front of it. Over a century its latitude changes by 0.005° and its longitude by 1.4°. The latitude moves because the ecliptic plane itself tilts slowly.
EclipticPosition uses the mean ecliptic and equinox of date: IAU 2006 precession and
the IAU 2006 mean obliquity, with no nutation. That’s the frame ERFA’s eraEqec06 and
eraEceq06 use, and the tests match them. The position carries its epoch, and its
to_icrs uses that epoch.
Obliquity and fixed points
An EclipticPosition can report the obliquity for its epoch:
use celestial_coords::frames::ecliptic::EclipticPosition;
use celestial_coords::transforms::CoordinateFrame;
use celestial_core::angle::DmsFmt;
use celestial_core::constants::MJD_ZERO_POINT;
use celestial_time::julian::JulianDate;
use celestial_time::scales::tt::TT;
let epoch = TT::from_julian_date(JulianDate::new(MJD_ZERO_POINT, 61041.0));
let fmt = DmsFmt { frac_digits: 3 };
let solstice = EclipticPosition::summer_solstice(epoch);
println!("mean obliquity {}", fmt.fmt(solstice.mean_obliquity()?));
println!("true obliquity {}", fmt.fmt(solstice.true_obliquity()?));
let icrs = solstice.to_icrs(&epoch)?;
println!("RA {:.4}°, Dec {:.4}°", icrs.ra().degrees(), icrs.dec().degrees());
// mean obliquity +23° 26' 9.228"
// true obliquity +23° 26' 17.294"
// RA 89.6041°, Dec 23.4354°
true_obliquity adds the IAU 2006/2000A nutation in obliquity. The frame itself stays on
the mean ecliptic. The June solstice point of 2026 is at RA 89.6° on ICRS axes, not 90°,
because the equinox has precessed since J2000.0.
Precession, nutation and obliquity covers
the obliquity models.
The other fixed points are vernal_equinox, autumnal_equinox, winter_solstice,
north_ecliptic_pole and south_ecliptic_pole, all for a given epoch.
The fixed J2000.0 ecliptic
The planetary theories work on a different ecliptic: the fixed VSOP2013 frame of
J2000.0. For heliocentric vectors in that frame, use
frames::ecliptic_cartesian::EclipticCartesian with the CartesianFrame trait from
transforms::cartesian. It calls the rotation that
Ecliptic coordinates describes.
Distances
ICRSPosition, GalacticPosition and EclipticPosition can each hold a Distance, and
the conversions copy it across unchanged. distance::Distance converts between parsecs,
light years, AU, kilometers, parallax and distance modulus. Constructors reject zero,
negative and non-finite values.
Edge cases
- Longitudes come back in [0°, 360°). Latitudes outside ±90° are rejected.
- At a pole, longitude has no meaning. The conversions return whatever longitude the rounding produces, and two poles with different longitudes can show a separation of about 1e-16 rad.
EclipticPosition::to_icrsignores itsepochargument and uses the position’s own epoch.
Where next
- From catalog to horizon for the equatorial frames.
- Ecliptic coordinates for the fixed VSOP2013 frame.
- Solar and lunar orientation for coordinates on the Sun and Moon.
Solar and lunar orientation
Point a telescope at the Sun and you see a disk with no grid on it. To say where a sunspot is, or to come back to the same active region tomorrow, you need to know how the Sun’s rotation axis is tilted toward you and which solar meridian faces the Earth. The Moon has the same problem with a twist: its tilt and libration let you see a little around its edges, and the features near the limb come and go over the month.
The solar and lunar modules compute those orientation angles. The heliographic and
selenographic frames use them to put coordinates on the surfaces.
The Sun
use celestial_coords::frames::heliographic::{HeliographicCarrington, HeliographicStonyhurst};
use celestial_coords::solar::{carrington_rotation_number, compute_solar_orientation, sun_earth_distance};
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
let tt = "2026-04-10T20:00:00Z".parse::<UTC>()?.to_tai()?.to_tt()?;
let sun = compute_solar_orientation(&tt)?;
println!("P {:+.2}°", sun.p.degrees());
println!("B0 {:+.2}°", sun.b0.degrees());
println!("L0 {:.2}°", sun.l0.degrees());
println!("rotation {:.4}", carrington_rotation_number(&tt)?);
println!("distance {:.6} au", sun_earth_distance(&tt)?);
// P -26.20°
// B0 -5.95°
// L0 63.85°
// rotation 2309.8226
// distance 1.001936 au
The three angles describe the disk you see:
- P is the position angle of the Sun’s rotation axis, measured from the north point of the disk toward the east. In April it’s -26°, so the solar north pole is tipped 26° to the west of celestial north.
- B0 is the heliographic latitude of the disk center. At -6° you see a little more of the southern hemisphere.
- L0 is the Carrington longitude of the disk center. It falls by about 13.2° a day as the Sun turns.
carrington_rotation_number counts solar rotations since Carrington’s first one in 1853.
The integer part is the rotation, and the fraction is how far into it the Sun has turned.
sun_earth_distance is the length of the Earth’s heliocentric position vector, in AU.
The angles follow Meeus, Astronomical Algorithms (2nd ed., ch. 29), with Carrington’s elements for the solar equator. The Earth’s position comes from the same series the aberration step uses. The tests reproduce Meeus’ worked example 29.a to the two decimal places he prints.
Coordinates on the Sun
Two frames put a grid on the solar surface:
HeliographicStonyhursthas longitude zero at the central meridian, the line through the disk center as seen from the Earth. A feature’s Stonyhurst longitude grows as the Sun carries it west across the disk.HeliographicCarringtonrotates with the Sun. A long-lived feature keeps roughly the same Carrington longitude from day to day.
The two differ by L0, so converting between them takes the epoch. Continuing the example above:
// A sunspot 20° west of the central meridian, 15° north
let spot = HeliographicStonyhurst::from_degrees(15.0, 20.0)?;
let fixed = spot.to_carrington(&tt)?;
println!("Carrington lon {:.2}°, lat {:.2}°", fixed.longitude().degrees(), fixed.latitude().degrees());
// Two days later, the same Carrington longitude has turned with the Sun
let later = "2026-04-12T20:00:00Z".parse::<UTC>()?.to_tai()?.to_tt()?;
let moved = HeliographicCarrington::from_degrees(15.0, fixed.longitude().degrees())?.to_stonyhurst(&later)?;
println!("Stonyhurst lon {:.2}° two days later", moved.longitude().degrees());
// Carrington lon 83.85°, lat 15.00°
// Stonyhurst lon 46.40° two days later
Both constructors take latitude first, then longitude. HeliographicStonyhurst::disk_center(&tt)
returns the point at B0 on the central meridian.
The Moon
use celestial_coords::frames::selenographic::SelenographicPosition;
use celestial_coords::lunar::compute_lunar_orientation;
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
let tt = "2026-04-10T20:00:00Z".parse::<UTC>()?.to_tai()?.to_tt()?;
let moon = compute_lunar_orientation(&tt)?;
let (optical, total) = (&moon.optical_libration, &moon.sub_earth_point);
println!("optical libration l {:+.3}°, b {:+.3}°", optical.longitude.degrees(), optical.latitude.degrees());
println!("sub-Earth point l {:+.3}°, b {:+.3}°", total.longitude.degrees(), total.latitude.degrees());
println!("position angle {:.2}°", moon.position_angle.degrees());
// Mare Crisium, near the eastern limb
let crisium = SelenographicPosition::from_degrees(17.0, 59.1)?;
println!("Mare Crisium visible: {}", crisium.is_visible_from_earth(&tt)?);
let far = SelenographicPosition::farside_center();
println!("far side center visible: {}", far.is_visible_from_earth(&tt)?);
// optical libration l -5.342°, b +4.299°
// sub-Earth point l -5.374°, b +4.356°
// position angle 349.42°
// Mare Crisium visible: true
// far side center visible: false
The Moon keeps one face toward the Earth, but not exactly. Its orbit is elliptical and tilted against its equator, so over a month the Earth sees it from up to several degrees east, west, north and south of the mean face. That’s libration.
- Optical libration is the part that comes from the geometry of the orbit.
- The sub-Earth point adds the physical libration, the small real wobble of the Moon about its axis. It’s the selenographic longitude and latitude of the point that faces the Earth’s center.
- The position angle is the angle of the Moon’s rotation axis, from the north point of the disk toward the east.
compute_optical_libration and compute_sub_earth_point return the two libration pairs
on their own, for when you don’t need the position angle.
The libration and position angle follow Meeus ch. 53. The Moon’s position comes from
Meeus ch. 47, arranged to match ERFA’s eraMoon98. The tests reproduce Meeus’ worked
example 53.a to the precision he prints.
Coordinates on the Moon
SelenographicPosition holds a latitude and longitude on the Moon, latitude first.
Longitude is zero at the mean center of the near side and grows toward Mare Crisium.
sub_earth_point(&tt)returns the point facing the Earth.is_visible_from_earth(&tt)is true within 90° of that point.nearside_center,farside_center,north_poleandsouth_poleare fixed points.
Edge cases
- The
CoordinateFrameconversions for these frames rotate a direction. They don’t move its origin from the Earth to the Sun or Moon. Use them to turn a direction in ICRS axes into the body’s axes, not to find which point on the surface you’re looking at. to_stonyhurstreturns longitudes in [0°, 360°), so a feature 10° east of the central meridian comes back as 350°, not -10°.is_visible_from_earthuses the Earth’s center. From the surface you can see up to about a degree further around the limb.
Where next
- Ecliptic and Galactic coordinates for the mean ecliptic of date that these orientations start from.
- Planets, Sun and Moon for positions of the Sun and Moon.
Planets, Sun and Moon
You want to know where Mars or the Moon is at a given time, and you’d rather
not download and ship a JPL kernel to find out. celestial-ephemeris builds
two published theories into the crate as truncated series. VSOP2013 (Simon et
al. 2013) covers the planets, and ELP/MPP02 (Chapront & Francou 2003) covers
the Moon. They need no data files at run time.
Here are Mars and Jupiter as seen from the Earth’s center:
use celestial_ephemeris::earth::Vsop2013Earth;
use celestial_ephemeris::planets::{Vsop2013Jupiter, Vsop2013Mars};
use celestial_time::scales::tdb::tdb_from_calendar;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let tdb = tdb_from_calendar(2026, 10, 5, 0, 0, 0.0)?;
let earth = Vsop2013Earth::new().heliocentric_state(&tdb)?;
let (mars, mars_velocity) = Vsop2013Mars.geocentric_state(&tdb, &earth)?;
let jupiter = Vsop2013Jupiter.geocentric_position(&tdb, &earth.0)?;
println!("Mars: {:.6} AU, {:.6} AU/day", mars.magnitude(), mars_velocity.magnitude());
println!("Jupiter: {:.6} AU", jupiter.magnitude());
Ok(())
}
The geocentric methods take the Earth’s heliocentric position or state as an argument instead of computing it, so one Earth evaluation per epoch serves every planet.
The truncated series are good to about 30 mas for Mercury through Saturn between 1950 and 2050. Accuracy has the per-body numbers. For anything tighter, or for barycentric positions, use a JPL SPK kernel.
Conventions
Every body on this page uses the same conventions:
- Input: a
&TDBepoch. - Output: ICRS axes, positions in AU and velocities in AU/day.
- Errors: every method returns
AstroResult.
The series measure time as (jd1 − 2451545.0) + jd2 days from J2000. The two
parts of the Julian date are never added first, so a time of day held in
jd2 keeps its precision. tdb_from_calendar already splits the date this
way, with midnight in jd1 and the time of day in jd2.
Positions are geometric: where the body is at that instant. They include no light time, aberration or light deflection. Light time shows how to add the first of these.
“Heliocentric” means relative to the Sun’s center, which differs from the solar system barycenter. Between 1950 and 2050 the Sun moves about the barycenter at 8.5 to 16.1 m/s. Aberration computed from heliocentric velocities is therefore off by up to 11 mas. When that matters, take the Earth’s barycentric velocity from a JPL kernel.
Planets
Each planet is a unit struct in celestial_ephemeris::planets:
| Type | Body |
|---|---|
Vsop2013Mercury | Mercury |
Vsop2013Venus | Venus |
Vsop2013Emb | Earth-Moon barycenter |
Vsop2013Mars | Mars |
Vsop2013Jupiter | Jupiter |
Vsop2013Saturn | Saturn |
Vsop2013Uranus | Uranus |
Vsop2013Neptune | Neptune |
Vsop2013Pluto | Pluto |
All of them have the same four methods:
| Method | Returns |
|---|---|
heliocentric_position(&tdb) | Vector3 position |
heliocentric_state(&tdb) | (Vector3, Vector3) position, velocity |
geocentric_position(&tdb, &earth) | heliocentric position minus earth |
geocentric_state(&tdb, &earth_state) | heliocentric state minus earth_state |
Vector3 is celestial_core::matrix::Vector3.
Earth and Sun
VSOP2013 has no series for the Earth itself. Vsop2013Earth computes it from
the Earth-Moon barycenter by removing the Moon’s share:
earth = emb − moon × MOON_EMB_MASS_RATIO
Here moon comes from ElpMpp02Moon::new(). The ratio is the Moon’s fraction
of the Earth-Moon mass, from celestial_core::constants. Since the Earth
depends on the Moon, Vsop2013Earth accepts only dates in the Moon’s range
(see Date ranges).
Vsop2013Earth has only heliocentric_position and heliocentric_state.
Vsop2013Sun has all four planet methods, so code that loops over bodies can
treat the Sun like any other. Its heliocentric position and velocity are zero,
and its geocentric values are the negated Earth.
Moon
ElpMpp02Moon returns the geocentric Moon directly, with no Earth argument:
use celestial_ephemeris::moon::ElpMpp02Moon;
use celestial_time::scales::tdb::tdb_from_calendar;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let tdb = tdb_from_calendar(2026, 10, 5, 0, 0, 0.0)?;
let moon = ElpMpp02Moon::new();
let position = moon.geocentric_position(&tdb)?;
let (_, velocity) = moon.geocentric_state(&tdb)?;
println!("Moon: {:.8} AU, {:.8} AU/day", position.magnitude(), velocity.magnitude());
Ok(())
}
The theory’s authors fitted its constants two ways. Each fit has its own constructor:
| Constructor | Constants fitted to | Rotation to ICRS |
|---|---|---|
new() | lunar laser ranging | ε = 84381.406″ (IAU 2006 obliquity) |
with_de405_fit() | JPL’s DE405 | ε = 84381.4096″, φ = −0.05028″ (fitted with DE405) |
ElpMpp02Moon::default() is the same as new(), and Vsop2013Earth uses
new() too. Against DE432s over 1950 to 2050, the shipped series misses by up
to 67 m with new() and 36 m with with_de405_fit().
Accuracy breaks these numbers down.
Given the same truncated series, the crate reproduces the authors’ Fortran bit for bit, when that Fortran is compiled without FMA.
Date ranges
Each theory rejects epochs outside its published range:
| Theory | Bodies | Years | TDB Julian dates |
|---|---|---|---|
| VSOP2013 | Mercury to Neptune, Earth-Moon barycenter, Sun | −4000 to +8000 | 260045.0 to 4643045.0 |
| VSOP2013 | Pluto | 0 to +4000 | 1721045.0 to 3182045.0 |
| ELP/MPP02 | Moon, Earth | −3000 to +3000 | 625295.0 to 2816795.0 |
Both ends are included. An epoch outside the range returns
AstroError::MathError with kind OutOfRange, and the message names the
theory and its years. A NaN or infinite epoch returns kind NotFinite:
use celestial_core::errors::{AstroError, MathErrorKind};
use celestial_ephemeris::planets::Vsop2013Pluto;
use celestial_time::julian::JulianDate;
use celestial_time::scales::tdb::TDB;
fn main() {
let year_5000 = TDB::from_julian_date(JulianDate::new(3547295.0, 0.0));
match Vsop2013Pluto.heliocentric_position(&year_5000) {
Err(AstroError::MathError { kind: MathErrorKind::OutOfRange, message, .. }) => {
println!("{message}");
}
other => println!("unexpected: {other:?}"),
}
}
These ranges are the theories’ own. The shipped tables were measured only over 1950 to 2050, so expect larger errors far from that span. See Outside 1950–2050.
Light time
The output is geometric, so correcting for light time is up to you. To see a
planet from the Earth at time t, evaluate the planet at t − τ, where τ
is the light-travel time. A fixed-point loop converges in a few passes:
use celestial_core::constants::SPEED_OF_LIGHT_AU_PER_DAY;
use celestial_ephemeris::earth::Vsop2013Earth;
use celestial_ephemeris::planets::Vsop2013Mars;
use celestial_time::scales::tdb::tdb_from_calendar;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let tdb = tdb_from_calendar(2026, 10, 5, 0, 0, 0.0)?;
let earth = Vsop2013Earth::new().heliocentric_position(&tdb)?;
let mut mars = Vsop2013Mars.geocentric_position(&tdb, &earth)?;
for _ in 0..3 {
let tau = mars.magnitude() / SPEED_OF_LIGHT_AU_PER_DAY;
let emitted = tdb.add_days(-tau);
mars = Vsop2013Mars.heliocentric_position(&emitted)? - earth;
}
println!("Mars, corrected for light time: {:.6} AU", mars.magnitude());
Ok(())
}
Both positions in this loop are heliocentric, so it ignores how far the Sun
moves during τ. That error is at most the Sun’s speed divided by the speed
of light, 11 mas.
Where next
- Accuracy: how far each body is from DE432s, and why.
- JPL SPK Kernels: barycentric positions and kernel accuracy.
- Regenerating the Tables: keep more or fewer terms.
JPL SPK Kernels
The built-in series are compact, but they miss JPL’s ephemeris by 2 mas to 3″ depending on the body, and they give only heliocentric positions. When you need better than that, or need the Earth’s velocity about the solar system barycenter for aberration, read a JPL kernel.
JPL’s Development Ephemerides, such as DE440 and DE432s, are distributed as SPK kernels. A kernel stores JPL’s numerical integration as Chebyshev polynomials. NAIF publishes them at https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/.
This example opens a kernel and gets the Moon’s position relative to the Earth:
use celestial_ephemeris::jpl::bodies;
use celestial_ephemeris::jpl::spk::SpkFile;
use celestial_time::scales::tdb::tdb_from_calendar;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let spk = SpkFile::open("de440.bsp")?;
let tdb = tdb_from_calendar(2026, 10, 5, 0, 0, 0.0)?;
let moon = spk.compute_position(bodies::MOON, bodies::EARTH, &tdb)?;
let mars = spk.compute_position(bodies::MARS_BARYCENTER, bodies::EARTH, &tdb)?;
println!("Moon: {:.3} km", moon.magnitude());
println!("Mars: {:.3} km", mars.magnitude());
Ok(())
}
SpkFile::open reads the whole file into memory and validates every segment
it can evaluate. A truncated or damaged kernel fails at open rather than at
the first lookup. Kernels in either byte
order can be read.
Positions and velocities
compute_state(body, center, &tdb) returns the position of body relative to
center in km and its velocity in km/s, as a (Vector3, Vector3).
compute_position returns the position alone. Both use the kernel’s axes,
which for the DE kernels are the ICRF.
These units differ from the built-in theories, which use AU and AU/day. This example converts the Earth’s barycentric state, the one to use for aberration:
use celestial_core::constants::{AU_KM, SECONDS_PER_DAY_F64};
use celestial_ephemeris::jpl::bodies;
use celestial_ephemeris::jpl::spk::SpkFile;
use celestial_time::scales::tdb::tdb_from_calendar;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let spk = SpkFile::open("de440.bsp")?;
let tdb = tdb_from_calendar(2026, 10, 5, 0, 0, 0.0)?;
let (position, velocity) =
spk.compute_state(bodies::EARTH, bodies::SOLAR_SYSTEM_BARYCENTER, &tdb)?;
let position = position / AU_KM;
let velocity = velocity * (SECONDS_PER_DAY_F64 / AU_KM);
println!("Earth: {:.9} AU from the barycenter", position.magnitude());
println!("Speed: {:.9} AU/day", velocity.magnitude());
Ok(())
}
How lookups chain through centers
A kernel stores each body relative to one center. In the DE kernels:
- The planetary barycenters (1 to 9) and the Sun (10) are relative to the solar system barycenter (0).
- The Moon (301) and the Earth (399) are relative to the Earth-Moon barycenter (3).
- Mercury (199) and Venus (299) are relative to their own barycenters (1 and 2).
The kernel has no segment for the Moon relative to the Earth, yet the first
example asks for it. compute_state and compute_position relate any two
bodies the kernel connects by walking each one’s chain of centers until the
chains meet. The Moon relative to the Earth is the Moon’s offset from the
Earth-Moon barycenter minus the Earth’s offset from it.
At each step the lookup follows the last segment in the file that covers the epoch, as SPICE does, so later segments override earlier ones. A chain can have at most 32 links.
Body codes
celestial_ephemeris::jpl::bodies names the NAIF codes the DE kernels use:
| Constant | Code |
|---|---|
SOLAR_SYSTEM_BARYCENTER | 0 |
MERCURY_BARYCENTER | 1 |
VENUS_BARYCENTER | 2 |
EARTH_MOON_BARYCENTER | 3 |
MARS_BARYCENTER | 4 |
JUPITER_BARYCENTER | 5 |
SATURN_BARYCENTER | 6 |
URANUS_BARYCENTER | 7 |
NEPTUNE_BARYCENTER | 8 |
PLUTO_BARYCENTER | 9 |
SUN | 10 |
MERCURY | 199 |
VENUS | 299 |
MOON | 301 |
EARTH | 399 |
The lookup methods take plain i32 codes, so a code outside this list works
too if the kernel has it.
List a kernel’s segments
segments() returns every segment in the file, including ones this crate
can’t evaluate. Use it to check what a kernel covers before you query it:
use celestial_ephemeris::jpl::spk::SpkFile;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let spk = SpkFile::open("de440.bsp")?;
for segment in spk.segments() {
println!(
"{:>3} relative to {:>2}: type {}, frame {}, JD {} to {}",
segment.body(),
segment.center(),
segment.data_type(),
segment.frame(),
segment.start().to_julian_date().to_f64(),
segment.end().to_julian_date().to_f64(),
);
}
Ok(())
}
start() and end() return the segment’s coverage as TDB.
Supported segments
Only type 2 segments in frame 1 can be evaluated. Type 2 stores Chebyshev polynomials for position, and the velocity is their derivative. Frame 1 is the one SPICE calls J2000, which the DE kernels use for the ICRF. Every DE planetary kernel is made of these.
A lookup whose chain passes through a segment of another type or frame returns
UnsupportedType or UnsupportedFrame.
Errors
Every fallible method returns Result<_, SpkError>, where SpkError is
celestial_ephemeris::jpl::SpkError:
| Variant | Cause |
|---|---|
Io | the file can’t be read |
InvalidFormat | not an SPK file, or damaged (found at open) |
InvalidData | the segments covering the epoch form a loop or exceed 32 links |
InvalidEpoch { jd } | the epoch is NaN or infinite |
SegmentNotFound { body, center, jd } | no segments connect the pair at that epoch |
UnsupportedType | the chain needs a segment of a type other than 2 |
UnsupportedFrame | the chain needs a segment in a frame other than J2000 |
SpkError converts into AstroError, so ? works in functions that return
AstroResult.
Where next
- Planets, Sun and Moon: the built-in series, with no kernel to download.
- Accuracy: how far the built-in series are from DE432s.
Accuracy
How close are the built-in series to JPL’s ephemeris? Between 1950 and 2050, seen from the Earth’s center, Mercury through Saturn are within about 30 mas of DE432s. Uranus and Neptune are within 0.8″, Pluto within 3″, the Sun within 2.3 mas and the Moon within 38 mas.
Most of that error belongs to the theories themselves. The rest comes from truncation: the crate ships 83,780 of VSOP2013’s 2,607,947 terms and 10,754 of ELP/MPP02’s 35,901.
How the series were cut
Each body is cut where the dropped terms move its direction, seen from the Earth, by at most 10 mas over 1950 to 2050. Where the full theory already misses JPL’s ephemeris by more than that, the cut instead stays below the theory’s own error.
The 10 mas limit matches an error you already carry. The theories give heliocentric velocities, and aberration computed from them is off by up to 11 mas (see Conventions).
Measured against DE432s
Each body was compared with JPL’s DE432s at 20,000 random TDB epochs from 1950
to 2050, the span DE432s covers. Both sides are geometric positions in ICRS,
and the Earth comes from Vsop2013Earth.
As seen from the Earth’s center:
| Body | Direction, max (mas) | Direction, 99% (mas) | Distance, max (km) |
|---|---|---|---|
| Sun | 2.3 | 1.7 | 0.8 |
| Moon | 38 | 30 | 0.067 |
| Mercury | 7.4 | 3.9 | 2.9 |
| Venus | 6.9 | 4.1 | 1.3 |
| Mars | 15 | 7.1 | 3.1 |
| Jupiter | 30 | 27 | 33 |
| Saturn | 6.8 | 5.0 | 24 |
| Uranus | 752 | 679 | 2942 |
| Neptune | 176 | 155 | 1542 |
| Pluto | 3041 | 2804 | 70976 |
For the planets and the Sun, the distance column is the error in range. The
Moon row is ElpMpp02Moon::new(), and its distance column is the largest
error in position. With with_de405_fit() the Moon row becomes 21 mas, 13 mas
and 0.036 km.
The Sun’s error is the Earth’s error, since the geocentric Sun is the negated
Earth. Vsop2013Earth is within 1.7 km of DE432s.
Where the error comes from
This table compares heliocentric errors against DE432s. It sets the shipped tables beside the full VSOP2013 series. The shipped columns use the same 20,000 epochs as the table above. The full-series column was measured at 2,000 epochs over the same span.
| Body | Shipped (km) | Shipped (mas) | Full series (mas) |
|---|---|---|---|
| Mercury | 3.3 | 14 | 4.9 |
| Venus | 1.0 | 1.8 | 1.0 |
| Earth-Moon barycenter | 1.7 | 2.3 | 1.0 |
| Mars | 4.5 | 4.3 | 3.2 |
| Jupiter | 104 | 29 | 22 |
| Saturn | 45 | 6.9 | 1.8 |
| Uranus | 10354 | 749 | 562 |
| Neptune | 4002 | 182 | 117 |
| Pluto | 115429 | 3122 | 2579 |
The bodies fall into three groups:
- Mercury, Venus, Mars and Saturn are cut at the 10 mas limit. Mercury looks worse here than from the Earth because it is so close to the Sun, so a small error in km is a large angle from the Sun’s center.
- Jupiter through Pluto are cut where the dropped terms are smaller than the theory’s own error. Keeping more terms would barely change their rows.
- The Earth-Moon barycenter is cut more finely than either rule asks. Every position seen from the Earth carries the Earth’s error, so it pays to keep that error small.
For the Moon, the full series misses DE432s by 60 m with new() and by 21 m
with with_de405_fit(). The shipped table drops terms worth at most about
19 m, so it misses by the 67 m and 36 m in the first table.
Keeping more terms costs memory and speed. To make that trade differently, see Regenerating the Tables.
Outside 1950–2050
DE432s spans only 1950 to 2050, so the numbers above say nothing about other dates. Some dropped terms are secular, meaning they are multiplied by powers of time, so expect the error to grow with distance from J2000. The date ranges each theory accepts are far wider than the span measured here (see Date ranges).
Where next
- JPL SPK Kernels: tighter positions, and barycentric ones.
- Regenerating the Tables: change the thresholds and measure the result.
Regenerating the Tables
The coefficient tables in the crate are truncated copies of VSOP2013 and ELP/MPP02. Regenerate them when you want a different trade between accuracy and size: more terms for a body you care about, or fewer to shrink the crate. Accuracy explains how the shipped thresholds were chosen.
Two tools behind the cli feature do the work:
| Tool | Writes |
|---|---|
vsop2013-gen | celestial-ephemeris/src/planetary_coefficients/, one file per body and mod.rs |
elpmpp02-gen | celestial-ephemeris/src/lunar_coefficients/moon.rs |
Both tools have the same three subcommands:
downloadfetches the authors’ data files.analyzereports how many terms a threshold keeps.generatewrites Rust source.
Download the data files
VSOP2013 comes as VSOP2013p1.dat to VSOP2013p9.dat, one file per body,
from IMCCE at https://ftp.imcce.fr/pub/ephem/planets/vsop2013/solution/.
Each file’s number is the body’s number in the thresholds
table below, so 3 is the Earth-Moon barycenter. ELP/MPP02 comes as
ELP_MAIN.S1 to ELP_MAIN.S3 and ELP_PERT.S1 to ELP_PERT.S3, from
http://cyrano-se.obspm.fr/pub/2_lunar_solutions/2_elpmpp02/.
cargo run --release -p celestial-ephemeris --features cli --bin vsop2013-gen -- \
download --output vsop2013
cargo run --release -p celestial-ephemeris --features cli --bin elpmpp02-gen -- \
download --output elpmpp02
The nine VSOP2013 files total about 305 MB. If you only need one body,
vsop2013-gen download --planet 5 fetches that body alone.
Choose a threshold
A threshold keeps only the terms whose amplitude passes it:
- VSOP2013:
sqrt(S² + C²) > threshold. Units follow the variable: AU for the semi-major axis, radians for the mean longitude, and none for the four eccentricity and inclination variables. - ELP/MPP02:
amplitude >= threshold. For main-problem terms the amplitude is the absolute value of the first coefficient. For perturbation terms it issqrt(S² + C²). Units are arcseconds for longitude and latitude, and km for distance.
The shipped tables were cut at these thresholds:
| Body | Threshold | Terms kept | Terms in the series |
|---|---|---|---|
| 1 Mercury | 1e-9 | 1,434 | 272,360 |
| 2 Venus | 1e-10 | 5,242 | 289,647 |
| 3 Earth-Moon barycenter | 1e-10 | 7,813 | 294,426 |
| 4 Mars | 1e-10 | 16,287 | 309,140 |
| 5 Jupiter | 1e-9 | 7,592 | 324,608 |
| 6 Saturn | 3e-10 | 27,689 | 350,525 |
| 7 Uranus | 3e-8 | 5,124 | 330,581 |
| 8 Neptune | 1e-8 | 4,870 | 322,572 |
| 9 Pluto | 1e-7 | 7,729 | 114,088 |
| Moon (ELP/MPP02) | 1e-4 | 10,754 | 35,901 |
The generators use these thresholds unless --threshold overrides them.
Before you change one, check how many terms it keeps:
cargo run --release -p celestial-ephemeris --features cli --bin vsop2013-gen -- \
analyze --input vsop2013 --planet 4 --threshold 3e-11
cargo run --release -p celestial-ephemeris --features cli --bin elpmpp02-gen -- \
analyze --input elpmpp02 --threshold 1e-5
Generate the source
cargo run --release -p celestial-ephemeris --features cli --bin vsop2013-gen -- \
generate --input vsop2013 --output celestial-ephemeris/src/planetary_coefficients
cargo run --release -p celestial-ephemeris --features cli --bin elpmpp02-gen -- \
generate --input elpmpp02 --output celestial-ephemeris/src/lunar_coefficients
rustfmt --edition 2021 celestial-ephemeris/src/planetary_coefficients/*.rs \
celestial-ephemeris/src/lunar_coefficients/moon.rs
vsop2013-gen generate --planet N regenerates a single body. The new
mod.rs still lists the bodies already in the output directory, so the
others stay in the build.
Each generated file starts with the command and threshold that produced it:
//! VSOP2013 coefficients for Mercury
//!
//! Generated from VSOP2013p1.dat by
//! `vsop2013-gen generate --input <dir> --output <dir> --planet 1 --threshold 1e-9`
//! Terms retained: 1434 of 272360 (0.5%)
The output is deterministic. Running the commands above with the default
thresholds, then rustfmt, reproduces the shipped files byte for byte.
Ship new thresholds
The tests pin the shipped tables, so a new threshold means updating each of
the following. Paths are relative to celestial-ephemeris/.
default_thresholdinsrc/bin/vsop2013_gen/generate/mod.rs, orDEFAULT_THRESHOLDinsrc/bin/elpmpp02_gen/generate/mod.rs. A test checks that these match the headers of the shipped files.- The exact values in
src/planets/tests/state.rs. - The bounds in
src/planets/tests/ctl.rsandsrc/planets/tests/de432s.rs. Each bound is the largest miss of the shipped table, rounded up. - For the Moon, the vectors in
src/moon/tests/authors/vectors.rs. They come from the authors’ Fortran, run on the same truncated series. - The numbers on the Accuracy page, and the term counts in
celestial-ephemeris/README.md.
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.
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.
How the Transformation Works
Most of the time you call pixel_to_celestial and never think about what’s
inside. You’ll want the details when a header doesn’t behave the way you
expect, when you’re writing a fitter that adjusts one stage, or when you need
the plane coordinates a solver works in. This page follows one pixel through
each stage and shows which header keywords drive it.
The FITS WCS papers split the trip from pixel to sky into four coordinate systems:
pixel (x, y)
│ linear: subtract CRPIX, multiply by the CD matrix
▼
intermediate (x, y) in degrees, a flat plane
│ deproject: undo the map projection
▼
native (φ, θ), spherical, with the projection's own pole
│ rotate: turn the native sphere onto the sky
▼
celestial (α, δ)
celestial_to_pixel runs the same stages backwards. Each stage is public, so
you can run them yourself:
use celestial_wcs::coordinate::PixelCoord;
use celestial_wcs::linear::LinearTransform;
use celestial_wcs::spherical::{Projection, SphericalRotation};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let crpix = [800.5, 600.5];
let crval = [148.8882, 69.0653];
let cd = [[-3.2604e-4, 6.930e-5], [6.930e-5, 3.2604e-4]];
let linear = LinearTransform::from_cd(crpix, cd)?;
let projection = Projection::tan();
let (phi_0, theta_0) = projection.native_reference();
let rotation = SphericalRotation::from_crval(crval[0], crval[1], phi_0, theta_0, None, None)?;
let pixel = PixelCoord::new(1203.4, 377.9);
let plane = linear.pixel_to_intermediate(pixel);
let native = projection.deproject(plane)?;
let sky = rotation.native_to_celestial(native)?;
println!("pixel: ({}, {})", pixel.x(), pixel.y());
println!("intermediate: ({:.6}°, {:.6}°)", plane.x_deg(), plane.y_deg());
println!("native: φ {:.4}°, θ {:.4}°", native.phi_deg(), native.theta_deg());
println!("celestial: RA {:.5}°, Dec {:.5}°", sky.alpha_deg(), sky.delta_deg());
Ok(())
}
pixel: (1203.4, 377.9)
intermediate: (-0.146788°, -0.044656°)
native: φ -73.0793°, θ 89.8466°
celestial: RA 148.47822°, Dec 69.02015°
The result matches what Wcs::pixel_to_celestial returns for the same header
on Pixels and Sky Coordinates. The Wcs adds two
things this sketch leaves out: distortion, and the PV1_0 offset described
below.
The linear stage
The linear stage turns a pixel into a position on a flat plane, measured in degrees from the reference point:
intermediate = CD × (pixel − CRPIX)
That plane is the intermediate world coordinate system, IntermediateCoord
in the code. It’s where scale, rotation, skew and axis flips live, and it’s the
space a plate solver fits in, because the transformation into it is linear.
A header can state the matrix three ways, and from_header reads all of them:
| Header form | What it holds | How it’s read |
|---|---|---|
CDi_j | the matrix itself, in degrees per pixel | used as is |
PCi_j with CDELTi | a unitless matrix and a scale per axis | row i of PC times CDELTi |
CDELTi with CROTA2 | the pre-2002 AIPS form: scales and a rotation | converted with Paper II eq. 189 |
If a header has any CDi_j, the CD form wins and missing elements are 0. Any
PCi_j keyword means the PC form, with missing elements taken from the
identity matrix. CROTA2 is read only when neither is present, because the
FITS standard doesn’t allow it beside PC.
Here’s an old-style header with a 12° rotation, and the CD matrix it becomes:
use celestial_wcs::builder::WcsBuilder;
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)
.set_float("CROTA2", 12.0);
let wcs = WcsBuilder::from_header(&header)?.build()?;
let cd = wcs.cd_matrix();
println!("CD1_1 {:.6e} CD1_2 {:.6e}", cd[0][0], cd[0][1]);
println!("CD2_1 {:.6e} CD2_2 {:.6e}", cd[1][0], cd[1][1]);
Ok(())
}
CD1_1 -3.260459e-4 CD1_2 -6.930320e-5
CD2_1 -6.930320e-5 CD2_2 3.260459e-4
CUNITi sets the unit of CRVALi, CDi_j and CDELTi. The reader accepts
deg, arcmin, arcsec, mas and rad, and converts each to degrees. An
absent CUNITi means degrees. Any other unit returns
WcsError::InvalidKeyword, since a celestial axis must be angular.
A header can also list latitude first, as CTYPE1 = 'DEC--TAN' and
CTYPE2 = 'RA---TAN'. The reader swaps the world-axis keywords so longitude
comes first, while CRPIXj and the second index of CDi_j still number the
pixel axes. You get RA from alpha_deg() either way.
The projection stage
The intermediate plane is a flat map of part of a sphere, and the projection
says which map. Deprojecting turns a plane position into native spherical
coordinates (φ, θ), NativeCoord in the code. Native coordinates are
longitude and latitude on a sphere whose pole is the projection’s own pole. For
TAN and the other zenithal projections that pole is the center of the field,
so θ is 90° minus the distance from the field center. In the example above,
θ = 89.8466° says the pixel is 0.1534° from the reference point.
Projections covers each projection and its parameters.
The spherical rotation
The last stage turns the native sphere so its reference point lands on CRVAL.
SphericalRotation holds three angles from Paper II: the celestial longitude
and latitude of the native pole, (αp, δp), and the native longitude of the
celestial pole, φp.
Every projection has a native reference point (φ0, θ0), returned by
Projection::native_reference. CRVAL gives the celestial coordinates of that
point, and the reference pixel CRPIX maps onto it:
| Projections | (φ0, θ0) |
|---|---|
| zenithal: TAN, SIN, ARC, ZEA, STG, AZP, SZP, ZPN, AIR | (0°, 90°) |
| conic: COP, COE, COD, COO | (0°, θa) |
| everything else | (0°, 0°) |
CRVAL alone doesn’t fix the rotation: the sky can still spin about the
reference point. LONPOLE (φp) removes that freedom. When it’s absent the
crate uses the Paper II default, which makes celestial latitude increase along
+y of the intermediate plane at the reference point. For a zenithal projection
the default is 180°, and with it CRVAL fixes the whole rotation.
For the other projections, CRVAL and LONPOLE can leave two possible
latitudes for the native pole. The crate takes the one nearer LATPOLE, which
defaults to 90°. You’ll
rarely set either unless you’re reproducing a header that already has them.
The PV1_m keywords on the longitude axis adjust this stage, following Paper
II §2.5 and §2.6:
| Keyword | Effect |
|---|---|
PV1_1, PV1_2 | replace the projection’s (φ0, θ0) |
PV1_0 | when nonzero, shift the plane so the new (φ0, θ0) still falls at CRPIX |
PV1_3, PV1_4 | stand in for LONPOLE and LATPOLE, and win over them |
Wcs::native_reference returns (φ0, θ0) after any PV1_1 and PV1_2
override. A TPV header uses every PV1_m as a polynomial term instead, so none
of these apply to it.
Distortion
A SIP or TPV correction adds one more step. SIP adjusts the pixel position before the linear stage, and TPV adjusts the intermediate coordinates after it. Distortion: SIP and TPV has the details.
Where next
- Projections: the projection stage in detail.
- Distortion: SIP and TPV: the corrections around the linear stage.
- Building a WCS in code: set each stage’s parameters directly.
Projections
The sky is a sphere and an image is flat, so every WCS needs a map projection, and no projection keeps every distance, angle and area at once. Across the few arcminutes of a telescope image the choice barely matters. Across a fisheye frame or an all-sky survey map it matters a lot, and the header has to name the projection the data was actually made with.
The crate implements all 26 celestial projection codes from FITS WCS Paper II (Calabretta & Greisen 2002). Here’s how much five of them disagree as you move away from the field center, with the same 0.01°-per-pixel scale for each:
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::coordinate::PixelCoord;
use celestial_wcs::spherical::Projection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let projections = [
Projection::tan(),
Projection::sin(),
Projection::arc(),
Projection::zea(),
Projection::stg(),
];
for projection in projections {
let wcs = WcsBuilder::new()
.crpix(0.0, 0.0)
.crval(120.0, 30.0)
.cd_matrix([[-0.01, 0.0], [0.0, 0.01]])
.projection(projection)
.build()?;
let code = wcs.projection_code();
// 1° and 40° north of the reference pixel
let near = wcs.pixel_to_celestial(PixelCoord::new(0.0, 100.0))?;
let far = wcs.pixel_to_celestial(PixelCoord::new(0.0, 4000.0))?;
println!("{code}: Dec {:.5}° at 100 px, {:.3}° at 4000 px", near.delta_deg(), far.delta_deg());
}
Ok(())
}
TAN: Dec 30.99990° at 100 px, 64.920° at 4000 px
SIN: Dec 31.00005° at 100 px, 74.277° at 4000 px
ARC: Dec 31.00000° at 100 px, 70.000° at 4000 px
ZEA: Dec 31.00001° at 100 px, 70.860° at 4000 px
STG: Dec 30.99997° at 100 px, 68.485° at 4000 px
At 1° from the center the five agree to within 0.00015°, about half an arcsecond. At 40° they’re spread over more than 9°. ARC keeps distance from the center exactly, so its 4000 pixels are exactly 40°. If you’re unsure which projection a wide-field image uses, this is why a wrong guess shows up first at the edges.
Pick a projection
Each code has a constructor on celestial_wcs::spherical::Projection, named
after the code in lower case. When you read a header, the code comes from
CTYPE1 and CTYPE2, which must name the same one.
| Code | Name | Where you’ll see it |
|---|---|---|
| TAN | gnomonic | Plate-solved telescope images. Straight lines on the sky are straight in the image. |
| SIN | orthographic, slant orthographic | Radio interferometer images. With PV2_1 and PV2_2 it covers the older NCP form. |
| ARC | zenithal equidistant | Wide fields where distance from the center should stay linear. |
| ZEA | zenithal equal area | Maps of a polar cap, or any wide field where areas must stay true. |
| STG | stereographic | Conformal wide-field maps: small circles stay circles. |
| AZP | zenithal perspective | A perspective view from a finite distance, with optional tilt. |
| SZP | slant zenithal perspective | AZP with the viewpoint off the axis. |
| ZPN | zenithal polynomial | Wide-field and fisheye optics whose radial distortion is fitted as a polynomial. |
| AIR | Airy | A zenithal projection that minimizes overall scale error inside a chosen radius. |
| CAR | plate carrée | All-sky maps on a regular longitude-latitude grid. |
| MER | Mercator | Conformal cylindrical maps. |
| CEA | cylindrical equal area | Equal-area cylindrical maps, with a parameter λ. |
| CYP | cylindrical perspective | Cylindrical maps with a perspective parameter. |
| SFL | Sanson-Flamsteed | Equal-area pseudocylindrical maps. Older headers called it GLS. |
| PAR | parabolic | Equal-area pseudocylindrical maps. |
| MOL | Mollweide | Equal-area all-sky maps. |
| AIT | Hammer-Aitoff | All-sky maps, often in galactic coordinates. |
| COP | conic perspective | Maps of a band of latitude. |
| COE | conic equal area | Equal-area maps of a band of latitude. |
| COD | conic equidistant | Maps of a band of latitude with true distance along meridians. |
| COO | conic orthomorphic | Conformal maps of a band of latitude. |
| BON | Bonne | Equal-area maps with a chosen standard parallel. |
| PCO | polyconic | Maps along a central meridian. |
| TSC | tangential spherical cube | The sky on six cube faces. |
| CSC | COBE quadrilateralized spherical cube | The cube layout used for COBE data. |
| QSC | quadrilateralized spherical cube | An equal-area cube layout. |
The crate doesn’t read the older AIPS codes GLS and NCP. A header that uses one
returns WcsError::UnsupportedProjection, as does any code not in the table.
Projection parameters
Some projections take parameters. In a header they’re PV2_m keywords on the
latitude axis. In code they’re arguments to the constructor:
| Code | Constructor | Header keywords and defaults |
|---|---|---|
| SIN | sin(), sin_with_params(xi, eta) | PV2_1 ξ = 0, PV2_2 η = 0 |
| AZP | azp(mu, gamma) | PV2_1 μ = 0, PV2_2 γ = 0 |
| SZP | szp(mu, phi_c, theta_c) | PV2_1 μ = 0, PV2_2 φc = 0, PV2_3 θc = 90 |
| ZPN | zpn(coeffs) | PV2_0 to PV2_29, each 0 |
| AIR | air(theta_b) | PV2_1 θb = 90 |
| CEA | cea(), cea_with_lambda(lambda) | PV2_1 λ = 1 |
| CYP | cyp(mu, lambda) | PV2_1 μ = 1, PV2_2 λ = 1 |
| COP, COE, COD, COO | cop(theta_a, eta) and so on | PV2_1 θa required, PV2_2 η = 0 |
| BON | bon(theta_1) | PV2_1 θ1 required |
Angles are in degrees. The defaults are Paper II’s, so a SIN header with no
PV2_m is plain orthographic.
The conics and BON have no sensible default for their first parameter, so a header without it fails to build:
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::coordinate::PixelCoord;
use celestial_wcs::spherical::Projection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let missing = WcsBuilder::new()
.crpix(0.0, 0.0)
.crval(0.0, 45.0)
.cd_matrix([[-0.1, 0.0], [0.0, 0.1]])
.proj_code("COE")
.build();
println!("{}", missing.unwrap_err());
// Cone of standard parallels at 30° and 60°: θa = 45°, η = 15°
let wcs = WcsBuilder::new()
.crpix(0.0, 0.0)
.crval(0.0, 45.0)
.cd_matrix([[-0.1, 0.0], [0.0, 0.1]])
.projection(Projection::coe(45.0, 15.0))
.build()?;
println!("native reference: {:?}", wcs.native_reference());
let sky = wcs.pixel_to_celestial(PixelCoord::new(-200.0, 100.0))?;
println!("RA {:.4}°, Dec {:.4}°", sky.alpha_deg(), sky.delta_deg());
Ok(())
}
Missing required WCS keyword: PV2_1
native reference: (0.0, 45.0)
RA 33.5376°, Dec 50.7484°
A conic’s two standard parallels are θa − η and θa + η. Its native reference point is (0°, θa), so CRVAL2 names the declination at θa.
ZPN from a header
ZPN’s radius is a polynomial in the distance from the field center:
R = (180°/π) Σ PV2_m (90° − θ)^m, with 90° − θ in radians. A header that sets
PV2_1 = 1 and nothing else is ARC. Higher terms describe barrel or pincushion
distortion in wide-field optics:
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::coordinate::PixelCoord;
use celestial_wcs::header::KeywordMap;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut header = KeywordMap::new();
header
.set_string("CTYPE1", "RA---ZPN")
.set_string("CTYPE2", "DEC--ZPN")
.set_float("CRPIX1", 2048.5)
.set_float("CRPIX2", 2048.5)
.set_float("CRVAL1", 83.82)
.set_float("CRVAL2", -5.39)
.set_float("CDELT1", -0.002)
.set_float("CDELT2", 0.002)
.set_float("PV2_1", 1.0)
.set_float("PV2_3", 0.05);
let wcs = WcsBuilder::from_header(&header)?.build()?;
let sky = wcs.pixel_to_celestial(PixelCoord::new(3500.0, 3500.0))?;
println!("{}: RA {:.4}°, Dec {:.4}°", wcs.projection_code(), sky.alpha_deg(), sky.delta_deg());
Ok(())
}
ZPN: RA 80.9163°, Dec -2.4821°
Points a projection can’t show
Many projections cover only part of the sphere. TAN reaches less than 90° from its center, and SIN shows one hemisphere. Asking for a point outside that region returns an error instead of a wrong coordinate. Both directions check:
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::coordinate::{CelestialCoord, PixelCoord};
use celestial_wcs::spherical::Projection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let wcs = WcsBuilder::new()
.crpix(0.0, 0.0)
.crval(120.0, 30.0)
.cd_matrix([[-0.01, 0.0], [0.0, 0.01]])
.projection(Projection::sin())
.build()?;
println!("{:?}", wcs.pixel_to_celestial(PixelCoord::new(0.0, 6000.0)));
println!("{:?}", wcs.celestial_to_pixel(CelestialCoord::new(300.0, -30.0)));
Ok(())
}
Err(OutOfBounds { message: "Point outside SIN projection boundary" })
Err(OutOfBounds { message: "SIN projection: point beyond the limb" })
The pixel 60° from the center lies outside SIN’s disk of radius 57.3°. The sky
position is the antipode of the field center, on the far side of the sphere.
Depending on the projection, the error is WcsError::OutOfBounds or
WcsError::Singularity. If you convert a whole grid of pixels, expect some of
them to fail at the edges of a wide map, and skip those.
Parameters outside Paper II’s range fail when you build. AZP with γ = ±90°, AZP
with µ = −1 (every point projects to the origin), CEA with λ ≤ 0 and AIR with
θb outside [−90°, 90°] each return WcsError::InvalidParameter.
Where next
- Distortion: SIP and TPV: the corrections a TAN header often carries.
- How the transformation works: where the projection sits in the chain.
Distortion: SIP and TPV
Real optics don’t produce a perfect projection. Field curvature, a field flattener at the wrong spacing or a tilted sensor bend the star pattern slightly, so a linear WCS that fits the center of the frame drifts by an arcsecond or more toward the corners. Plate solvers fix this by fitting a small polynomial on top of the projection and writing its coefficients into the header.
Two conventions for that polynomial are in wide use, and the crate reads and writes both:
- SIP (Simple Imaging Polynomial, Shupe et al. 2005) corrects pixel positions. astrometry.net and many amateur plate solvers write SIP.
- TPV corrects the intermediate plane coordinates of a TAN projection. You’ll find it in headers from survey pipelines such as SCAMP.
Neither needs any setup: the header names the convention, and
WcsBuilder::from_header applies it.
Read a SIP header
A -SIP suffix on both CTYPE values turns SIP on. Here’s the M81 field from
Pixels and Sky Coordinates with a second-order SIP
correction, compared against the same header without it:
use celestial_core::angle::Angle;
use celestial_core::math::angular_separation;
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-SIP")
.set_string("CTYPE2", "DEC--TAN-SIP")
.set_float("CRPIX1", 800.5)
.set_float("CRPIX2", 600.5)
.set_float("CRVAL1", 148.8882)
.set_float("CRVAL2", 69.0653)
.set_float("CD1_1", -3.2604e-4)
.set_float("CD1_2", 6.930e-5)
.set_float("CD2_1", 6.930e-5)
.set_float("CD2_2", 3.2604e-4)
.set_int("A_ORDER", 2)
.set_float("A_2_0", 2.1e-6)
.set_float("A_1_1", -4.0e-7)
.set_float("A_0_2", 8.0e-7)
.set_int("B_ORDER", 2)
.set_float("B_2_0", -6.0e-7)
.set_float("B_1_1", 1.7e-6)
.set_float("B_0_2", 3.0e-7);
let wcs = WcsBuilder::from_header(&header)?.build()?;
let corner = PixelCoord::new(1600.0, 1200.0);
let sky = wcs.pixel_to_celestial(corner)?;
println!("corner: RA {:.5}°, Dec {:.5}°", sky.alpha_deg(), sky.delta_deg());
header
.set_string("CTYPE1", "RA---TAN")
.set_string("CTYPE2", "DEC--TAN");
let plain = WcsBuilder::from_header(&header)?.build()?;
let undistorted = plain.pixel_to_celestial(corner)?;
let shift = angular_separation(
sky.alpha().radians(), sky.delta().radians(),
undistorted.alpha().radians(), undistorted.delta().radians(),
);
println!("SIP moves the corner by {:.2}\"", Angle::from_radians(shift).arcseconds());
let back = wcs.celestial_to_pixel(CelestialCoord::new(sky.alpha_deg(), sky.delta_deg()))?;
println!("back to pixel: x {:.6}, y {:.6}", back.x(), back.y());
Ok(())
}
corner: RA 148.26662°, Dec 69.31533°
SIP moves the corner by 1.84"
back to pixel: x 1600.000000, y 1200.000000
The coefficients are tiny, but they multiply the square of the distance from CRPIX, about 1000 pixels at this corner. That’s how a 1e-6 term moves a star by almost two arcseconds.
What SIP computes
SIP measures a pixel’s offset from the reference pixel, u = x − CRPIX1 and v = y − CRPIX2, and adds two polynomials before the linear stage:
x' = x + Σ A_p_q · u^p · v^q
y' = y + Σ B_p_q · u^p · v^q
The sums run over p + q ≤ A_ORDER (or B_ORDER). A_ORDER and B_ORDER are
required and must be 2 to 9. Terms the header leaves out are 0.
Going from sky to pixel means inverting those polynomials. Some headers carry a
fitted inverse, the AP_p_q and BP_p_q terms with AP_ORDER and
BP_ORDER. A fitted inverse only approximates the true one, so the crate uses
it as a starting guess and then solves the forward polynomials with Newton’s
method. That’s why the round trip
above lands back on 1600.000000, 1200.000000. Without AP and BP, Newton starts
from the pixel itself, which works because the correction is small next to the
pixel position. If Newton doesn’t converge in 20 steps, celestial_to_pixel returns
WcsError::ConvergenceFailure.
AP_ORDER and BP_ORDER must appear together. A header with only one of them
returns WcsError::MissingKeyword.
Build SIP in code
When your own fitter produced the coefficients, build a SipDistortion and pass
it to the builder:
use celestial_wcs::builder::{WcsBuilder, WcsKeywordValue};
use celestial_wcs::distortion::sip::SipDistortion;
use celestial_wcs::distortion::DistortionModel;
use celestial_wcs::spherical::Projection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let crpix = [800.5, 600.5];
let mut sip = SipDistortion::new(crpix, 2, 2)?;
sip.set_a(2, 0, 2.1e-6)?;
sip.set_b(1, 1, 1.7e-6)?;
let wcs = WcsBuilder::new()
.crpix(crpix[0], crpix[1])
.crval(148.8882, 69.0653)
.cd_matrix([[-3.2604e-4, 6.930e-5], [6.930e-5, 3.2604e-4]])
.projection(Projection::tan())
.distortion(DistortionModel::Sip(sip))
.build()?;
for keyword in wcs.to_keywords() {
let name = keyword.name;
if name.starts_with("CTYPE") || name.starts_with('A') || name.starts_with('B') {
match keyword.value {
WcsKeywordValue::Real(v) => println!("{name:<8} = {v}"),
WcsKeywordValue::Integer(v) => println!("{name:<8} = {v}"),
WcsKeywordValue::String(v) => println!("{name:<8} = '{v}'"),
}
}
}
Ok(())
}
CTYPE1 = 'RA---TAN-SIP'
CTYPE2 = 'DEC--TAN-SIP'
A_ORDER = 2
A_2_0 = 0.0000021
B_ORDER = 2
B_1_1 = 0.0000017
SipDistortion::new takes the reference pixel and the two orders, and
returns WcsError::InvalidParameter for an order outside 2 to 9, the range
the SIP convention allows. set_inverse_order takes 0 to 9. The
reference pixel must equal the builder’s crpix, because SIP measures its
offsets from CRPIX. If they differ, build returns
WcsError::InvalidParameter.
The setters check each term as you add it. set_a(2, 1, ...) on an order-2
polynomial fails, since p + q = 3 is beyond the order, and so does a NaN or
infinite coefficient. Setting a term to 0 removes it, which is why
to_keywords writes only nonzero terms. For a fitted inverse, call
set_inverse_order(ap_order, bp_order) first, then set_ap and set_bp.
Read a TPV header
TPV is a projection code of its own, RA---TPV and DEC--TPV. It’s TAN plus
a polynomial in the intermediate plane coordinates, with the coefficients in
PV1_0 through PV1_39 and PV2_0 through PV2_39:
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::coordinate::PixelCoord;
use celestial_wcs::header::KeywordMap;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut header = KeywordMap::new();
header
.set_string("CTYPE1", "RA---TPV")
.set_string("CTYPE2", "DEC--TPV")
.set_float("CRPIX1", 1024.5)
.set_float("CRPIX2", 2048.5)
.set_float("CRVAL1", 150.1163)
.set_float("CRVAL2", 2.2010)
.set_float("CD1_1", -7.3e-5)
.set_float("CD1_2", 0.0)
.set_float("CD2_1", 0.0)
.set_float("CD2_2", 7.3e-5)
.set_float("PV1_0", 1.2e-5)
.set_float("PV1_1", 1.0003)
.set_float("PV1_7", -0.012)
.set_float("PV2_0", -8.0e-6)
.set_float("PV2_1", 0.9998)
.set_float("PV2_7", -0.011);
let wcs = WcsBuilder::from_header(&header)?.build()?;
let sky = wcs.pixel_to_celestial(PixelCoord::new(1.0, 1.0))?;
println!("{}: RA {:.5}°, Dec {:.5}°", wcs.projection_code(), sky.alpha_deg(), sky.delta_deg());
let back = wcs.celestial_to_pixel(sky)?;
println!("back: x {:.6}, y {:.6}", back.x(), back.y());
Ok(())
}
TAN: RA 150.19109°, Dec 2.05159°
back: x 1.000000, y 1.000000
projection_code returns TAN, because that’s the projection doing the work.
to_keywords still writes TPV in CTYPE, along with every coefficient that
differs from its default.
What TPV computes
With (x, y) the intermediate coordinates in degrees and r = √(x² + y²), TPV replaces them with
ξ = PV1_0 + PV1_1·x + PV1_2·y + PV1_3·r + PV1_4·x² + PV1_5·x·y + PV1_6·y² + ...
η = PV2_0 + PV2_1·y + PV2_2·x + PV2_3·r + PV2_4·y² + PV2_5·y·x + PV2_6·x² + ...
The terms run up to seventh order, 40 per axis. The second axis uses the same
term list with x and y swapped. Absent terms are 0, except PV1_1 and PV2_1,
which are 1, so a TPV header with no PV keywords is plain TAN. The inverse is
solved with Newton’s method, as for SIP.
Since TPV uses every PV1_m as a coefficient, a TPV WCS can’t also use
PV1_0 to PV1_4 to move the reference point or set the pole. See
How the transformation works.
To build TPV in code, fill a celestial_wcs::distortion::tpv::TpvDistortion
with set_pv(axis, m, value) and pass DistortionModel::Tpv(Box::new(tpv)) to
the builder, with Projection::tan() as the projection. Any other projection
returns WcsError::InvalidParameter from build.
Other conventions
The crate reads SIP and TPV only. A CTYPE with any other suffix, such as
RA---TAN-XYZ, returns WcsError::UnsupportedProjection. The IRAF codes TNX
and ZPX, and the DPj and DQi lookup distortions from the draft FITS
distortion paper, aren’t supported. A header with TNX or ZPX fails at the
projection code. A header with DPj cards and no suffix builds without them,
so its corners will be off by however much distortion the cards describe.
Where next
- Pixels and Sky Coordinates: reading headers and converting coordinates.
- Building a WCS in code: the rest of the builder.
Open and Save Images
Your camera writes 16-bit FITS. Your stacking program writes 32-bit float
XISF. A friend sends a tile-compressed .fits.fz. You want the pixels and the
header keywords from each of them without writing three readers. Image::open
reads any of these files into the same type:
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("cygnus.fit")?;
println!("{} x {}, {} channel(s)", img.width(), img.height(), img.channels());
println!("OBJECT = {:?}", img.get("OBJECT").as_str());
println!("FOCALLEN = {:?}", img.get("FOCALLEN").as_f64());
println!("EXPTIME = {:?}", img.get("EXPTIME").as_f64());
match &img.pixels {
PixelData::F32(samples) => println!("{} f32 samples", samples.len()),
PixelData::U16(samples) => println!("{} u16 samples", samples.len()),
other => println!("{} samples, BITPIX {:?}", other.len(), other.bitpix()),
}
Ok(())
}
512 x 512, 1 channel(s)
OBJECT = Some("Cygnus Wall")
FOCALLEN = Some(675.0)
EXPTIME = None
262144 f32 samples
cygnus.fit is in celestial-images/test_data: a 512 x 512 crop of a stacked
image, stored as 32-bit floats. Image::open picks the format from the file
extension: .fits, .fit and .fts are FITS, and .xisf is XISF. For any
other extension it reads the first bytes of the file and decides from those.
What an Image holds
An Image has four public fields:
pixels, aPixelDatawith one variant per sample type, fromU8toF64.dimensions, the axis lengths in FITS order:[width, height]for a mono image and[width, height, 3]for RGB.keywords, the header cards as aVec<Keyword>. An XISF file stores FITS keywords too, so both formats fill this field.xisf_properties, the XISF properties of the image. It’s empty for FITS.
The pixel type follows the file. A 16-bit camera frame comes back as U16 and
a float stack as F32, with no conversion, so the values you read are the
values the camera or the stacking program wrote. Each PixelData variant has
an accessor (as_u16, as_f32 and so on) that returns None for the other
variants. FITS Files explains which variant each FITS BITPIX
and BZERO combination produces.
Read header keywords
img.get(name) returns a Field, which converts the card’s value on request:
| Method | Returns Some for |
|---|---|
as_str | string cards, with trailing spaces removed |
as_f64 | real and integer cards, so CRPIX1 = 800 reads as 800.0 |
as_i64 | integer cards only |
as_bool | logical cards (T or F) |
exists | true when the card is present, whatever its value |
A missing keyword is not an error. Every method returns None, as EXPTIME
did above, so you decide what a missing value means for your program.
When a header repeats a name, get returns the first card and get_last
returns the last one. FITS readers apply the last value of a repeated card, so
use get_last for anything that changes how you interpret the pixels, such as
WCS keywords. Pixels and Sky Coordinates shows a
KeywordProvider built on get_last that turns an image header into a WCS.
Change keywords and save in another format
set_keyword replaces every card of the same name with one new card, and
remove_keyword deletes them. HISTORY and COMMENT cards are appended
instead, since a header holds many of each. save picks the format from the
extension, the same way open does:
use celestial_images::fits::header::keywords::Keyword;
use celestial_images::formats::image::Image;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut img = Image::open("cygnus.fit")?;
img.set_keyword(Keyword::string("OBSERVER", "A. Observer"));
img.set_keyword(Keyword::history("Converted to XISF"));
img.remove_keyword("ROWORDER");
img.save("cygnus.xisf")?;
let copy = Image::open("cygnus.xisf")?;
println!("OBSERVER = {:?}", copy.get("OBSERVER").as_str());
println!("ROWORDER = {:?}", copy.get("ROWORDER").as_str());
println!("same pixels: {}", copy.pixels.as_f32() == img.pixels.as_f32());
Ok(())
}
OBSERVER = Some("A. Observer")
ROWORDER = None
same pixels: true
save writes the whole file to memory first and then replaces the file on
disk, so a save that fails leaves an existing file as it was.
Converting between formats keeps every pixel value, but XISF has no signed
integer samples. A FITS file with BITPIX = 16 and no BZERO holds i16
samples, and saving it as XISF fails until you convert the samples:
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A bias frame stored as BITPIX = 16 with no BZERO, so its samples are i16
let mut bias = Image::new(PixelData::I16(vec![-12, 0, 7, 3]), [2, 2]);
if let Err(e) = bias.save("bias.xisf") {
println!("{e}");
}
bias.pixels = bias.pixels.signed_to_float()?;
bias.save("bias.xisf")?;
println!("{:?}", Image::open("bias.xisf")?.pixels);
Ok(())
}
XISF error: Unsupported sample format: Int16 pixels: XISF 1.0 has no signed integer sample format; convert them with PixelData::signed_to_offset_unsigned or PixelData::signed_to_float
F32([-12.0, 0.0, 7.0, 3.0])
signed_to_float keeps the values. signed_to_offset_unsigned adds 32768 so
the samples fit u16, which keeps the file the same size but shifts every
value.
Color images
An RGB Image holds its samples interleaved: red, green and blue of the first
pixel, then of the second, and so on. That’s the order a display or a texture
upload wants. FITS stores the three colors as separate planes, all the red
samples first, and XISF usually does the same. open and save reorder the
samples for you:
use celestial_images::fits::io::reader::FitsFile;
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Two pixels, an orange one and a blue one, stored R G B R G B
let img = Image::new(PixelData::U8(vec![255, 128, 0, 0, 64, 255]), [2, 1, 3]);
img.save("two.fits")?;
let (_, on_disk) = FitsFile::open("two.fits")?.read_hdu_with_data::<u8>(0)?;
println!("in the file: {on_disk:?}");
let back = Image::open("two.fits")?;
println!("in memory: {:?}, {:?}", back.pixels, back.kind());
Ok(())
}
in the file: [255, 0, 128, 64, 0, 255]
in memory: U8([255, 128, 0, 0, 64, 255]), Rgb
Only an image with exactly three axes and three planes counts as RGB. A data
cube with any other number of planes keeps its planes one after another.
interleaved_to_planar and planar_to_interleaved convert an RGB image in
place when you need the other order.
Scale pixels to [0, 1]
Display code and many algorithms want floats between 0 and 1. There are two ways to get them, and they answer different questions:
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;
fn main() {
let mut frame = Image::new(PixelData::U16(vec![1000, 1010, 1040, 2000]), [4]);
println!("{:?}", frame.pixels.to_f32());
println!("{:?}", frame.pixels.to_f32_normalized());
frame.normalize();
println!("{:?}", frame.pixels);
}
[1000.0, 1010.0, 1040.0, 2000.0]
[0.015259022, 0.015411613, 0.015869383, 0.030518044]
F64([0.0, 0.01, 0.04, 1.0])
to_f32converts the values and doesn’t scale them.to_f32_normalizeddivides by the range of the type, 65535 foru16. A value means the same thing in every image of that type, which is what you want when you compare frames. Float images already in [0, 1] stay as they are, and 64-bit integers and other float images are scaled by their own minimum and maximum.normalizescales by the image’s own minimum and maximum, so the faintest pixel becomes 0 and the brightest 1. That’s useful for a quick look, but one hot pixel sets the maximum, and two frames scaled this way can’t be compared. NaN and infinite samples don’t count toward the minimum and maximum, and keep their value.
normalize replaces the pixels: integer images become F64, and float images
keep their type. For a display stretch that ignores hot pixels, see
Stretching for Display.
What Image::open reads
Image::open returns one image per file. For FITS, that’s the first HDU that
holds image data, which is what most programs mean by “the image”. A
tile-compressed image counts, so a .fits.fz file opens like any other. For
XISF, it’s the first Image element. To reach the other HDUs of a FITS file,
use FitsFile as FITS Files shows. To reach the other images of
an XISF file, use XisfFile as XISF Files shows.
With the standard-formats feature, Image also opens and saves PNG and TIFF
files. They have no header keywords, so keywords comes back empty.
Where next
- Write a New Image: build a FITS or XISF file from a pixel buffer, with metadata and a WCS.
- FITS Files and XISF Files: what each format stores and what the crate supports.
- Debayering: turn a one-shot color camera’s raw frame into RGB.
- Solve Your First Image: plate-solve an
Image.
Write a New Image
You have pixels in a Vec: a frame from a camera driver, or the output of
your own stacking or calibration code. You want a FITS or XISF file that
other programs open with the right metadata, and a WCS if you’ve solved the
image. The crate has two ways to get there. AstroImage borrows your buffer
and writes it with a builder. Image, the type Image::open returns, owns
its pixels and suits a frame you’ll keep working on.
Write a buffer with AstroImage
Here a stacked, plate-solved frame goes to disk with its metadata and WCS:
use celestial_images::fits::header::keywords::Keyword;
use celestial_images::fits::io::reader::FitsFile;
use celestial_images::formats::astro_image::AstroImage;
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::spherical::Projection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A stacked frame from your own pipeline, already plate-solved
let stack = vec![0.1f32; 1600 * 1200];
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()?;
AstroImage::new(&stack, [1600, 1200])
.object("M81")
.filter("L")
.exposure(3600.0)
.date_obs("2026-03-20T03:15:00")
.keyword(Keyword::integer("NCOMBINE", 12).with_comment("frames stacked"))
.wcs(&wcs)
.write_to("m81_stack.fits")?;
let mut fits = FitsFile::open("m81_stack.fits")?;
for keyword in fits.get_header(0)?.keywords() {
match &keyword.value {
Some(value) => println!("{:<8} = {value}", keyword.name),
None => println!("{} {}", keyword.name, keyword.comment.as_deref().unwrap_or("")),
}
}
println!("checksums valid: {}", fits.validate_hdu_checksum(0)?.all_valid());
Ok(())
}
SIMPLE = T
BITPIX = -32
NAXIS = 2
NAXIS1 = 1600
NAXIS2 = 1200
EXTEND = T
COMMENT FITS (Flexible Image Transport System) format is defined in 'Astronomy
COMMENT and Astrophysics', volume 376, page 359; bibcode: 2001A&A...376..359H
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 = 6.93E-05
CD2_1 = 6.93E-05
CD2_2 = 0.00032604
LATPOLE = 69.0653
OBJECT = 'M81'
FILTER = 'L'
EXPTIME = 3600.0
DATE-OBS = '2026-03-20T03:15:00'
NCOMBINE = 12
DATASUM = '847500'
CHECKSUM = '36gXA3ZV33dVA3ZV'
checksums valid: true
The mandatory cards (SIMPLE through EXTEND) come from the data, so you
never set them. The WCS cards come from wcs.to_keywords(), which
Building a WCS in Code describes, and a keyword you set
with the same name as a WCS card replaces it. write_fits and write_to add
DATASUM and CHECKSUM, so a reader can check that the file arrived intact.
A compressed file gets them on the HDU that holds the compressed image.
The metadata setters write the keywords most capture and processing programs read:
| Setter | Keyword |
|---|---|
object | OBJECT |
telescope | TELESCOP |
instrument | INSTRUME |
observer | OBSERVER |
filter | FILTER |
exposure | EXPTIME, seconds |
temperature | CCD-TEMP, °C |
gain | GAIN |
binning | XBINNING and YBINNING |
date_obs | DATE-OBS |
date_obs writes the string you pass and doesn’t check it. Use the FITS form,
YYYY-MM-DDThh:mm:ss with optional fractional seconds, in UTC.
UTC::to_iso8601 produces that form, as Create and Format
Times shows. Any other card goes in through keyword or keywords.
write_to picks FITS or XISF from the extension. With .xisf, the keywords go
into the XISF file as FITS keywords, and the WCS is also written as XISF
astrometric solution properties. XISF Files covers that mapping.
Which sample types each method takes
AstroImage writes the buffer in its own type. Each format has its own list
of types it can store, so the method you call limits the element type of your
Vec:
| Method | Element types |
|---|---|
write_fits | u8, i8, i16, u16, i32, u32, i64, u64, f32, f64 |
write_xisf | u8, u16, u32, u64, f32, f64 |
write_to | u8, u16, u32, u64, f32, f64 |
write_to takes only the types both formats store, because it decides the
format at run time. FITS stores i8, u16, u32 and u64 as the integer
type of the same width with the other signedness, plus a BZERO offset, so
write_fits shifts each sample and writes BZERO for you. A Vec<u16> from
a camera driver comes back from Image::open as U16. Since write_fits
sets BZERO itself, a BZERO or BSCALE keyword you pass with one of these
types is an error. u64 samples can’t be tile-compressed.
A multi-channel buffer must be planar: every red sample, then every green,
then every blue, with dimensions of [width, height, 3]. That’s the order
both formats store. An Image holds RGB interleaved instead, so pick the type
that matches the order your buffer already has.
Write a camera frame with Image
Image takes any PixelData variant, including U16, and has the same
metadata setters as AstroImage:
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// One frame from the camera driver: 16-bit samples, row by row
let raw: Vec<u16> = vec![1000; 3008 * 3008];
let mut frame = Image::new(PixelData::U16(raw), [3008, 3008]);
frame
.object("NGC 7000")
.filter("Ha")
.exposure(300.0)
.temperature(-10.0)
.gain(100.0)
.binning(1, 1)
.date_obs("2026-08-14T03:21:07.250");
frame.save("light_0001.fits")?;
let back = Image::open("light_0001.fits")?;
println!("first sample: {:?}", back.pixels.as_u16().map(|p| p[0]));
for name in ["CCD-TEMP", "GAIN", "XBINNING"] {
println!("{name:<8} = {:?}", back.get(name).value());
}
Ok(())
}
first sample: Some(1000)
CCD-TEMP = Some(Real(-10.0))
GAIN = Some(Real(100.0))
XBINNING = Some(Integer(1))
Image::save writes DATASUM and CHECKSUM cards, as write_fits does.
A file saved again gets fresh cards in place of the old ones.
To write a WCS into an Image, add the cards from wcs.to_keywords() with
set_keyword. Each WcsKeyword converts into a Keyword with From.
Compress the output
Both writers can tile-compress a FITS file. On AstroImage, call
.compressed(CompressionAlgorithm::Rice) before write_fits or write_to,
and optionally .tile_size(width, height). On Image, call
save_fits_compressed(path, algorithm, tile_size) instead of save. For
XISF, XisfWriter compresses data blocks. Tile
Compression and XISF Files cover both.
Where next
- Tile Compression: shrink 16-bit frames without losing a bit.
- FITS Files: what
BZEROandBSCALEdo to the values you write. - Building a WCS in Code: make the
Wcsyou pass to.wcs().
FITS Files
Image::open covers the common case: one image and its header. Some files
hold more than that. A survey frame can carry a science image, a variance map
and a mask. A .fits.fz file keeps its image in a binary table. A processing
pipeline might write a catalog table after the image. When you need to see
everything in a file, or check exactly what’s stored, you work with
FitsFile.
A file is a chain of HDUs
A FITS file is a sequence of header and data units (HDUs). Each one has a
header of 80-character cards and an optional block of data. The first is the
primary HDU, and the rest are extensions: images, ASCII tables or binary
tables. FitsFile scans the headers when it opens the file and reads data
only when you ask for it, so opening a large file is fast.
This walks the HDUs of mef.fits.fz, one of the test files in
celestial-images/test_data/compressed. It holds two tile-compressed images
after an empty primary HDU:
use celestial_images::fits::io::reader::FitsFile;
use celestial_images::formats::image::Image;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut fits = FitsFile::open("mef.fits.fz")?;
for index in 0..fits.num_hdus() {
let hdu = fits.read_hdu(index)?;
let header = hdu.header();
let name = header.get("EXTNAME").as_str().unwrap_or("-");
let checksums = fits.validate_hdu_checksum(index)?;
println!(
"HDU {index}: {:<16} {name:<4} checksums valid: {}",
format!("{:?}", hdu.logical_type()),
checksums.all_valid()
);
}
let img = Image::open("mef.fits.fz")?;
println!("Image::open read {}x{}, EXTNAME {:?}", img.width(), img.height(), img.get("EXTNAME").as_str());
Ok(())
}
HDU 0: Image - checksums valid: true
HDU 1: CompressedImage SCI checksums valid: true
HDU 2: CompressedImage FLT checksums valid: true
Image::open read 23x17, EXTNAME Some("SCI")
hdu_type() reports what the file stores, so HDUs 1 and 2 are BinaryTable.
logical_type() reports what the HDU means, so a binary table that holds a
compressed image reports CompressedImage. Image::open returned the first
HDU with pixels, the SCI image. The empty primary HDU has no pixels, so it
was skipped.
get_image_info and read_hdu_with_data reach the images after the first.
For a compressed HDU they read ZNAXISn and ZBITPIX, and
read_hdu_with_data decompresses the tiles:
use celestial_images::fits::io::reader::FitsFile;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut fits = FitsFile::open("mef.fits.fz")?;
let (dimensions, bitpix) = fits.get_image_info(2)?;
println!("FLT: {dimensions:?} {bitpix:?}");
let (_, flat) = fits.read_hdu_with_data::<f32>(2)?;
println!("{} samples, first {:?}", flat.len(), &flat[..3]);
Ok(())
}
FLT: [23, 17] F32
391 samples, first [NaN, 937.50757, 1024.8617]
validate_hdu_checksum recomputes the DATASUM and CHECKSUM cards of one
HDU. Each field of the result is None when the header has no such card,
Some(true) when it matches and Some(false) when it doesn’t. A changed data
unit fails both cards, since CHECKSUM covers the data too.
If the scan hits a malformed header partway through the file, open still
succeeds. The HDUs before the problem stay readable, and scan_error()
returns what went wrong. That way one damaged extension doesn’t cost you the
image in front of it.
Headers and keywords
get_header(index) returns a Header, and get and get_last on it work as
they do on Image. Each card is a Keyword with three public fields:
name, value and comment. value is None for commentary cards such as
HISTORY and COMMENT, whose text is in comment. The value types are
Logical, Integer, Real, String and Complex.
Two conventions extend the 80-character card, and the crate reads and writes both:
- Long strings. A string value longer than one card continues on
CONTINUEcards. You get the whole string back as one value. - Long names. A keyword name longer than 8 characters, or one with
characters FITS doesn’t allow, is stored as
HIERARCH name = value. A lookup of"ESO DET DIT"findsHIERARCH ESO DET DIT, andset_keywordwith a long name writes theHIERARCHform.
Data types, BZERO and BSCALE
FITS stores integers as signed values only, with one exception for 8-bit
data. A camera’s unsigned 16-bit frame can’t be stored as it is, so writers
subtract 32768 from every sample and record BZERO = 32768. A reader adds it
back. Image does this in both directions:
use celestial_images::fits::io::reader::FitsFile;
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A 16-bit camera frame: unsigned samples from 0 to 65535
let frame = Image::new(PixelData::U16(vec![0, 1000, 32768, 65535]), [2, 2]);
frame.save("frame.fits")?;
let mut fits = FitsFile::open("frame.fits")?;
let header = fits.get_header(0)?;
println!("BITPIX = {:?}", header.get("BITPIX").as_i64());
println!("BZERO = {:?}", header.get("BZERO").as_f64());
let (_, stored) = fits.read_hdu_with_data::<i16>(0)?;
println!("stored: {stored:?}");
let back = Image::open("frame.fits")?;
println!("Image has: {:?}", back.pixels);
Ok(())
}
BITPIX = Some(16)
BZERO = Some(32768.0)
stored: [-32768, -31768, 0, 32767]
Image has: U16([0, 1000, 32768, 65535])
read_hdu_with_data::<T> returns the values as stored, with no scaling. The
type parameter must match BITPIX, or ZBITPIX for a compressed image: u8
for 8, i16 for 16, i32 for 32, i64 for 64, f32 for -32 and f64 for
-64. A type that doesn’t match is an error. It’s the right tool when you
want to see exactly what’s in the file. Image::open applies the scaling and
picks the PixelData variant from BITPIX, BZERO and BSCALE:
BITPIX | Scaling in the header | PixelData |
|---|---|---|
| 8 | none | U8 |
| 8 | BZERO = -128 | I8 |
| 16 | none | I16 |
| 16 | BZERO = 32768 | U16 |
| 32 | none | I32 |
| 32 | BZERO = 2147483648 | U32 |
| 64 | none | I64 |
| 64 | BZERO = 9223372036854775808 | U64 |
| -32 | none | F32 |
| -64 | none | F64 |
| any | any other BZERO or BSCALE | F64 |
“None” means BSCALE = 1 and BZERO = 0, or no scaling cards at all. The
offsets in the table each shift a signed type onto the unsigned type of the
same width, so the samples keep their size in memory.
Any other scaling turns the stored values into physical values,
BZERO + BSCALE × stored, and those need a float type:
use celestial_images::fits::header::keywords::Keyword;
use celestial_images::fits::io::reader::FitsFile;
use celestial_images::formats::astro_image::AstroImage;
use celestial_images::formats::image::Image;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Stored bytes whose physical value is BZERO + BSCALE * stored
let stored = vec![0u8, 1, 2, 255];
AstroImage::new(&stored, [4])
.keyword(Keyword::real("BSCALE", 0.5))
.keyword(Keyword::real("BZERO", -10.0))
.write_fits("scaled.fits")?;
let img = Image::open("scaled.fits")?;
println!("{:?}", img.pixels);
println!("BSCALE card kept: {}", img.get("BSCALE").exists());
img.save("resaved.fits")?;
let mut fits = FitsFile::open("resaved.fits")?;
println!("resaved BITPIX = {:?}", fits.get_header(0)?.get("BITPIX").as_i64());
Ok(())
}
F64([-10.0, -9.5, -9.0, 117.5])
BSCALE card kept: false
resaved BITPIX = Some(-64)
The Image drops BSCALE and BZERO from its keywords, because its pixels
already hold physical values. Keeping the cards would apply the scaling a
second time on the next save. The cost shows when you save: the file is
written as 64-bit floats, eight times the size of the 8-bit original. To keep
the original encoding, write the stored values with AstroImage and set the
scaling cards yourself.
Undefined pixels and BLANK
An integer image marks pixels with no measurement, such as dead columns or
saturated regions, by setting them to the value of the BLANK card. When
Image::open scales such an image to F64, those pixels become NaN. When it
keeps an integer type, they keep their stored value and the BLANK card stays
in keywords, converted to the in-memory value. normalize, stf and
mad_normalized treat them as NaN, so a BLANK of -32768 doesn’t become the
black point of your stretch. Float images mark undefined pixels with NaN and have no
BLANK card.
Tables and random groups
read_hdu returns Hdu::AsciiTable or Hdu::BinaryTable for table
extensions. Both table types have all_column_info, column_by_name,
get_row, get_column_values and iter_rows, which return cells as
TableValue, with TSCALn and TZEROn applied. Binary tables can hold
variable-length arrays, and the crate reads them from the heap. These methods
take a reader as an argument: open the same file with std::fs::File::open
and pass it in. A primary HDU of random groups, an old format from radio
interferometry, comes back as Hdu::RandomGroups, and read_groups returns
its groups.
What’s supported
| Feature | Read | Write |
|---|---|---|
Primary and IMAGE extension HDUs | yes | primary HDU only |
| Several image HDUs in one file | yes | no |
| ASCII and binary tables | yes | no |
| Random groups | yes | no |
CHECKSUM and DATASUM | yes | yes |
CONTINUE long strings, HIERARCH | yes | yes |
| Tile compression: Rice, GZIP 1 and 2 | yes | yes |
| Tile compression: HCOMPRESS, PLIO | no | no |
The writers produce one image per file: a primary HDU, or an empty primary HDU
followed by one compressed image. Image::open returns only the first image
HDU. FitsFile::read_hdu_with_data reads any image HDU, compressed or not, as
stored values without BZERO or BSCALE applied. Tile
Compression covers what each codec supports.
Where next
- Tile Compression: Rice and GZIP tiles, and the tradeoffs between them.
- Pixels and Sky Coordinates: turn the WCS cards in a header into sky positions.
- XISF Files: the other format
Imagereads and writes.
Tile Compression
A night of 16-bit frames from a 26-megapixel camera fills tens of gigabytes,
and most of each frame is sky background that varies by a few counts. Tile
compression shrinks those files without changing a single pixel, and the
result is still a FITS file that astropy, cfitsio and most capture and
processing programs read. Files compressed this way usually end in .fits.fz,
the extension the fpack tool gives them.
Here’s a 1024 x 1024 frame with a sky background near 1000 counts and a few counts of noise, saved four ways:
use celestial_images::fits::compression::CompressionAlgorithm;
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;
// A 1024 x 1024 frame: a sky background near 1000 ADU with a little noise.
fn sky_frame() -> Image {
let mut state = 12345u32;
let samples: Vec<u16> = (0..1024 * 1024)
.map(|_| {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1000 + (state >> 27) as u16
})
.collect();
Image::new(PixelData::U16(samples), [1024, 1024])
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let frame = sky_frame();
frame.save("sky.fits")?;
frame.save_fits_compressed("sky_rice.fits", CompressionAlgorithm::Rice, None)?;
frame.save_fits_compressed("sky_gzip.fits", CompressionAlgorithm::Gzip, None)?;
frame.save_fits_compressed("sky_gzip2.fits", CompressionAlgorithm::Gzip2, None)?;
for name in ["sky.fits", "sky_rice.fits", "sky_gzip.fits", "sky_gzip2.fits"] {
let bytes = std::fs::metadata(name)?.len();
let same = Image::open(name)?.pixels.as_u16() == frame.pixels.as_u16();
println!("{name:<15} {:>9} bytes, pixels match: {same}", bytes);
}
Ok(())
}
sky.fits 2102400 bytes, pixels match: true
sky_rice.fits 803520 bytes, pixels match: true
sky_gzip.fits 1056960 bytes, pixels match: true
sky_gzip2.fits 961920 bytes, pixels match: true
Rice brought the frame to 38% of its size, and every pixel came back. The
noise in a real frame sets how far it shrinks: each bit of noise per pixel is
a bit Rice has to keep. Image::open reads a compressed file like any other,
so code that reads your frames doesn’t change. AstroImage compresses with
.compressed(algorithm), as Write a New Image shows.
How it works
The compressed file holds an empty primary HDU, then a binary table. The
image is cut into tiles, and each tile is compressed on its own into one row
of the table. Your header keywords are copied into the table’s header, next
to Z keywords such as ZBITPIX and ZNAXIS1 that describe the original
image. A reader that understands the convention rebuilds the image. One that
doesn’t still sees a valid FITS file with a table in it.
Because tiles are independent, a reader can decompress part of an image
without the rest. This crate always decompresses the whole image, so the tile
shape matters only to other programs that read your files. By default each
tile is one row of the image. Pass a tile
size to save_fits_compressed or AstroImage::tile_size for rectangular
tiles. Tiles at the right and bottom edges are cut short when the size doesn’t
divide the image.
Choose an algorithm
Rice(RICE_1) codes the difference between neighboring pixels, which is small in astronomical images. It’s the fastest and usually the smallest for integer data, and it’s whatfpackuses by default. It takes 8, 16 and 32-bit integers only.Gzip(GZIP_1) runs deflate on each tile. It takes any pixel type.Gzip2(GZIP_2) shuffles the bytes of each tile first, putting all the most significant bytes together, then runs deflate. It compresses multi-byte pixels better thanGzip, and it’s the better choice for float images.
For a float image, Rice isn’t an option, and the two GZIP variants are lossless:
use celestial_images::fits::compression::CompressionAlgorithm;
use celestial_images::formats::image::Image;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut stack = Image::open("cygnus.fit")?;
// Its 4174 HISTORY cards would add 340 KB to every file below
stack.remove_keyword("HISTORY");
stack.save("stack.fits")?;
stack.save_fits_compressed("stack_gzip.fits", CompressionAlgorithm::Gzip, None)?;
stack.save_fits_compressed("stack_gzip2.fits", CompressionAlgorithm::Gzip2, None)?;
for name in ["stack.fits", "stack_gzip.fits", "stack_gzip2.fits"] {
let bytes = std::fs::metadata(name)?.len();
let same = Image::open(name)?.pixels.as_f32() == stack.pixels.as_f32();
println!("{name:<17} {bytes:>8} bytes, pixels match: {same}");
}
Ok(())
}
stack.fits 1059840 bytes, pixels match: true
stack_gzip.fits 947520 bytes, pixels match: true
stack_gzip2.fits 815040 bytes, pixels match: true
Float data compresses poorly without loss, because the low bits of each value
are noise. fpack gets much smaller float files by quantizing them: it rounds
each value to a fraction of the noise and Rice-codes the integers. The crate
reads those files, with or without dithering, but doesn’t write them, since
quantization changes your pixel values. When you need smaller float files, the
tradeoff is yours to make with fpack.
Limits
The writer refuses combinations it can’t store and tells you what to use instead. The reader reports codecs it doesn’t support:
use celestial_images::fits::compression::CompressionAlgorithm;
use celestial_images::formats::image::Image;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let stack = Image::open("cygnus.fit")?;
if let Err(e) = stack.save_fits_compressed("stack_rice.fits", CompressionAlgorithm::Rice, None) {
println!("{e}");
}
if let Err(e) = Image::open("hcompress_i16.fits.fz") {
println!("{e}");
}
Ok(())
}
FITS error: Unsupported compression: RICE_1 tiles cannot hold floating-point pixels without lossy quantization, which is not written; use GZIP_1 or GZIP_2
FITS error: Unsupported compression: HCOMPRESS_1 tiles cannot be read
| Codec | Read | Write |
|---|---|---|
RICE_1 | yes | 8, 16 and 32-bit integers |
GZIP_1, GZIP_2 | yes | every type except U64 |
NOCOMPRESS | yes | no |
| Quantized floats | yes | no |
HCOMPRESS_1, PLIO_1 | no | no |
Unsigned 64-bit images aren’t written compressed with any codec, because other FITS readers don’t decode those tiles to the same values. Save them uncompressed.
Image::open decompresses only the first image in a file. A file with several
compressed images, such as mef.fits.fz in FITS Files, gives you
the first one through Image, and the rest through
FitsFile::read_hdu_with_data.
Image::save picks the format from the extension, and .fz isn’t one it
knows. Save compressed files with save_fits_compressed, which takes any path.
Image::open recognizes a .fits.fz file from its first bytes.
Where next
- FITS Files: HDUs, header keywords and how
BZEROmaps to pixel types. - XISF Files: XISF compresses its data blocks with LZ4 or zlib.
XISF Files
XISF (Extensible Image Serialization Format) is the format many astrophotography processing tools save stacks and processed images in. A file starts with an XML header that describes each image, followed by the pixel data in binary blocks. The XML can hold FITS keywords, so a header read from FITS carries over, and typed properties: named values such as strings, numbers, vectors and matrices, which FITS cards can’t express.
Pleiades Astrophoto created XISF for PixInsight, and publishes the XISF 1.0 specification that the reader and writer follow.
Image::open and Image::save read and write XISF the same way they do FITS,
and Open and Save Images covers that path. This page is
about XisfFile and XisfWriter, which you need for properties, compression,
checksums and files with more than one image.
Write and read a file
XisfWriter takes images, keywords and properties, and writes them when you
call write:
use celestial_images::fits::header::keywords::Keyword;
use celestial_images::formats::image::Image;
use celestial_images::xisf::header::compression::XisfCompression;
use celestial_images::xisf::header::property::XisfProperty;
use celestial_images::xisf::reader::XisfFile;
use celestial_images::xisf::writer::XisfWriter;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A 4 x 2 RGB image, planar: all red samples, then green, then blue
let planar: Vec<f32> = [[0.1f32; 8], [0.2; 8], [0.3; 8]].concat();
let mut writer = XisfWriter::create("m42.xisf")?
.compression(XisfCompression::Lz4)
.sha1_checksums(true);
writer.add_image(&planar, 4, 2, 3)?;
writer.add_keyword(Keyword::string("OBJECT", "M42"));
writer.add_keyword(Keyword::real("EXPTIME", 120.0).with_comment("seconds"));
writer.add_property(XisfProperty::string(
"Observation:Object:Name",
"Orion Nebula",
));
writer.add_property(XisfProperty::float64("Instrument:ExposureTime", 120.0));
writer.write()?;
let mut xisf = XisfFile::open("m42.xisf")?;
let info = xisf.image_info(0).ok_or("no image")?;
println!(
"{:?} {:?} {:?}",
info.geometry, info.sample_format, info.color_space
);
println!("EXPTIME = {:?}", xisf.get("EXPTIME").as_f64());
for property in xisf.properties(0)? {
println!("{} = {:?}", property.id, property.value);
}
let samples = xisf.read_image_data_typed::<f32>(0)?;
println!("XisfFile: {:?}", &samples[..3]);
let img = Image::open("m42.xisf")?;
println!(
"Image: {:?}",
&img.pixels.as_f32().ok_or("not f32")?[..3]
);
Ok(())
}
[4, 2, 3] Float32 Rgb
EXPTIME = Some(120.0)
Observation:Object:Name = String("Orion Nebula")
Instrument:ExposureTime = Float64(120.0)
XisfFile: [0.1, 0.1, 0.1]
Image: [0.1, 0.2, 0.3]
The last two lines show the one difference between the two readers.
XisfFile returns samples planar, the way the writer took them, so the first
three are all red. Image interleaves RGB, so its first three samples are the
red, green and blue of the first pixel.
add_image takes the width, height and channel count, and sets the color
space from the channel count: three channels are RGB and anything else is
gray. read_image_data_typed::<T> must ask for the stored sample type, and
returns an error naming both types when it doesn’t. read_image_data_raw
returns the little-endian bytes instead.
Keywords and properties
Keywords and properties do overlapping jobs. Keywords are FITS cards, so any
program that reads FITS headers understands them, and they survive a
conversion to FITS. Properties have types and namespaced names such as
Instrument:ExposureTime, and their values can be vectors and matrices. Use
keywords for anything a FITS reader should see, and properties for values that
have no FITS form.
On the reading side, get and keywords() return the keywords of the first
image, and image_keywords(index) those of any other. properties(index)
returns the properties of one image, with vector and matrix values read from
their data blocks. On the writing side, keywords and properties attach to the
first image. set_keyword replaces a keyword of the same name, and
add_keyword appends one.
The reader decodes six property types into values: String, Boolean,
Int32, Float64, F64Vector and F64Matrix. The other types in the
specification are kept without decoding:
- A scalar, complex or
TimePointproperty, such asUInt16,Float32orComplex64, is anXisfPropertyValue::Otherthat holds its type name and the text of itsvalueattribute. - A vector or matrix of another element type, such as
I32VectororF32Matrix, is anXisfPropertyValue::OtherArraythat holds its type name, its dimensions and its elements as little-endian bytes.
The writer writes both back as they were read, and refuses a type name the specification doesn’t define or array data that doesn’t match its dimensions. Data blocks of properties may be compressed with zlib or LZ4, as image blocks are.
A data block that lies past the end of the file, fails its checksum or
doesn’t decompress makes properties return an error, because the header
says the data exists. A property the reader can’t interpret is left out of
the list without an error: one with a type the specification doesn’t define,
malformed attributes, a block in another file or a zstd block.
Data types and compression
XISF stores unsigned integers and floats: UInt8, UInt16, UInt32,
UInt64, Float32 and Float64. The writer takes slices of the matching
Rust types, u8 through f64. There are no signed integer samples, so an
i16 image from FITS needs converting first, as Open and Save
Images shows.
compression sets how the writer stores each data block: Lz4, Lz4Hc or
Zlib. LZ4 is fast to read and write, and zlib gives smaller files that take
longer to read. Lz4Hc writes the same blocks as Lz4, labeled as LZ4HC,
because the LZ4 encoder the crate uses has no high-compression mode. A block
that doesn’t get smaller is stored uncompressed. The reader also decodes
byte-shuffled blocks, which other programs write, but Zstd is not supported
in either direction.
Image::save writes XISF without compression. Use XisfWriter when you want
it.
sha1_checksums(true) adds a SHA-1 digest to every data block. The reader
checks SHA-1, SHA-256 and SHA-512 digests when it reads a block, and a block
that fails is an error.
The astrometric solution
A plate-solved XISF image can describe its WCS twice: as the FITS WCS
keywords, and as a set of astrometric solution properties with ids that start
with PCL:AstrometricSolution:. The crate keeps the two in agreement in both
directions.
When you write an image with a WCS, through AstroImage with .wcs() or
Image::save on an image with WCS keywords, the writer adds the solution
properties derived from the keywords:
use celestial_images::formats::astro_image::AstroImage;
use celestial_images::xisf::header::property::XisfPropertyValue;
use celestial_images::xisf::reader::XisfFile;
use celestial_wcs::builder::WcsBuilder;
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.3333e-4, 0.0], [0.0, 3.3333e-4]])
.projection(Projection::tan())
.build()?;
let pixels = vec![0.0f32; 1600 * 1200];
AstroImage::new(&pixels, [1600, 1200])
.wcs(&wcs)
.write_to("m81.xisf")?;
let mut xisf = XisfFile::open("m81.xisf")?;
println!("CRPIX1 keyword = {:?}", xisf.get("CRPIX1").as_f64());
for property in xisf.properties(0)? {
let id = property.id.trim_start_matches("PCL:AstrometricSolution:");
match property.value {
XisfPropertyValue::String(text) => println!("{id} = {text}"),
XisfPropertyValue::F64Vector(v) => println!("{id} = {v:?}"),
XisfPropertyValue::F64Matrix { data, .. } => println!("{id} = {data:?}"),
other => println!("{id} = {other:?}"),
}
}
Ok(())
}
CRPIX1 keyword = Some(800.5)
ProjectionSystem = Gnomonic
ReferenceCelestialCoordinates = [148.8882, 69.0653]
ReferenceImageCoordinates = [800.0, 600.0]
LinearTransformationMatrix = [-0.00033333, 0.0, 0.0, 0.00033333]
ReferenceNativeCoordinates = [0.0, 90.0]
CelestialPoleNativeCoordinates = [180.0, 69.0653]
The properties map onto FITS WCS keywords this way:
| Property | FITS keywords |
|---|---|
ProjectionSystem | the projection code in CTYPEi |
ReferenceCelestialCoordinates | CRVAL1, CRVAL2 |
ReferenceImageCoordinates | CRPIX1 - 0.5, CRPIX2 - 0.5 |
LinearTransformationMatrix | CD1_1, CD1_2, CD2_1, CD2_2 |
ReferenceNativeCoordinates | PV1_1, PV1_2 |
CelestialPoleNativeCoordinates | LONPOLE, LATPOLE |
ReferenceImageCoordinates is half a pixel less than CRPIX because the two
formats count pixels differently. FITS puts the center of the first pixel at
1, and XISF puts it at 0.5. The native reference and pole come from the
projection, so a cylindrical projection such as CAR gets (0, 0) where the
zenithal TAN above gets (0, 90).
Reading works the other way. When an XISF file has the solution properties
and no WCS keywords, Image::open turns the properties into keywords, so the
WCS code in Pixels and Sky Coordinates and the
plate solver read it the same as a FITS header:
use celestial_images::formats::image::Image;
use celestial_images::xisf::header::property::XisfProperty;
use celestial_images::xisf::writer::XisfWriter;
const SOLUTION: &str = "PCL:AstrometricSolution";
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A file whose solution is stored only as properties
let mut writer = XisfWriter::create("solved.xisf")?;
writer.add_image(&vec![0u16; 1600 * 1200], 1600, 1200, 1)?;
writer.add_properties([
XisfProperty::string(format!("{SOLUTION}:ProjectionSystem"), "Gnomonic"),
XisfProperty::f64_vector(
format!("{SOLUTION}:ReferenceCelestialCoordinates"),
vec![148.8882, 69.0653],
),
XisfProperty::f64_vector(
format!("{SOLUTION}:ReferenceImageCoordinates"),
vec![800.0, 600.0],
),
XisfProperty::f64_matrix(
format!("{SOLUTION}:LinearTransformationMatrix"),
2,
2,
vec![-3.3333e-4, 0.0, 0.0, 3.3333e-4],
),
]);
writer.write()?;
let img = Image::open("solved.xisf")?;
for keyword in &img.keywords {
println!("{:<6} = {:?}", keyword.name, keyword.value);
}
println!("properties left: {}", img.xisf_properties.len());
Ok(())
}
CTYPE1 = Some(String("RA---TAN"))
CTYPE2 = Some(String("DEC--TAN"))
CRPIX1 = Some(Real(800.5))
CRPIX2 = Some(Real(600.5))
CRVAL1 = Some(Real(148.8882))
CRVAL2 = Some(Real(69.0653))
CD1_1 = Some(Real(-0.00033333))
CD1_2 = Some(Real(0.0))
CD2_1 = Some(Real(0.0))
CD2_2 = Some(Real(0.00033333))
properties left: 0
The Image keeps one copy of the solution, as keywords, and drops the
properties, so an edit to the keywords can’t leave a stale solution behind.
The next save writes fresh properties from the keywords. When a file has
both, the keywords win.
The mapping has limits, set by what the properties can say:
- The XISF specification names seven projections:
TAN,SIN,STG,ZEA,CAR,MERandAIT. A WCS with any other projection, or with projection parameters, is written as keywords only. - The properties hold equatorial coordinates in the ICRS. A header with
RADESYS = 'FK5'at equinox 2000 is accepted, since the two frames differ by tens of milliarcseconds. Other systems, such as galactic coordinates or FK4, are written as keywords only, so they aren’t mislabeled. - SIP and TPV distortion terms have no property form. The properties describe the linear solution, and the keywords keep the distortion.
Distortion: SIP and TPV explains the distortion keywords, and Projections the projection codes.
Limits
- One image through
Image.Image::openreads the first image of the file. UseXisfFilewithnum_imagesand an index for the rest. The writer attaches keywords and properties to the first image only. - Monolithic files only. A file whose header points to data in other files, or a header stored on its own, can’t be read.
- Float bounds. XISF records a range,
bounds, for each image. For float images,add_imageandImage::saverecord the minimum and maximum sample value, which some programs use to rescale the image when they open it. If your floats are already in [0, 1] and you want them shown that way, write withXisfWriter::add_image_with_bounds(..., (0.0, 1.0)). The reader ignoresboundsand returns the stored values. - Properties on a round trip.
Image::openkeeps every property it can interpret, andImage::savewrites them back. A property left out of the list, as described under Keywords and properties, is lost.
Where next
- Open and Save Images: the format-agnostic
Imagetype. - Pixels and Sky Coordinates: read the WCS from an
Image, whichever format it came from. - Hints and Image Metadata: what the plate solver reads from an image header.
Debayering
A one-shot color camera has a single sensor with a grid of color filters over it, one filter per pixel. Each pixel records only red, green or blue, so the raw frame is a mosaic: one number per pixel, arranged in a repeating 2 x 2 tile called a Bayer pattern. Debayering, or demosaicing, estimates the two missing colors at every pixel from its neighbors and turns the mosaic into an RGB image.
Most capture programs save the raw mosaic and leave debayering to the processing software, because calibration with darks and flats has to happen on the mosaic first. The crate debayers mosaics of every sample type, integer or float, with bilinear interpolation.
Debayer an image
Image::debayer takes the pattern and replaces the mono mosaic with an
interleaved RGB image of the same width and height. The pattern has to match
the sensor, and the example shows what a wrong one does to a mosaic of an
evenly lit target:
use celestial_images::debayer::BayerPattern;
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;
// A 4 x 4 RGGB mosaic of an evenly lit target:
// red sites read 600, green sites 1000, blue sites 400.
fn mosaic() -> Image {
let mut raw = Vec::new();
for y in 0..4 {
for x in 0..4 {
raw.push(match (x % 2, y % 2) {
(0, 0) => 600u16,
(1, 1) => 400,
_ => 1000,
});
}
}
Image::new(PixelData::U16(raw), [4, 4])
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
for pattern in [BayerPattern::Rggb, BayerPattern::Bggr, BayerPattern::Grbg] {
let mut img = mosaic();
img.debayer(pattern)?;
// RGB samples are interleaved: R, G, B of pixel 0, then pixel 1, ...
let rgb = img.pixels.as_u16().ok_or("not u16")?;
let pixel = |x: usize, y: usize| &rgb[(y * 4 + x) * 3..][..3];
println!(
"{pattern:?}: {:?} {:?} {:?}",
img.dimensions,
pixel(1, 1),
pixel(2, 1)
);
}
Ok(())
}
Rggb: [4, 4, 3] [600, 1000, 400] [600, 1000, 400]
Bggr: [4, 4, 3] [400, 1000, 600] [400, 1000, 600]
Grbg: [4, 4, 3] [1000, 400, 1000] [1000, 500, 1000]
With the right pattern, every pixel comes out as the color the target
actually has. Bggr swaps red and blue, so the image is the right brightness
with the wrong hue. Grbg reads the green samples as red and blue, so the
whole image turns magenta, and the green channel changes from one pixel to the
next in a fine grid. If your first debayered image has either look, try
another pattern.
The pattern names the colors of the top-left 2 x 2 tile, read left to right
and then top to bottom. Rggb means red at (0, 0), green at (1, 0) and (0, 1),
and blue at (1, 1).
Get the pattern from the header
Capture programs record the pattern in a BAYERPAT keyword. The crate doesn’t
read it for you, so map it to a BayerPattern yourself:
use celestial_images::debayer::BayerPattern;
use celestial_images::fits::header::keywords::Keyword;
use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;
fn bayer_pattern(img: &Image) -> Option<BayerPattern> {
match img.get("BAYERPAT").as_str()? {
"RGGB" => Some(BayerPattern::Rggb),
"GRBG" => Some(BayerPattern::Grbg),
"GBRG" => Some(BayerPattern::Gbrg),
"BGGR" => Some(BayerPattern::Bggr),
_ => None,
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A raw frame from a one-shot color camera, as a capture program saves it
let mut raw = Image::new(PixelData::U16(vec![1000; 3008 * 3008]), [3008, 3008]);
raw.set_keyword(Keyword::string("BAYERPAT", "RGGB"));
raw.save("osc_light.fits")?;
let mut img = Image::open("osc_light.fits")?;
let pattern = bayer_pattern(&img).ok_or("no BAYERPAT, or one this code doesn't handle")?;
img.debayer(pattern)?;
println!("{pattern:?}: {} channels, {:?}", img.channels(), img.kind());
println!("BAYERPAT after debayer: {:?}", img.get("BAYERPAT").as_str());
img.save("osc_light_rgb.fits")?;
Ok(())
}
Rggb: 3 channels, Rgb
BAYERPAT after debayer: None
debayer removes BAYERPAT, XBAYROFF and YBAYROFF, because they describe
the mosaic and the pixels are RGB now. A program that opened the RGB file and
still found them might try to debayer it a second time.
Some capture programs also write ROWORDER = 'BOTTOM-UP', which means the
rows are stored bottom row first, or XBAYROFF and YBAYROFF, which shift
the pattern by a pixel. Either one changes which pattern describes the data
as stored. debayer doesn’t apply any of them, so adjust the pattern before
you pass it in: with the rows flipped, RGGB becomes GBRG.
Debayer SER frames
A color planetary capture stores the pattern in the SER header’s color_id,
and BayerPattern::from_color_id converts it. For captures deeper than 8 bits,
read_frame_u16 decodes each frame and debayer_bilinear_u16 debayers the
samples without building an Image:
use celestial_images::debayer::{debayer_bilinear_u16, BayerPattern};
use celestial_images::ser::header::SerHeader;
use celestial_images::ser::reader::SerReader;
use celestial_images::ser::types::ColorId;
use celestial_images::ser::writer::SerWriter;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// A short 12-bit capture from a color planetary camera
let header = SerHeader {
color_id: ColorId::BayerRggb,
image_width: 640,
image_height: 480,
pixel_depth_per_plane: 12,
..SerHeader::default()
};
let mut writer = SerWriter::create("saturn.ser", header)?;
for _ in 0..3 {
writer.write_frame(&vec![0u8; 640 * 480 * 2])?;
}
writer.finalize()?;
let reader = SerReader::open("saturn.ser")?;
let header = reader.header();
let (width, height) = (header.image_width as usize, header.image_height as usize);
let pattern = BayerPattern::from_color_id(header.color_id).ok_or("not a Bayer capture")?;
for id in 0..reader.frame_count() {
let raw = reader.read_frame_u16(id)?;
let rgb = debayer_bilinear_u16(&raw, width, height, pattern)?;
println!(
"frame {id}: {} mosaic samples -> {} RGB samples",
raw.len(),
rgb.len()
);
}
Ok(())
}
frame 0: 307200 mosaic samples -> 921600 RGB samples
frame 1: 307200 mosaic samples -> 921600 RGB samples
frame 2: 307200 mosaic samples -> 921600 RGB samples
debayer_bilinear_u8 does the same for 8-bit frames, which frame.data from
iter_frames gives you directly. Both functions return the RGB samples
interleaved, and return an error unless the slice holds exactly width × height samples and the mosaic is at least 2 x 2.
from_color_id returns None for the CMY patterns SER also defines, since
the crate debayers RGB filters only. SER Video Files covers
reading captures.
How bilinear interpolation works
At each pixel, the color the filter recorded is kept, and each missing color
is the mean of the nearest pixels that recorded it. A red site takes green
from its four horizontal and vertical neighbors and blue from its four
diagonal ones. A green site takes red and blue from its two neighbors on the
row or column where those colors sit. At the edges of the frame, the mosaic
is mirrored about its edge pixels: the missing neighbor at x = -1 is the pixel
at x = 1, which recorded the same color as the one at x = -1 would have.
Integer means are rounded down, toward negative infinity for signed types.
Float means are rounded to the sample type, and f32 means are taken in
f64 first.
Bilinear interpolation is fast, and with the parallel feature, on by
default, it debayers rows on all cores. Its weakness is fine detail: it
averages across edges, so sharp star profiles pick up colored fringes and the
image loses a little resolution. Methods that follow edges, such as VNG or
AHD, do better there, and the crate doesn’t have them. For stacking many
frames, where the fringes average out, bilinear is the usual choice.
Limits
Image::debayerworks on mono images of everyPixelDatavariant, with dimensions[width, height]or[width, height, 1]. An image with more than one channel, other axes, or fewer than 2 pixels on a side is anImageError::InvalidDimensionserror, and the image is left unchanged.- The four RGB patterns are supported. CMY sensors and X-Trans sensors, which use a 6 x 6 tile, aren’t.
Image::debayerdoesn’t readBAYERPAT,ROWORDER,XBAYROFForYBAYROFF. It removesBAYERPAT,XBAYROFFandYBAYROFF.
Where next
- Stretching for Display: make a linear RGB image visible on screen.
- SER Video Files: read and write planetary captures.
Stretching for Display
Open a stacked image and show its pixels as they are, and you get a black frame with a few white stars. The data is linear: brightness on the sensor maps straight to numbers, and the faint nebula you spent hours on is a hair above the sky background, in the bottom percent of the range. A stretch is a curve that lifts those faint values into the range a screen shows, while it keeps stars from turning into white blobs.
Stretch::stf picks that curve from the image’s own statistics, so it works
on any frame without tuning:
use celestial_images::formats::image::Image;
use celestial_images::stretch::{StfParams, Stretch};
fn median(mut values: Vec<f64>) -> f64 {
values.sort_by(f64::total_cmp);
values[values.len() / 2]
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("cygnus.fit")?;
println!("linear: median {:.4}", median(img.pixels.to_f64_normalized()));
let stretched = img.stf(&StfParams::default())?;
println!("stretched: median {:.4}", median(stretched.pixels.to_f64_normalized()));
let display = stretched.to_u8()?;
let bytes = display.pixels.as_u8().ok_or("not u8")?;
let levels = bytes.iter().map(|&b| f64::from(b)).collect();
println!("8-bit: median {} of 255", median(levels));
display.save("cygnus_display.fits")?;
Ok(())
}
linear: median 0.0078
stretched: median 0.2509
8-bit: median 64 of 255
The median pixel of this image is sky background, at 0.8% of full scale.
Shown linearly, it maps to level 2 of 255, which is black. After the stretch
the background is at a quarter of the range, where it’s a dark gray, and
the nebula above it becomes visible. stf returns a new Image of F64
values in [0, 1] and leaves the original alone, so you can keep measuring the
linear data. to_u8 converts that to 8-bit samples for a texture, a PNG with
the standard-formats feature, or a preview file.
The stretch is for looking at. It changes the pixel values in ways that photometry and astrometry can’t undo, so measure on the linear image.
How the curve is chosen
stf works on each channel by itself and does three things:
- It measures the channel’s median, which is the sky background in nearly every astronomical image, and its noise. The noise is the median absolute deviation (MAD) times 1.4826. For Gaussian noise that equals the standard deviation, and unlike the standard deviation it barely moves when the frame has bright stars and hot pixels.
- It sets a black point
shadow_clipnoise widths below the median, -2.8 by default. Everything darker turns black. That’s mostly noise, so the background stops looking grainy. - It applies a midtones transfer function, a curve that maps the black point
to 0, white to 1, and moves the background to
target_background, 0.25 by default. Values above the background are compressed smoothly, so stars keep some shape.
Both numbers are fields of StfParams. Raise target_background for a brighter
image that shows more faint detail and more noise:
use celestial_images::formats::image::Image;
use celestial_images::stretch::{StfParams, Stretch};
fn median(mut values: Vec<f64>) -> f64 {
values.sort_by(f64::total_cmp);
values[values.len() / 2]
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("cygnus.fit")?;
for target_background in [0.15, 0.25, 0.40] {
let params = StfParams {
target_background,
..StfParams::default()
};
let stretched = img.stf(¶ms)?;
println!(
"target {target_background:.2}: median {:.4}",
median(stretched.pixels.to_f64_normalized())
);
}
let clipped = StfParams {
shadow_clip: 0.5,
..StfParams::default()
};
if let Err(e) = img.stf(&clipped) {
println!("{e}");
}
Ok(())
}
target 0.15: median 0.1506
target 0.25: median 0.2509
target 0.40: median 0.4011
Invalid input: STF shadow_clip is a non-positive multiple of MADN (default -2.8), got 0.5
The median lands near the target, not exactly on it, because the curve is
fitted to the background before the black point clips it. A positive
shadow_clip would put the black point above the background and turn most of
the image black, so stf refuses it. A target_background outside [0, 1] is
refused too.
Color images
Each channel of an RGB image gets its own black point and curve. That removes a color cast in the background, such as the orange of light pollution, since every channel’s background lands on the same target. The cost is that the colors of objects aren’t preserved. Use the stretched image to judge framing, focus and gradients, and don’t read star colors from it.
Before you stretch
stf scales the pixels to [0, 1] first with to_f64_normalized, so an
integer image is divided by the range of its type, 65535 for a U16 frame,
and a float image outside [0, 1] is rescaled by its own minimum and maximum.
The statistics leave out NaN pixels and pixels equal to a BLANK card, so
dead regions don’t drag the median down. A channel with no usable pixels at
all is an error.
Debayer a one-shot color frame before you stretch it. Stretched as a mosaic, its red, green and blue sites share one curve, and the result shows the Bayer grid. Debayering covers that step.
Normalize by the noise for detection
mad_normalized uses the same median and noise for a different job. It
subtracts the background from each channel and divides by the noise, so every
value reads as “how many noise widths above the sky”. Values are clipped to
[-5, 100] so a few saturated stars don’t dominate:
use celestial_images::formats::image::Image;
use celestial_images::stretch::Stretch;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("cygnus.fit")?;
let normalized = img.mad_normalized()?;
let samples = normalized.pixels.as_f32().ok_or("not f32")?;
let above = samples.iter().filter(|&&v| v > 5.0).count();
println!(
"{above} of {} pixels are more than 5 sigma above the background",
samples.len()
);
Ok(())
}
1577 of 262144 pixels are more than 5 sigma above the background
One threshold then means the same thing on a bright frame and a dark one, which is what source detection wants.
Where next
- Debayering: turn a raw color mosaic into RGB before you stretch it.
- Open and Save Images: the
Imagetype these methods work on.
SER Video Files
Planetary and lunar imaging records thousands of short frames, then stacks
the sharpest ones. Capture programs save those frames as SER files: one
header, the raw frames back to back, and an optional trailer that holds a
timestamp for each frame. The ser module reads and writes this format.
Read the frames of a capture
use celestial_images::ser::reader::SerReader;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let reader = SerReader::open("jupiter.ser")?;
println!(
"{} frames of {}x{}",
reader.frame_count(),
reader.header().image_width,
reader.header().image_height
);
for frame in reader.iter_frames() {
let frame = frame?;
println!("frame {}: {} bytes, {:?}", frame.id, frame.data.len(), frame.timestamp);
}
Ok(())
}
SerReader memory-maps the file, so frame.data is a slice of the file’s
bytes and no frame is copied. frame.timestamp is None when the file has
no trailer. open checks that the file holds every frame the header
declares, so a file that is too short fails at open rather than at the
first frame read.
For a part of the capture, iter_frames_range(start, count) iterates over
count frames from start, and read_frame(id) returns one frame. Frames
with a pixel depth of 9 to 16 bits store two bytes per sample.
read_frame_u16 decodes them in the byte order the header gives.
Read a large capture quickly
A borrowed frame costs nothing when the file is already in the page cache.
When it isn’t, every page of the frame waits on its own page fault, and that
is far slower than the disk. On an internal SSD, reading a 15 GB capture
through the mapping took 19.6 s with one thread. Reading it with
read_frame_into took 2.3 s.
If you make several passes over a capture, or read it right after copying it off a camera, read frames into a buffer you own:
use celestial_images::ser::reader::SerReader;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let reader = SerReader::open("sun.ser")?;
let mut frame = vec![0u8; usize::try_from(reader.header().frame_size()?)?];
for id in 0..reader.frame_count() {
reader.read_frame_into(id, &mut frame)?;
// process `frame`
}
Ok(())
}
read_frame_into copies the frame with one positioned read, pread on
Linux and macOS, and the loop reuses one buffer. The buffer must be exactly
one frame long. The read still goes through the page cache, so a second
pass reads from memory.
To read a band of a frame, read_rows_into(id, rows, &mut buf) reads rows
rows.start..rows.end. A row is image_width * bytes_per_pixel() bytes.
read_frame_data, read_frame_u16 and read_timestamp read the same way.
Write a capture
SerWriter takes a header and then one frame at a time:
use celestial_images::ser::header::SerHeader;
use celestial_images::ser::timestamp::SerTimestamp;
use celestial_images::ser::types::ColorId;
use celestial_images::ser::writer::SerWriter;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let header = SerHeader {
color_id: ColorId::Mono,
image_width: 640,
image_height: 480,
pixel_depth_per_plane: 8,
..SerHeader::default()
};
let mut writer = SerWriter::create("capture.ser", header)?;
let frame = vec![0u8; 640 * 480];
let time = SerTimestamp::from_unix_seconds(1_776_801_600.0)?;
writer.write_frame_with_timestamp(&frame, Some(time))?;
writer.finalize()?;
Ok(())
}
The writer counts frames itself and ignores the header’s frame_count.
Each frame must be exactly one frame’s worth of bytes for the header’s
size, color format and pixel depth. Either every frame has a timestamp or
none does, because the trailer has one entry per frame.
finalize writes the header with the final frame count, then the
timestamp trailer. Call it and check its result. Dropping the writer
finalizes the file too, but a drop has no way to report an error.
flush_buffer updates the header without finalizing, so the file on disk
holds every frame written so far. The trailer is still written only by
finalize.
To buffer frames in memory before they go to disk,
SerWriter::with_buffer(path, header, megabytes) sets the buffer size. The
limit is 1024 MiB, because the buffer is allocated in full up front.
Timestamps
SER stores each timestamp as .NET ticks: 100 ns units since 0001-01-01, with
no leap seconds. SerTimestamp converts between ticks and Unix time
(from_unix, to_unix, from_unix_seconds, to_unix_seconds) and to and
from the library’s UTC type (from_celestial_time, to_utc).
to_utc returns an error for a time before 1960, where UTC starts. A
timestamp of zero ticks is 0001-01-01, so a capture program that writes zeros
when it has no clock produces timestamps that to_unix converts and to_utc
refuses.
Files that change while open
Because SerReader memory-maps the file, another program that changes the
file while the reader has it open affects the reader:
- If it truncates the file, the next read of a removed page through the
mapping makes the kernel stop the process with
SIGBUSon Linux and macOS. That read can be a new frame fromread_frame,frame_slice,frame_slicesoriter_frames, or a frame you already hold. Rust cannot turn this into an error.read_frame_into,read_rows_into,read_frame_data,read_frame_u16andread_timestampdon’t read through the mapping, so they return an I/O error instead. - If it writes over the file in place, nothing reports it. Frames from
read_frame,frame_slice,frame_slicesanditer_framesborrow the mapped file, so frames already returned change under you. The methods that copy into a buffer don’t change what they already returned. - If it replaces the file by renaming a new one over it, the reader is unaffected. It keeps reading the file it opened.
Open a SER file only after the capture program has finished writing it. If the file sits on a drive that may be unplugged while you read, use only the methods that copy, so a lost drive is an error and not a crash. To work on a file that may be rewritten in place, copy it first and open the copy.
Where next
- Debayering: turn the frames of a color capture into RGB.
- Stretching for Display: make a stacked result visible on screen.
Star Catalog
celestial-catalog searches a star catalog built from Gaia DR3 and
Hipparcos. The catalog is one file, and you search it by sky position.
The problem it solves
A plate solver, a pointing run and a finder chart all ask the same question: which stars are within this radius of this position, and how bright are they? Gaia DR3 can answer it, but the full release is 701 GB of compressed CSV in 3,386 files. Cut to magnitude 18.5 it’s still more than 419 million stars and 23 GB, far too much to load at startup. Most of those stars are faint ones along the Milky Way, which you’d throw away anyway.
The crate’s forge tool cuts the survey down to the brightest stars in
each patch of sky and writes them to one file, sorted by position. The
library memory-maps that file, so opening it reads a header and an index,
and a search reads only the patches of sky it touches. Opening the 6.2 GB
catalog reads 12.6 MB of it.
Here are the four stars brighter than magnitude 4 within a degree of the Pleiades:
use celestial_catalog::query::catalog::Catalog;
use celestial_catalog::query::cone::{cone_search, ConeSearchParams};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let catalog = Catalog::open("catalog-small.bin")?;
// The Pleiades: every star brighter than magnitude 4 within 1 degree.
let stars = cone_search(&catalog, &ConeSearchParams {
ra_deg: 56.75,
dec_deg: 24.1167,
radius_deg: 1.0,
max_mag: Some(4.0),
max_results: None,
epoch: None,
})?;
for s in &stars {
println!(
"{:>20} RA {:9.5}° Dec {:+9.5}° mag {:5.2} {:.3}° away",
s.star.source_id, s.ra_deg, s.dec_deg, s.star.mag, s.distance_deg
);
}
Ok(())
}
66714384142368256 RA 56.87125° Dec +24.10494° mag 2.85 0.111° away
65283232316451328 RA 56.45680° Dec +24.36754° mag 3.86 0.367° away
65271996684817280 RA 56.21900° Dec +24.11313° mag 3.70 0.485° away
66526127137440128 RA 57.29069° Dec +24.05321° mag 3.62 0.498° away
Those are Alcyone, Maia, Electra and Atlas, nearest first. The long numbers are Gaia DR3 source IDs. Positions are ICRS degrees at the catalog epoch, J2016.0, unless you ask for another date.
What you get
- Searches that read only what they need. The file is memory-mapped,
and
Catalog::stars_in_pixelhands back a slice that points into the map. Nothing is parsed per star, so a 1° search around the Trapezium returns 7,668 stars from the 6.2 GB file in under a millisecond once the pages are in memory. - Proper motion to your date. Give a search an epoch and it moves each star from J2016.0 to that date before it measures the distance. Barnard’s Star moves 107″ between 2016 and 2026, so this matters for nearby stars.
- Gaia’s quality flags. Each record says whether it has a proper motion and parallax, whether Gaia’s astrometry for it is suspect, and whether it came from Hipparcos. You can drop doubtful stars before you use them.
- Three ready-made sizes. Pre-built files run from 276 MB to 6.2 GB. You can download one and start searching without touching the survey data.
- Two command-line tools.
query-catalogsearches a file from the shell, andforgebuilds a new file from the survey data.
Limits
- The catalog is thinned in crowded regions. Each patch of sky keeps a fixed number of its brightest stars. Away from the Milky Way that’s often every star to magnitude 18.5. Along the galactic plane the cut can fall near magnitude 10 in the smallest file. Get a Catalog File has the numbers for each size.
- One magnitude, no colors. Each record has one magnitude: Gaia G, or Hipparcos Hp for stars brighter than about 7.5 that came from Hipparcos. There are no BP/RP colors and no radial velocities.
- A few bright stars appear twice. Gaia’s Hipparcos cross-match table
has no entry for some bright stars, and
forge mergepairs those by position and magnitude. About a dozen keep both records, within 2″ of each other, because their Hp and G differ by more than the pairing allows. Build a Catalog with forge gives the limits. - Catalog places only. A search returns ICRS positions. Aberration, precession and refraction, the steps that turn a catalog place into where the star appears, are celestial-coords’ job.
- A fixed file format. The library reads format version 2 files from
forge. You can’t add stars or columns to a file after it’s built.
If you need Gaia’s other columns, such as colors or radial velocities, query the Gaia archive directly. This file gives up those columns to run offline and fast.
Where to start
- To get a catalog file and pick a size, read Get a Catalog File.
- To search from the shell, read The query-catalog Command.
- To search from your own code, read Search the Catalog from Rust.
- To build a file yourself from Gaia DR3 and Hipparcos, read Build a Catalog with forge. Download a pre-built file first if you can: the build needs about 800 GB of disk.
- To understand how the file is laid out and what the size settings do, read How the Catalog File Works.
- For how the plate solver uses the catalog, and how each size did on real images, see The Star Catalog in the plate solving section.
Get a Catalog File
Every search needs a catalog file. Building one from the survey data means downloading 701 GB and needs about 800 GB of disk, so start with a pre-built file. This page covers downloading one, checking it, and picking the size that fits your work.
Download a pre-built file
The catalog folder on Dropbox has three files. All three hold stars down to magnitude 18.5, with positions at epoch J2016.0. They differ in how many stars each patch of sky keeps:
| File | HEALPix order | Stars per cell | Stars | Size |
|---|---|---|---|---|
catalog-small.bin | 6 | 100 | 4,915,200 | 276 MB |
catalog-standard.bin | 8 | 50 | 38,841,656 | 2.2 GB |
catalog-full.bin | 8 | 200 | 111,072,265 | 6.2 GB |
Put the file anywhere and pass its path to Catalog::open or to
query-catalog --catalog. Nothing else needs to be installed next to it.
The rest of this page explains the order and stars-per-cell columns, and
Choose a size says which file to pick.
Install the command-line tools
The forge and query-catalog binaries need the cli feature. From a
clone of the repository:
cargo install --path celestial-catalog --features cli
Or straight from GitHub, without a clone:
cargo install --git https://github.com/gaker/celestial celestial-catalog --features cli
Both commands install the two binaries into ~/.cargo/bin. The library
doesn’t need the cli feature, which adds clap, rayon, reqwest and other
dependencies that only the binaries use.
Check the file
query-catalog info opens the file and prints its header. Opening checks
the header and every entry in the index, so a truncated or damaged
download fails here:
query-catalog --catalog catalog-small.bin info
HEALPix order: 6
nside: 64
npix: 49152
Total stars: 4915200
Epoch: J2016.0
Magnitude limit: 18.50
Average stars per pixel: 100.0
File size: 276037696 bytes (263.25 MB)
The star count and file size should match the table above. “Pixel” and “cell” mean the same thing: one patch of sky in the HEALPix grid. The query-catalog Command covers searching.
Choose a size
Two numbers set a file’s size. The HEALPix order sets how finely the sky is cut into cells: order 6 makes 49,152 cells about 55′ across, and order 8 makes 786,432 cells about 13.7′ across. Stars per cell caps how many stars each cell keeps, the brightest first. How the Catalog File Works explains the tradeoff between them.
What the cap costs you is depth: in a crowded cell, the cap fills up before the magnitude limit does. This table shows the magnitude down to which each file keeps every star, measured over all of its cells:
| File | Half the sky | 90% of the sky | Everywhere |
|---|---|---|---|
catalog-small.bin | G 13.1 | G 11.7 | G 9.7 |
catalog-standard.bin | G 16.1 | G 14.0 | G 10.4 |
catalog-full.bin | G 18.5 | G 15.8 | G 12.1 |
Read the small file’s row as: in half the sky it keeps every star brighter than G 13.1, and nowhere does it drop a star brighter than G 9.7. The faintest values come from cells along the Milky Way, where all of a 55′ cell’s 100 brightest stars can be brighter than G 10.
When the small file is enough
- Bright stars. Any search for stars brighter than G 9.7 returns the same stars from all three files. Choosing alignment stars, listing targets for a pointing run or drawing a finder chart to that magnitude doesn’t need the larger downloads.
- Wide-field plate solving. A field about 1° across or more holds plenty of small-catalog stars to match. The solver’s tests solved every test image with the small file, from a 22′ × 17′ frame of M106 up to 4° fields. On M106, though, it matched only 10 stars, too few to fit distortion terms. The Star Catalog in the plate solving section has the results for each image and file.
- Limited disk or bandwidth. The small file is 276 MB, so it fits on a small computer at the mount.
When to use a larger file
- Narrow fields. Under about 1° across, use
catalog-standard.bin. Under about 20′, or in crowded fields along the Milky Way, usecatalog-full.bin. - Faint stars. If you need stars fainter than G 13 to G 14 over most of the sky, the small file doesn’t have them.
If you aren’t sure, start with the standard file.
Credit the data
The pre-built files are derived from:
- Gaia DR3: European Space Agency (ESA) mission Gaia, processed by the Gaia Data Processing and Analysis Consortium (DPAC). Gaia DR3 is licensed under CC BY 4.0. See the Gaia credit page for how to cite it.
- Hipparcos: the new reduction of the Hipparcos data (van Leeuwen 2007), matched to Gaia with the Gaia EDR3 Hipparcos2 best-neighbour table.
If you use a catalog file in published work, cite Gaia DR3 as ESA asks.
Next steps
- To search from the shell, read The query-catalog Command.
- To search from your own code, read Search the Catalog from Rust.
- To build a file with a different order, cap or magnitude limit, read Build a Catalog with forge.
The query-catalog Command
query-catalog searches a catalog file from the shell. Use it to check a
file you’ve downloaded, to look up the stars around a target, or to feed
a list of stars to a script as JSON or CSV.
Install it with the cli feature, as Get a Catalog
File shows. Every
invocation names the catalog first, then a subcommand:
query-catalog --catalog <path> <subcommand>
There are two subcommands: info prints the file’s header, and search
runs a cone search.
Print the header
query-catalog --catalog catalog-small.bin info
HEALPix order: 6
nside: 64
npix: 49152
Total stars: 4915200
Epoch: J2016.0
Magnitude limit: 18.50
Average stars per pixel: 100.0
File size: 276037696 bytes (263.25 MB)
npix is the number of HEALPix cells, 12 × nside², and the epoch is the
date of every position in the file. The standard and full files print
order 8 and 786,432 cells. How the Catalog File Works
explains the grid.
Search around a position
search takes a right ascension and a declination, then options. This is
every star brighter than magnitude 4 within half a degree of Alcyone, in
the Pleiades:
query-catalog --catalog catalog-small.bin search 3h47m24s +24d07m00s --radius 0.5 --mag-max 4
1: 66714384142368256 RA=3ʰ 47ᵐ 29.0992ˢ Dec=+24° 6' 17.7896" Mag= 2.85 Dist=0.0227° Source=HIPPARCOS
2: 66526127137440128 RA=3ʰ 49ᵐ 9.7653ˢ Dec=+24° 3' 11.5626" Mag= 3.62 Dist=0.4073° Source=GAIA
3: 65283232316451328 RA=3ʰ 45ᵐ 49.6310ˢ Dec=+24° 22' 3.1491" Mag= 3.86 Dist=0.4376° Source=GAIA
Total results: 3
Results come nearest first. Each row has the source ID, the position, the
magnitude, the distance from the search center and where the record came
from. Alcyone’s row says HIPPARCOS but carries a Gaia source ID. Gaia
has no 5- or 6-parameter astrometric solution for Alcyone, so the catalog
keeps the Hipparcos record and labels it with the Gaia ID. A Hipparcos
star with no Gaia match shows its HIP number negated, such as -17608.
RA and Dec take decimal degrees or sexagesimal. RA accepts 18h36m56s or
18:36:56, and Dec accepts +38d47m01s or -5:22:30.
Negative declinations
A declination such as -5:23:28 starts with a dash, so the argument
parser reads it as a flag and stops:
error: unexpected argument '-5' found
tip: to pass '-5' as a value, use '-- -5'
Put the options first and the position after --. Here are the three
stars nearest the Trapezium in Orion:
query-catalog --catalog catalog-small.bin search --radius 0.2 --limit 3 -- 5h35m17s -5:23:28
1: 3017364063331140224 RA=5ʰ 35ᵐ 16.7328ˢ Dec=-5° 23' 25.2252" Mag= 9.98 Dist=0.0014° Source=GAIA
2: 3017364063330718080 RA=5ʰ 35ᵐ 16.4687ˢ Dec=-5° 23' 22.9059" Mag= 4.96 Dist=0.0026° Source=GAIA
3: 3017364063330465152 RA=5ʰ 35ᵐ 17.2594ˢ Dec=-5° 23' 16.5645" Mag= 6.58 Dist=0.0034° Source=GAIA
Total results: 3
Move stars to a date
Positions in the file are at J2016.0. For a nearby star that’s a long
time: Barnard’s Star moves more than 10″ a year. --date moves every star
to 00:00 UTC on a calendar date before the search measures distances:
query-catalog --catalog catalog-small.bin search --radius 0.1 --mag-max 9 --date 2026-04-10 --raw 269.4485 4.7394
1: 4472832130942575872 RA=269.446208° Dec=+4.768985° Mag= 8.19 Dist=0.0297° Source=GAIA
Total results: 1
The search center is Barnard’s Star’s catalog place, and by 2026 the star
is 0.0297°, or 107″, away from it. --epoch does the same with a TT
Julian Date, such as --epoch 2461140.5. The two flags conflict, so pass
one or the other. --raw prints decimal degrees instead of sexagesimal.
Get JSON or CSV
--format json and --format csv print the same fields for a script to
read:
query-catalog --catalog catalog-small.bin search --radius 0.2 --limit 2 --format json -- 5h35m17s -5:23:28
[
{
"source_id": 3017364063331140224,
"ra_deg": 83.81971981441534,
"dec_deg": -5.3903403413178115,
"mag": 9.975762,
"distance_deg": 0.0013502099081598566,
"source": "GAIA"
},
{
"source_id": 3017364063330718080,
"ra_deg": 83.81861966629604,
"dec_deg": -5.389696084726389,
"mag": 4.9609604,
"distance_deg": 0.0026190410447155922,
"source": "GAIA"
}
]
query-catalog --catalog catalog-small.bin search --radius 0.2 --limit 2 --format csv -- 5h35m17s -5:23:28
source_id,ra_deg,dec_deg,mag,distance_deg,source
3017364063331140224,83.81971981441534,-5.3903403413178115,9.975762,0.0013502099081598566,GAIA
3017364063330718080,83.81861966629604,-5.389696084726389,4.9609604,0.0026190410447155922,GAIA
In both formats, ra_deg and dec_deg are the moved position when you
pass --date or --epoch.
Search options
| Flag | Default | Meaning |
|---|---|---|
--radius | 1.0 | Search radius in degrees |
--mag-max | none | Leave out stars fainter than this magnitude |
--limit | none | Return at most this many stars, nearest first |
--date | none | Move stars to 00:00 UTC on this YYYY-MM-DD date |
--epoch | none | Move stars to this TT Julian Date |
--format | table | table, json or csv |
--raw | off | Print decimal degrees in the table instead of sexagesimal |
--timing | off | Print how long the search took, to standard error |
--timing measures the search alone, not opening the file.
Next steps
- To run the same searches from your own code, read Search the Catalog from Rust.
- To understand why a crowded field returns fewer faint stars than you expect, read How the Catalog File Works.
Search the Catalog from Rust
Use this when your program needs the stars around a position: a target list, a finder chart, a check on a mount’s pointing, or your own matching code. The library needs no solver and no network, only a catalog file from Get a Catalog File.
Add the crate
[dependencies]
celestial-catalog = { git = "https://github.com/gaker/celestial" }
# Only for the proper-motion example, to turn a UTC time into TT.
celestial-time = { git = "https://github.com/gaker/celestial" }
The library doesn’t need the cli feature.
Open a file and run a cone search
use celestial_catalog::query::catalog::Catalog;
use celestial_catalog::query::cone::{cone_search, ConeSearchParams};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let catalog = Catalog::open("catalog-small.bin")?;
// The Pleiades: every star brighter than magnitude 4 within 1 degree.
let stars = cone_search(&catalog, &ConeSearchParams {
ra_deg: 56.75,
dec_deg: 24.1167,
radius_deg: 1.0,
max_mag: Some(4.0),
max_results: None,
epoch: None,
})?;
for s in &stars {
println!(
"{:>20} RA {:9.5}° Dec {:+9.5}° mag {:5.2} {:.3}° away",
s.star.source_id, s.ra_deg, s.dec_deg, s.star.mag, s.distance_deg
);
}
Ok(())
}
66714384142368256 RA 56.87125° Dec +24.10494° mag 2.85 0.111° away
65283232316451328 RA 56.45680° Dec +24.36754° mag 3.86 0.367° away
65271996684817280 RA 56.21900° Dec +24.11313° mag 3.70 0.485° away
66526127137440128 RA 57.29069° Dec +24.05321° mag 3.62 0.498° away
Catalog::open maps the file and checks its header and index, so a bad
file fails here instead of partway through a search. It reads no star
records. Keep one Catalog for the life of your program: every search
borrows it, and searches from several threads can share it.
cone_search returns a Vec<ConeSearchResult>, nearest first. Each
result has:
star, theStarRecordas stored in the file.ra_deganddec_deg, the position the search matched on. Without an epoch they’re the stored position.distance_deg, the distance from the search center.
max_mag drops fainter stars before sorting, and max_results keeps the
nearest ones after sorting. Leave both None to get every star in the
cone.
Read a star’s fields
A StarRecord holds the Gaia DR3 source ID, the position and proper
motion at the catalog epoch, the parallax, one magnitude and a set of
flags. The flags say which of the other fields you can trust:
use celestial_catalog::query::catalog::{
Catalog, StarRecord, FLAG_HAS_PARALLAX, FLAG_HAS_PROPER_MOTION, FLAG_RUWE_SUSPECT,
FLAG_SOURCE_HIPPARCOS,
};
use celestial_catalog::query::cone::{cone_search, ConeSearchParams};
fn describe(star: &StarRecord) -> String {
let id = if star.flags & FLAG_SOURCE_HIPPARCOS == 0 {
format!("Gaia DR3 {}", star.source_id)
} else if star.source_id < 0 {
format!("HIP {}", -star.source_id)
} else {
format!("Hipparcos, Gaia DR3 {}", star.source_id)
};
let motion = if star.flags & FLAG_HAS_PROPER_MOTION != 0 {
format!("pm {:+.1}, {:+.1} mas/yr", star.pmra, star.pmdec)
} else {
"no proper motion".to_string()
};
let parallax = if star.flags & FLAG_HAS_PARALLAX != 0 {
format!("parallax {:.2} mas", star.parallax)
} else {
"no parallax".to_string()
};
let ruwe = if star.flags & FLAG_RUWE_SUSPECT != 0 { ", RUWE > 1.4" } else { "" };
format!("{id}: mag {:.2}, {motion}, {parallax}{ruwe}", star.mag)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let catalog = Catalog::open("catalog-small.bin")?;
let stars = cone_search(&catalog, &ConeSearchParams {
ra_deg: 56.75,
dec_deg: 24.1167,
radius_deg: 1.0,
max_mag: Some(4.5),
max_results: None,
epoch: None,
})?;
for s in &stars {
println!("{}", describe(&s.star));
}
Ok(())
}
Hipparcos, Gaia DR3 66714384142368256: mag 2.85, pm +19.3, -43.7 mas/yr, parallax 8.09 mas
Gaia DR3 65205373152172032: mag 4.17, pm +13.1, -48.4 mas/yr, parallax 7.07 mas, RUWE > 1.4
Gaia DR3 65283232316451328: mag 3.86, pm +19.5, -45.5 mas/yr, parallax 7.67 mas, RUWE > 1.4
Gaia DR3 65271996684817280: mag 3.70, pm +20.5, -46.1 mas/yr, parallax 8.35 mas, RUWE > 1.4
Gaia DR3 66526127137440128: mag 3.62, pm +19.1, -46.2 mas/yr, parallax 8.12 mas, RUWE > 1.4
Gaia DR3 65296907494549120: mag 4.26, pm +16.3, -47.2 mas/yr, parallax 9.54 mas, RUWE > 1.4
Raising the limit to 4.5 brings in Merope and Taygeta, and shows three things about the records:
- Source IDs. A Gaia record has its Gaia DR3 source ID. A Hipparcos record has the Gaia ID of its cross-match when there is one, and its HIP number negated when there isn’t. Alcyone, the first line, is a Hipparcos record because Gaia has no proper motion or parallax for it.
- Stars without a cross-match. Gaia’s Hipparcos cross-match table has
no entry for Merope,
Gaia DR3 65205373152172032, or Taygeta,Gaia DR3 65296907494549120.forge mergepaired each Hipparcos record with the Gaia record 0.07″ or 0.13″ from it, and kept the Gaia record because each has a 5- or 6-parameter solution. A negative-ID record is a Hipparcos star that nothing paired, or one whose Gaia record has no proper motion. - Gaia’s bright stars are often flagged. All five Gaia records here have RUWE above 1.4, which says Gaia’s astrometric solution for them fits poorly. Check the flag before you use a bright Gaia star as a reference position.
pmra includes the cos(Dec) factor, as Gaia gives it, so it’s the motion
across the sky. A record without FLAG_HAS_PROPER_MOTION or
FLAG_HAS_PARALLAX stores zero in that field, which leaves the star in
place when you move it to an epoch.
These are all the flags, as constants in query::catalog:
| Flag | Set when |
|---|---|
FLAG_HAS_PROPER_MOTION | pmra and pmdec are measured |
FLAG_HAS_PARALLAX | parallax is measured |
FLAG_RUWE_SUSPECT | Gaia RUWE is above 1.4, so the astrometric solution may be poor |
FLAG_NO_5PARAM | Gaia has no 5-parameter solution: a 6-parameter one, or position only |
FLAG_BP_RP_EXCESS_SUSPECT | Gaia’s BP/RP flux excess is high, a sign of a blend or an extended source |
FLAG_SOURCE_HIPPARCOS | the record came from Hipparcos, and mag is Hp |
FLAG_5_OR_6_PARAM | Gaia has a 5- or 6-parameter solution |
FLAG_DUPLICATED_SOURCE | Gaia flagged the source as duplicated during its processing |
Move stars to your date
Every position in the file is at the catalog epoch, J2016.0 for the
pre-built files. Set epoch to a TT Julian Date and the search moves each
star to that date, using its proper motion and parallax, before it
measures distances:
use celestial_catalog::query::catalog::Catalog;
use celestial_catalog::query::cone::{cone_search, ConeSearchParams};
use celestial_time::scales::conversions::{ToTAI, ToTT};
use celestial_time::scales::utc::UTC;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let catalog = Catalog::open("catalog-small.bin")?;
// cone_search reads the epoch as TT.
let utc: UTC = "2026-04-10T14:00:00Z".parse()?;
let epoch = utc.to_tai()?.to_tt()?.to_julian_date();
// Barnard's Star, searched at its J2016.0 catalog position.
let stars = cone_search(&catalog, &ConeSearchParams {
ra_deg: 269.4485,
dec_deg: 4.7394,
radius_deg: 0.1,
max_mag: Some(9.0),
max_results: None,
epoch: Some(epoch),
})?;
for s in &stars {
println!("catalog: RA {:.6}° Dec {:+.6}°", s.star.ra, s.star.dec);
println!("2026: RA {:.6}° Dec {:+.6}°", s.ra_deg, s.dec_deg);
println!("{:.1}\" from the search center", s.distance_deg * 3600.0);
}
Ok(())
}
catalog: RA 269.448503° Dec +4.739420°
2026: RA 269.446207° Dec +4.768989°
106.8" from the search center
s.star keeps the stored J2016.0 place, and s.ra_deg and s.dec_deg
hold the moved one. The search matches on the moved place, so a star that
has moved out of the cone isn’t returned.
The catalog has no radial velocities, so the motion uses zero for them.
For Barnard’s Star, which has the largest proper motion of any star, that
leaves out about 0.07″ over these ten years. The
moved place is still an ICRS catalog place. To get where the star appears
from your site, pass it to celestial-coords, as Find the Altitude and
Azimuth of a Star does.
Moving a star costs more than reading it. A 1° search around the Trapezium returns 7,668 stars from the full file, and once the file’s pages were in memory it took 0.6 ms without an epoch and 3.6 ms with one.
Read a cell directly
A cone search is built on two lower-level calls. ang2pix_nest gives the
HEALPix cell that holds a position, and Catalog::stars_in_pixel returns
that cell’s stars as a slice into the file, brightest first:
use celestial_catalog::query::catalog::Catalog;
use celestial_catalog::query::healpix::ang2pix_nest;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let catalog = Catalog::open("catalog-small.bin")?;
let order = catalog.header().order;
// The pixel that holds the center of the Pleiades.
let pixel = ang2pix_nest(order, 56.75, 24.1167)?;
let stars = catalog.stars_in_pixel(pixel);
println!("pixel {pixel}: {} stars", stars.len());
if let (Some(first), Some(last)) = (stars.first(), stars.last()) {
println!("brightest mag {:.2}, faintest mag {:.2}", first.mag, last.mag);
}
Ok(())
}
pixel 463: 100 stars
brightest mag 3.70, faintest mag 12.65
This is the small file’s cap at work: the cell is 55′ across, and it keeps its 100 brightest stars, down to magnitude 12.65. Use the order from the file’s header, because the cell numbers depend on it. A pixel number past the end of the grid returns an empty slice.
Reading cells is useful when you want to walk the whole sky, such as
counting stars or building your own index. For anything shaped like a
circle, use cone_search, which works out the cells for you.
Read the header
Catalog::header returns the values forge wrote:
use celestial_catalog::query::catalog::Catalog;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let catalog = Catalog::open("catalog-small.bin")?;
let header = catalog.header();
println!("order {}, {} pixels", header.order, header.npix);
println!("{} stars to magnitude {}", header.total_stars, header.mag_limit);
println!("positions at J{:.1}", header.epoch);
println!("{} bytes", catalog.file_size());
Ok(())
}
order 6, 49152 pixels
4915200 stars to magnitude 18.5
positions at J2016.0
276037696 bytes
epoch is a Julian year. CatalogHeader also implements Display, which
prints the block that query-catalog info shows.
Handle errors
Every fallible call returns a CatalogError. Opening a file that isn’t
there gives an Io error with the path, and a search with an impossible
center gives InvalidInput:
use celestial_catalog::error::CatalogError;
use celestial_catalog::query::catalog::Catalog;
use celestial_catalog::query::cone::{cone_search, ConeSearchParams};
fn main() -> Result<(), Box<dyn std::error::Error>> {
match Catalog::open("missing.bin") {
Err(CatalogError::Io { context, source }) => println!("{context}: {source}"),
Err(e) => println!("{e}"),
Ok(_) => println!("opened"),
}
let catalog = Catalog::open("catalog-small.bin")?;
let result = cone_search(&catalog, &ConeSearchParams {
ra_deg: 10.0,
dec_deg: 95.0,
radius_deg: 1.0,
max_mag: None,
max_results: None,
epoch: None,
});
if let Err(e) = result {
println!("{e}");
}
Ok(())
}
Failed to open catalog file "missing.bin": No such file or directory (os error 2)
Invalid input: cone search: Dec 95 is outside [-90, 90] degrees
Catalog::open returns InvalidHeader for a file that isn’t a catalog,
is a version 1 file, or has the wrong length, and CorruptTable for a
damaged index. A search rejects a center or radius
that isn’t finite, a negative radius and an epoch that isn’t finite. Any
RA is accepted and reduced to [0°, 360°), and a radius over 180° searches
the whole sky.
Next steps
- To understand what the order and the cap mean for your searches, read How the Catalog File Works.
- To turn catalog places into altitude and azimuth, read From Catalog to Horizon.
- To plate-solve images against the catalog, start with Solve Your First Image.
Build a Catalog with forge
forge builds a catalog file from the Gaia DR3 and Hipparcos source
data. Use it when the pre-built files don’t fit: you
want a different magnitude limit, a different HEALPix order or cap, or a
catalog you built and checked yourself.
Before you start
The build is slow and needs a lot of disk, almost all of it for Gaia:
- The download is 701 GB in 3,386 compressed CSV files from ESA. At a steady 100 Mbit/s that’s about 16 hours.
- The build needs about 800 GB of disk: the 701 GB of source files,
plus about 75 GB of working files at magnitude 18.5. The Gaia ingest and
the merged file are 23.5 GB each, and
build-indexwrites a third file of that size while it sorts. - The Gaia ingest reads every byte of the 701 GB, decompressing and parsing about 1.8 billion rows. It uses every core by default.
Once the merged file exists, the last step is quick. Building each of the three pre-built files from it took 74 to 89 seconds on a 16-core Mac. You can try several orders and caps without repeating the slow steps.
The steps
Install forge with the cli feature, as Get a Catalog
File shows. The build
runs in five steps:
download-gaiafetches the Gaia DR3 source files.ingest-gaiareads them and keeps the stars brighter than a magnitude limit.ingest-hipparcosreads the Hipparcos catalog and moves its positions to the Gaia epoch, J2016.0.mergecombines the two and drops the Gaia or Hipparcos copy of each star that’s in both.build-indexsorts the stars into HEALPix cells, applies the cap and writes the catalog file.
The ingest steps write to one working directory, and merge and
build-index read from it. Every subcommand takes --help and
--verbose (-v). The examples use /data/gaia for the Gaia files,
/data/hip for the Hipparcos files and /data/work for the working
directory.
Download Gaia DR3
forge download-gaia --output /data/gaia
download-gaia lists the files on ESA’s server and downloads four at a
time. Change that with --concurrency. Each failed file is retried up to
three times (--retries), and --limit 10 downloads only the first ten
files, which is enough to try the later steps on a patch of sky. Pass
--allow-partial-sky to ingest-gaia for such a patch.
The command records each verified file in gaia_manifest.json in the
output directory, so you can stop it and run it again: the rerun skips
every file that the manifest lists with the same size and ETag. If you got
the files some other way, there’s no manifest. The command then hashes each
local file of the right size, skips the ones whose MD5 matches ESA’s
_MD5SUM.txt, and adds them to the manifest. Hashing all 3,386 files reads
all of the roughly 750 GB once, which is limited by disk speed but takes far less
time than downloading it again. A file that doesn’t match is downloaded
again.
Each file name gives the range of HEALPix level-8 pixels that the file
holds: GaiaSource_000000-003111.csv.gz holds pixels 0 to 3111, and the
3,386 files cover pixels 0 to 786431 once each. Unless you pass --limit,
the command checks that ESA’s listing covers the sky that way and stops
if it doesn’t, because a listing cut short would leave files out.
--allow-partial-sky downloads such a listing anyway.
Ingest Gaia
forge ingest-gaia --path /data/gaia --output /data/work --mag-limit 18.5
This keeps every Gaia star brighter than G 18.5 and writes them to
/data/work/gaia_ingest.bin. The pre-built files used 18.5, which keeps
more than 419 million stars. The default limit is 15.0. Each half magnitude fainter
adds a lot of stars, so pick the faintest limit you need rather than the
faintest you can store.
The command processes files in parallel, one per core unless you pass
--threads. It writes a part file for each input file and joins them at
the end, deleting the parts. If a run stops partway, the next run skips
every input file that already has a part file. If a file fails to
decompress or parse, the command lists it in failed_files.log and
doesn’t write gaia_ingest.bin, so a damaged download can’t produce an
incomplete catalog.
Before it reads any file, the command checks the file names. If a file is missing, it lists the pixels that no file covers and stops:
Error: The .csv.gz files in "/data/gaia" do not cover the sky once. GaiaSource_AAAAAA-BBBBBB.csv.gz holds HEALPix level-8 pixels AAAAAA to BBBBBB, and the 3,386 Gaia DR3 files cover pixels 000000-786431 once each:
pixels 467168-467207 have no file
pixels 467355-467400 have no file
Add or remove files until they cover the sky once, then rerun. To build a catalog of part of the sky, pass --allow-partial-sky.
Those two gaps are four files in Ophiuchus, about 4.5 deg² of sky. The
join at the end checks the part file names the same way, so part files
left over from another set of input files can’t add a second copy of a
patch of sky. To build from part of the sky on purpose, pass
--allow-partial-sky. With --no-concat, a gap is only a warning,
because the run that joins the parts checks them.
To change the magnitude limit after an interrupted run, delete the
gaia_part_*.bin files first. They hold the old limit’s stars, and the
join refuses parts with a different limit.
Ingest Hipparcos
forge ingest-hipparcos --workdir /data/hip --output /data/work --mag-limit 7.5
Gaia DR3 has no usable astrometry for some of the brightest stars, so
the catalog takes them from Hipparcos. The command reads hip2.dat, the
Hipparcos new reduction (van Leeuwen 2007), and Gaia’s Hipparcos
cross-match table Hipparcos2BestNeighbour.csv from --workdir. When a
file is missing, it downloads the compressed copy from CDS or ESA and
unpacks it, so the first run fetches about 11 MB.
The pre-built files used --mag-limit 7.5, which keeps 23,270 Hipparcos
stars. The default is 7.0. The command moves each star from the Hipparcos
epoch, J1991.25, to J2016.0, and writes hipparcos_ingest.bin and
hipparcos_shared_matches.bin to --output.
Merge
forge merge --workdir /data/work
merge writes merged.bin with every star from both ingests, once. For a
star in both, it keeps the Gaia record when Gaia has a 5- or 6-parameter
astrometric solution for it, and the Hipparcos record otherwise.
It finds most stars in both through the cross-match table. The table has
no entry for about 4,200 of the 23,270 Hipparcos stars, so merge pairs
each of those by position. It takes the nearest Gaia record within 2″
whose G is at most 2.0 mag brighter or 1.0 mag fainter than the star’s
Hp. Both places are at J2016.0. The limits come from these sources of
difference:
- Position. The Hipparcos place has moved 24.75 years from J1991.25. The catalog errors give 18 mas of uncertainty for the median star, but a binary’s orbit curves its path, and an acceleration of 6.5 mas/yr² moves it 2″ off the straight line in that time.
- Magnitude. Hp and G are different bands. G reaches further into the red, so a red giant’s G is up to about 2 mag brighter than its Hp. G is fainter than Hp when Gaia splits a pair that Hipparcos measured as one star: each star of an equal pair is 0.75 mag fainter than both.
At the pre-built files’ magnitude limits this pairs about 4,100 stars. For about 40 of them a second Gaia record also qualifies, usually the other star of a pair, and that record stays. A Gaia record that two Hipparcos stars pick is dropped, and both Hipparcos records stay, as for a Gaia source that the cross-match table gives to two stars. About a dozen stars keep both records, because the two magnitudes differ by more than the limits allow.
Build the index
build-index is where the three pre-built files differ. These are the
commands that made them, each from the same merged.bin:
forge build-index --workdir /data/work --output catalog-full.bin --healpix-order 8 --max-per-cell 200
forge build-index --workdir /data/work --output catalog-standard.bin --healpix-order 8 --max-per-cell 50
forge build-index --workdir /data/work --output catalog-small.bin --healpix-order 6 --max-per-cell 100
--healpix-order sets the grid: nside = 2^order, and the default is 8.
The largest order is 10, because above it the index grows past 805 MB and
wide cone searches fail. --max-per-cell keeps that many of the
brightest stars in each cell. Leave it out and every star is kept, which
at magnitude 18.5 gives a 23.5 GB file. How the Catalog File
Works explains how to
choose the two.
The command prints its plan, then statistics about the result. This is
the end of the run that built catalog-small.bin:
=== Index Statistics ===
HEALPix order: 6
nside: 64
npix: 49152
Epoch: J2016
Magnitude limit: 18.50
Total stars before cap: 419445381
Total stars after cap: 4915200
Stars removed by cap: 414530181
Cells at cap: 49152 / 49152 non-empty (100.0%)
Empty pixels: 0
Stars per pixel (non-empty): min=100, max=100, mean=100.0, median=100
Output file size: 276037696 bytes (0.26 GB)
Elapsed time: 88.64s
Validating output...
Pixel 0: 100 stars verified
Pixel 24576: 100 stars verified
Pixel 49151: 100 stars verified
Validation passed.
Written "catalog-small.bin"
“Cells at cap” is the share of cells where the cap cut stars. In those cells the catalog is shallower than the magnitude limit. Here every cell was cut. The full file’s build reports 46.1%, so more than half of its cells keep every star to 18.5.
The command builds into a temporary file beside --output, opens it with
the library to check it, and only then renames it into place. A failed
build leaves an earlier catalog at that path untouched. The temporary
file is as large as merged.bin, so the output’s disk needs that much
free space.
Next steps
- To check the new file, run
query-catalog --catalog <file> info, as The query-catalog Command shows. - To compare your file’s depth with the pre-built ones, see Choose a size.
How the Catalog File Works
The full catalog file is 6.2 GB, yet opening it reads only 12.6 MB, and a 1° cone search of it returns in under a millisecond once its pages are in memory. How does a search know where to look without reading the rest of the file?
The answer is that the file is sorted by position. The sky is cut into cells of equal area, every star is filed under its cell, and a small index at the front of the file says where each cell’s stars start. A search works out which cells its circle touches, looks them up in the index and reads those cells’ stars, and nothing else.
Cells on the sky
The cells come from HEALPix (Górski et al. 2005), the grid that Gaia and Planck use. It starts with 12 base cells, and each step of refinement splits every cell into four. The number of steps is the order, so a grid of order N has 12 × 4^N cells, all with the same area:
| Order | Cells | Cell size | Cell area |
|---|---|---|---|
| 6 | 49,152 | 55′ | 0.84 deg² |
| 8 | 786,432 | 13.7′ | 0.052 deg² |
| 10 | 12,582,912 | 3.4′ | 0.0033 deg² |
The file numbers its cells in HEALPix’s nested scheme. In that scheme the four children of cell p are cells 4p to 4p + 3, so cells that are close in number are close on the sky. A cone search uses this: it starts from the 12 base cells, keeps the ones that might overlap the circle, splits those, and repeats down to the file’s order. What’s left is every cell that touches the circle, plus a few near its edge that turn out not to.
A 1° search at order 8 covers about 60 cells’ worth of area, plus the cells its edge crosses. The search reads those cells’ stars and drops the ones outside the circle.
Inside the file
The file has three parts, one after the other:
- A 64-byte header: the magic bytes
CCAT, the format version, the order, nside, the number of cells, the number of stars, the epoch as a Julian year and the magnitude limit. - The cell index: 16 bytes per cell, giving the byte offset of the cell’s first star and how many stars it has. At order 8 that’s 12.6 MB, and at order 6 it’s 786 KB.
- The star records: 56 bytes each, grouped by cell, and brightest first within each cell.
You can check the arithmetic on the small file: 64 bytes, plus 49,152
cells at 16 bytes, plus 4,915,200 stars at 56 bytes, is 276,037,696
bytes, the size that query-catalog info prints.
Everything is little-endian, and each record has the same layout as the
StarRecord struct in memory. The library maps the file into memory and
treats the records as a &[StarRecord] slice in place, so reading a star
costs a memory access and nothing more. The same layout means the crate
only builds for little-endian targets, which covers x86-64 and the
64-bit ARM machines in common use.
Catalog::open checks the header, checks that the file is exactly as
long as the header says, and checks that every index entry points inside
the star data at its own run of records. A damaged or truncated file fails
there, so a search never reads past the end of the map. Opening a version
1 file fails with a message to rebuild it: version 1 numbered some cells
wrongly, and its stars would land in the wrong places.
What the order and the cap trade
A catalog to magnitude 18.5 has more than 419 million stars. Almost all of them are
faint stars along the Milky Way, and few uses need them all. forge
thins them with a cap: each cell keeps only its brightest N stars.
Two settings then decide what’s in the file: the order sets the cell
size, and the cap sets how many stars each cell keeps.
The cap sets the most stars any patch of sky can have, the cap divided by the cell area:
| File | Order | Cap | Most stars per deg² |
|---|---|---|---|
catalog-small.bin | 6 | 100 | 119 |
catalog-standard.bin | 8 | 50 | 953 |
catalog-full.bin | 8 | 200 | 3,812 |
The order decides how evenly those stars are spread. Take one 55′ cell of the small file. It’s the same patch of sky as 16 cells of the standard file. The small file keeps the 100 brightest stars of the whole patch, so if a bright cluster is in one corner, the cluster can take most of the 100 and leave the rest of the patch nearly empty. The standard file keeps 50 in each of the 16 smaller cells, 800 in all, and every corner of the patch gets its share. A narrow field sees about the same number of stars wherever it points.
Higher orders cost little at search time. Their price is a larger index:
Catalog::open checks every entry, and each entry takes 16 bytes of disk
whether or not its cell holds stars. forge stops at order 10, where the
index is already 201 MB.
Where the cap cuts in
Away from the Milky Way, many cells hold fewer stars than the cap, all the way to magnitude 18.5. Those cells keep everything. Along the galactic plane the cap fills with bright stars, and the cell’s faintest kept star can be magnitude 10 to 12. The depth of the catalog therefore changes across the sky. Choose a size lists the depth of each pre-built file.
For plate solving, that’s the right trade. A solver matches the brightest
stars it detects, so it needs the brightest catalog stars in every part
of the field, and it has little use for a dense list of faint stars in
one cell. If you need completeness to a fixed magnitude everywhere, build
a file without --max-per-cell, or with a cap high enough that no cell
reaches it.
Where the stars come from
forge builds the file from two sources:
- Gaia DR3, every star brighter than the magnitude limit, G 18.5 for the pre-built files. Positions, proper motions and parallaxes are at J2016.0.
- Hipparcos, from the new reduction of van Leeuwen (2007), for stars
brighter than Hp 7.5. Gaia has no 5- or 6-parameter astrometry for some
of the brightest stars, and Hipparcos fills them in.
forgemoves each Hipparcos position from J1991.25 to J2016.0, so the whole file has one epoch.
A star in both catalogs keeps its Gaia record when Gaia has a 5- or
6-parameter solution for it, and its Hipparcos record otherwise. forge
finds the stars in both through Gaia’s Hipparcos cross-match table. The
table has no entry for about 4,200 of the 23,270 Hipparcos stars, and
forge pairs about 4,100 of those with the nearest Gaia record within 2″
of the right magnitude. Build a Catalog with forge
gives the limits.
Edge cases
- A whole-sky search holds every star in memory. A radius of 180° or
more searches the whole sky, and for the full file that’s 111 million
results at 80 bytes each, about 8.9 GB. To visit every star, loop over
the cells with
Catalog::stars_in_pixelinstead. - Fast-moving stars near the edge of a search. A search picks cells by the stored J2016.0 positions, then matches on the moved ones. A star that was outside every cell the circle touches in 2016, but has moved inside the circle by your date, isn’t returned. Barnard’s Star, the fastest, moves 10.4″ a year, so even ten years from the catalog epoch this needs a fast star within about 2′ of the circle’s edge.
- One magnitude system per record. Gaia records have G and Hipparcos
records have Hp. The two agree to a few tenths of a magnitude for most
stars, but a red star’s G can be up to 2 mag brighter than its Hp. A
max_magcut near a star’s magnitude can keep or drop it depending on which catalog its record came from.
Next steps
- To pick a file, read Get a Catalog File.
- To build a file with your own order and cap, read Build a Catalog with forge.
- For how the plate solver uses the catalog, see The Star Catalog.
Solve Your First Image
You have a frame from last night and you want to know exactly where it points: the sky position of every pixel, the plate scale and the field rotation. Finding that out from the stars in the image is called plate solving, and the answer is a WCS (World Coordinate System), the mapping from pixel coordinates to sky coordinates that FITS headers store.
celestial-solver is a plate solver. It detects the stars in your image,
matches them against a Gaia DR3 and Hipparcos star catalog, and fits a WCS
with lens distortion terms. This page solves one image from the command
line and then from Rust.
What you need
- An image in FITS or XISF, straight from your capture program. Most capture programs write the rough pointing, the time and the optics into the header, and the solver reads them. Hints and Image Metadata covers images without them.
- A star catalog file. Download one from the catalog
folder.
The examples use
catalog-standard.bin, 2.2 GB. The Star Catalog explains the three sizes and how to choose. - The
image-solverbinary, built with theclifeature:
cargo install --path celestial-solver --features cli
Solve from the command line
The example image is a 2328 x 1760 frame of M106 taken through a 14-inch
SCT. Point image-solver at the image and the catalog:
image-solver --image m106.fit --catalog catalog-standard.bin
================================================================================
Creation time ............ 2026-11-29 17:42:41 UTC
Creation software ........ Celestial Image Solver v0.1.1-alpha.2
Reference catalog ........ Gaia DR3 - Celestial Catalog v0.1.1-alpha.2
Linear transformation matrix (sky = matrix * pixel):
-1.17033237e-5 +1.59491498e-4 -1.26803744e-1
-1.59558955e-4 -1.18413163e-5 +1.96232683e-1
Projection ............... Gnomonic (TAN-SIP)
Projection origin ........ [1164.500000 880.500000] px -> [RA: 12 18 54.266 Dec: +47 18 38.81]
Resolution ............... 0.575 arcsec/px (linear approximation)
Rotation ................. -85.785 deg (linear approximation)
Reference system ......... ICRS
Observation start time ... 2023-03-20 04:17:45 UTC
Focal distance ........... 2725.60 mm
Pixel size ............... 7.60 um
Field of view ............ 22' 18.6" x 16' 52.5"
Image dimensions ......... 2328 x 1760 px
Image center ............. RA: 12 18 54.240 Dec: +47 18 39.12 ex: -0.026787 px ey: -0.025739 px
Image bounds:
top-left RA: 12 18 09.389 Dec: +47 30 21.12 ex: +0.011043 px ey: +0.014759 px
top-right RA: 12 17 59.911 Dec: +47 08 08.03 ex: -0.019714 px ey: +0.026397 px
bottom-left RA: 12 19 48.782 Dec: +47 29 06.58 ex: +0.016245 px ey: -0.003358 px
bottom-right RA: 12 19 38.740 Dec: +47 06 55.42 ex: +0.002875 px ey: -0.030406 px
SIP distortion order ..... A=3, B=3
A_2_0 +7.960367e-7
A_1_1 -6.321852e-7
A_0_2 +1.379057e-7
A_3_0 -1.541029e-9
A_2_1 -4.614312e-10
A_1_2 -2.109124e-9
A_0_3 -7.964577e-10
B_2_0 -1.469285e-7
B_1_1 +4.951556e-7
B_0_2 -5.844659e-7
B_3_0 -5.513422e-10
B_2_1 -1.434648e-9
B_1_2 -5.377468e-10
B_0_3 -8.729534e-10
Control points ........... 24
Linear RMS ............... 0.5607 px
SIP RMS .................. 0.2055 px
Weighted SIP RMS ......... 0.2056 px
Improvement .............. 63.3%
================================================================================
--- timings ---
open file: 2.5ms
solve: 50.6ms
save files: 2.4us
total: 53.0ms
The lines to read first:
- Image center is where the middle of the frame points. The header
said
12 18 48.035 +47 15 45.90, so the mount was off by about 3 arcminutes. - Resolution and Rotation are the plate scale and the angle from image up to north. “Linear approximation” means they describe the linear part of the fit, before the distortion terms.
- Focal distance is the effective focal length that the fitted scale implies for the header’s pixel size. The header said 2737 mm.
- Control points is the number of image stars the final fit used. SIP RMS is the RMS distance between those stars and the places where the solution puts their catalog positions: 0.21 px here.
The report goes to standard output and the timings to standard error, so
image-solver ... > m106.txt saves the report alone. The image-solver
Command describes every line of the report.
Save the solution
Add --output to write a copy of the image with the WCS in its header:
image-solver --image m106.fit --catalog catalog-standard.bin --output m106.solved.fits
The extension picks the format: .fits, .fit or .fts for FITS, or
.xisf. The input file isn’t touched. The new header has the standard FITS
WCS cards, with SIP distortion cards when the solver fitted them, so any
program that reads a FITS WCS can place the image on the sky. The solver
also reads that WCS back, so solving the solved file works and starts from
the WCS it holds.
Solve from Rust
The library call is solve(&image, &catalog).run(). It reads the same
header values as the command does and returns a SolveResult:
use celestial_catalog::query::catalog::Catalog;
use celestial_images::formats::image::Image;
use celestial_solver::solve::solve;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("m106.fit")?;
let catalog = Catalog::open("catalog-standard.bin")?;
let result = solve(&img, &catalog).run()?;
let (ra, dec) = result.pixel_to_sky(1163.5, 879.5)?;
println!("center: RA {ra:.4}°, Dec {dec:.4}°");
let (sx, sy) = result.wcs.scale_arcsec();
println!("scale: {sx:.3} x {sy:.3} arcsec/px, rotation {:.2}°", result.wcs.rotation_deg());
println!("{} stars matched, log-odds {:.1}", result.pairs.len(), result.log_odds);
match &result.sip {
Some(sip) => println!("RMS {:.3} px with SIP order {}", sip.rms_px, sip.a_order),
None => println!("RMS {:.3} px", result.wcs.rms_px),
}
result.save_with(&img, "m106.solved.fits")?;
Ok(())
}
center: RA 184.7260°, Dec 47.3109°
scale: 0.575 x 0.575 arcsec/px, rotation -85.79°
24 stars matched, log-odds 202.3
RMS 0.206 px with SIP order 3
pixel_to_sky and sky_to_pixel apply the full solution, distortion
included. They count pixels from 0 at the center of the first pixel, so
the center of this 2328 x 1760 frame is (1163.5, 879.5). The FITS header
counts from 1 at the same point, and the text report counts from 0 at the
outer corner of the first pixel. Those are the same position in three
conventions.
result.wcs is the linear fit alone, and result.wcs.rms_px is its RMS,
0.56 px here. When the solver fitted distortion terms, result.sip holds
them with their own RMS. log_odds measures how sure the solver is that
the match is real. How Solving Works explains it.
save_with writes a solved copy as --output does. To add the WCS to an
image you already hold, call result.write_into(&mut img).
The library API is likely to change shape in a later release. The steps and ideas in these pages will stay the same.
Next steps
- To pass a focal length, a position or a whole set of metadata, read Hints and Image Metadata.
- If the solve failed, go to When Solving Fails.
- To understand what the solver did, read How Solving Works.
- To use the WCS for pixel and sky conversions elsewhere, see Pixels and Sky Coordinates.
How Solving Works
Your image holds a few hundred points of light. The catalog holds tens of millions of stars. The header gives a rough idea of where the telescope was pointing, but the field could be rotated by any angle, mirrored, and offset by a few arcminutes. How does the solver work out which dots are which stars?
It runs in five stages, and each one narrows the question:
- Detect the stars in the image.
- Match small star patterns in the image against patterns in the catalog around the hint.
- Verify each candidate match by asking how likely the rest of the image is if the match were true.
- Fit a WCS to the matched stars, then match every detected star and fit again with distortion terms.
- Verify the final WCS the same way, and fall back to the simpler fit if it fails.
The matching and verification follow the method of Lang et al. 2010, “Astrometry.net: Blind astrometric calibration of arbitrary astronomical images” (AJ 139, 1782).
Finding the stars
Detection has to find stars and only stars. Hot pixels, nebulosity, galaxy cores and gradients from the moon all stand above the background too, and each false star is noise for the matcher.
The detector first models the background on a grid of 64-pixel cells, so a gradient across the frame doesn’t read as signal. It then builds a structure map: the image minus a smoothed copy of itself, which keeps features about the size of a star and drops larger ones. Connected regions of that map become candidates. Regions under 5 pixels are hot pixels or cosmic rays, regions over 2000 pixels are nebulae or galaxies, and both are dropped. So are regions within 5 pixels of the edge, whose light is cut off.
Each surviving region gets a centroid, a sub-pixel position from the pixel values above the local background. A star needs a signal-to-noise ratio of at least 5, and a fainter detection within 20 pixels of a brighter one is dropped as a duplicate. Stars with large saturated cores are rejected, because their centroids are poor. The output is a list sorted by flux, brightest first.
Detection works on whatever pixel type the file holds: 8-bit and 16-bit camera frames and 32-bit float stacks all solve without conversion.
Matching star patterns
Rotation and scale make direct comparison hopeless, so the solver compares shapes instead. It takes groups of four stars, called quads, and reduces each one to four numbers that stay the same when the group is moved, rotated or scaled. The two stars farthest apart define a frame, with one at (0, 0) and the other at (1, 0). The positions of the other two stars in that frame are the four numbers, called the quad’s hash. The same four stars in the catalog give the same hash, give or take the centroid error.
On the image side, the solver picks up to 100 stars: the brightest in each cell of a grid over the image, so that one bright corner doesn’t take all of them. It builds quads from each star and three of its 10 nearest neighbors.
On the catalog side, it searches a cone around the hint. The cone’s radius is 1.2 times half the image diagonal, so the field still fits inside it when the hint is a little off. It picks catalog stars at the same density as the image stars, builds quads the same way, and indexes their hashes. Every image quad whose hash lands near a catalog quad’s hash is a candidate match.
A mirrored image has mirrored quads. Images come out mirrored after some meridian flips and with some diagonals, so the solver runs the search twice in parallel, once for each orientation, and accepts whichever finds a verified match first.
Is the match real?
Most candidate matches are chance. With thousands of quads on each side, some image quad will resemble some catalog quad by accident. The solver needs a test that rejects those and accepts real matches quickly.
Each candidate gives four star pairs, which are enough to fit a linear map from the sky to the image. That map predicts where the brightest catalog stars in the field should appear. If the match is real, many of the other detected stars sit within a pixel or so of a prediction. If it’s chance, the detections fall where they fall, with no relation to the predictions.
The solver compares these two explanations one detection at a time, in order of brightness. Each detection near a prediction makes “real” more likely, and each one far from every prediction makes it less likely. The running total is the log-odds: the natural log of how many times more likely the match is to be real than chance. The model allows for a quarter of the detections having no catalog counterpart, because satellites, hot pixels and stars fainter than the catalog limit are common. The four stars of the quad itself are left out, since they agree with the map by construction.
A match is accepted when the log-odds passes ln(10⁹), about 20.7: odds of a billion to one. The threshold comes from the paper’s cost model, in which accepting a false match costs far more than missing a true one. The test has a useful guarantee: a chance match reaches odds of K to 1 with probability at most 1/K, whatever the image looks like. A typical real match passes with a lot to spare. The M106 frame on the first page ended at 202.
The first candidate to pass is accepted, and the search stops there. The order is fixed, so the same image and catalog always give the same answer.
Fitting the WCS
The accepted match brings its star pairs: the quad’s own stars and the other detections that landed on catalog stars. The solver fits a gnomonic (TAN) projection to them, the standard projection for telescope images. It first fits a model to every set of three pairs among the 100 best, and keeps the model that most pairs agree with. That removes the occasional wrong pair. It then fits by weighted least squares, weighting each pair by how precise its centroid is, so bright stars count more than faint ones.
Two checks follow. The fitted plate scale must be within a factor of 2 of the hint, and the fitted center must be within one image diagonal of the hint position. A match that fails either one contradicts what the header says, and the solve stops with an error rather than return it.
The first fit only used the stars the matcher found. Refinement uses all of them. With the first WCS, the solver predicts where up to 2000 catalog stars around the field fall in the image, and pairs each detection with the nearest prediction within 3 pixels. It fits again with those pairs, predicts again, and repeats until the pairs stop changing, at most 5 times.
The refit also models lens and field distortion with SIP polynomials, the standard FITS way to describe distortion. Each order adds terms, and too many terms bend the solution to fit noise. To choose, the solver fits every order up to 4, and for each one predicts each star from a fit that left that star out. It keeps the order with the smallest of those prediction errors, which may be no distortion terms at all. The M106 frame chose order 3, and its RMS went from 0.56 px to 0.21 px.
Checking the result
The refined WCS goes through the same log-odds test as the matches did. It places the catalog stars, and each fitted star is scored against a fit made without it, so a WCS can’t pass by agreeing with its own inputs. The SIP terms are left out of this test, because a high-order polynomial could bend a slightly wrong solution onto its own stars.
If the refined WCS fails, or the refinement couldn’t fit at all, the solver
falls back to the first WCS and tests that instead. result.refinement
records which one you got and why. If neither passes, the solve fails with
a NoMatch error that gives the log-odds it reached.
What you get back
A solve returns one WCS in two forms:
result.wcs, the linear TAN fit, with its scale, rotation and RMS.result.sip, the distortion fit with its own center and CD matrix, when an order of 2 or more was chosen.
The FITS header the solver writes combines them: RA---TAN-SIP and
DEC--TAN-SIP axes, the A_p_q and B_p_q coefficients, and inverse
AP_p_q and BP_p_q coefficients so that readers can map sky to pixel as
well as pixel to sky. Positions are ICRS, at the epoch of the image:
catalog stars are moved by their proper motion from the catalog epoch,
J2016.0, to the date in the header.
Limits
- There is no blind solving. The solver searches around a position hint and a plate scale, and won’t search the whole sky. Hints and Image Metadata explains how far off they can be.
- Dense nebulae and galaxy fields can starve detection. Bright extended regions are rejected as not star-shaped, and a field with few stars left may not reach the log-odds threshold.
- Very small fields need a deep catalog. A field of 10 arcminutes holds few stars brighter than G 18.5, and the smaller catalog tiers hold fewer. The Star Catalog has the numbers.
Next steps
- Hints and Image Metadata covers what the solver reads from the header and how to supply it yourself.
- When Solving Fails maps each error back to the stage above that raised it.
Hints and Image Metadata
The solver doesn’t search the whole sky. It needs three things before it starts: roughly where the image points, roughly how many arcseconds one pixel covers, and when the image was taken. Capture programs such as NINA, SharpCap, Ekos and SGP write all three into the FITS header, and the solver reads them from there. This page covers where each one comes from, how wrong it can be, and how to supply it when the header doesn’t have it.
Why the solver needs a hint
The matching stage compares image quads with catalog quads from one patch of sky. The position hint picks the patch, and the plate scale sets its size and the spacing of the stars in it. Without them, the solver would have to compare against the whole sky at every scale, which is slower and needs a different kind of index.
The epoch matters less. The catalog positions are for J2016.0, and the solver moves each star by its proper motion to the date of the image. For most stars that’s well under a pixel, but nearby stars move by arcseconds per decade.
What the solver reads from the header
| Needed | Header keywords, in the order tried |
|---|---|
| Position hint | the sky position of the image center under the header’s WCS, then CRVAL1/CRVAL2, then RA/DEC, then OBJCTRA/OBJCTDEC |
| Plate scale | FOCALLEN in mm and XPIXSZ in microns |
| Epoch | MJD-OBS, then DATE-OBS, with TIME-OBS when DATE-OBS has no time |
The plate scale is 206.265 × XPIXSZ / FOCALLEN arcseconds per pixel.
XPIXSZ must be the size of a binned pixel: 7.6 µm for a 3.8 µm sensor
binned 2x2. Most capture programs write it that way.
RA and DEC can be decimal degrees or sexagesimal strings. OBJCTRA
and OBJCTDEC are sexagesimal, in hours and degrees. When a header
repeats a keyword, the last card wins, which is how FITS libraries read
it.
A header with a full WCS from an earlier solve gives the best hint of all, so solving an already solved image works and starts from its old solution.
How wrong the hint can be
The solver has two limits that you can see in its errors:
- Plate scale within a factor of 2. The first fitted scale must be
between half and double the hint. On the jellyfish nebula frame below,
whose true focal length is 2943 mm, each
--focal-lengthtried from 1500 to 5800 solved. 7000 failed this check, and 1000 failed earlier, in matching, because the solver looked for star patterns at the wrong size. - Center within one image diagonal. The fitted center must be within one diagonal of the hint. In practice the catalog search is the tighter limit: it covers a cone of 0.6 diagonals around the hint, and the image has to fall mostly inside it. On the M106 frame, whose diagonal is 0.47°, a hint 0.2° off solved and a hint 0.3° off didn’t. On a 2.3° x 1.7° frame of the Rosette nebula, whose diagonal is 2.9°, a hint 1° off solved.
For a mount that has been synced or plate solved once that night, both limits are generous. They exist to catch a header that is wrong, such as a focal length typed for a different telescope, before the solver returns a match that disagrees with it.
Override a header value
When the header is wrong or missing one value, override that value and
let the rest come from the header. The jellyfish nebula frame has
XPIXSZ, OBJCTRA, OBJCTDEC and DATE-OBS, but no FOCALLEN:
$ image-solver --image jellyfish.fit --catalog catalog-standard.bin
Error: image is missing required header: FOCALLEN
Give the focal length on the command line:
image-solver --image jellyfish.fit --catalog catalog-standard.bin --focal-length 2900
--focal-length also fixes a header that names the bare telescope when a
reducer or Barlow was in the path. --pixel-size fixes a pixel size that
doesn’t account for binning.
In Rust, each value has a setter on the solver: hint, epoch,
focal_length_mm, pixel_size_um and plate_scale_arcsec. The epoch is a
UTC Julian Date, the scale DATE-OBS uses. The solver converts it to TT
for the catalog, so it must be 1960 or later, when UTC begins.
use celestial_catalog::query::catalog::Catalog;
use celestial_images::formats::image::Image;
use celestial_solver::solve::solve;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("jellyfish.fit")?;
let catalog = Catalog::open("catalog-standard.bin")?;
// The header has XPIXSZ but no FOCALLEN.
let result = solve(&img, &catalog).focal_length_mm(2900).run()?;
let (sx, _) = result.wcs.scale_arcsec();
println!("scale: {sx:.3} arcsec/px");
if let Some(f) = result.wcs.effective_focal_mm() {
println!("effective focal length: {f:.0} mm");
}
Ok(())
}
scale: 0.527 arcsec/px
effective focal length: 2943 mm
A plate scale you set with plate_scale_arcsec takes priority over the
focal length and pixel size. Use it when you know the scale from an
earlier solve but not the optics. effective_focal_mm is the focal length
the fitted scale implies. When it’s far from the nominal one, there’s a
reducer or Barlow in the path that the header doesn’t know about.
Images without a header
PNG and TIFF files have no FITS header, and some software writes FITS files
without the keywords above. For those, build an ImageMetadata yourself
and pass it with with_metadata. The solver then reads nothing from the
header:
use celestial_catalog::query::catalog::Catalog;
use celestial_coords::frames::icrs::ICRSPosition;
use celestial_images::formats::image::Image;
use celestial_solver::metadata::image_metadata::ImageMetadata;
use celestial_solver::solve::solve;
use celestial_time::scales::utc::utc_from_calendar;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("m106.fit")?;
let catalog = Catalog::open("catalog-standard.bin")?;
let meta = ImageMetadata {
hint: ICRSPosition::from_degrees(184.74, 47.30)?, // M106
scale_arcsec: 0.58,
epoch: utc_from_calendar(2023, 3, 20, 4, 17, 45.7)?.to_julian_date(),
focal_mm: None,
pixel_um: None,
};
let result = solve(&img, &catalog).with_metadata(meta).run()?;
println!("center: {:.4}°, {:.4}°", result.wcs.crval1, result.wcs.crval2);
Ok(())
}
center: 184.7260°, 47.3107°
scale_arcsec is the plate scale the solve uses. focal_mm and
pixel_um are optional: the solver copies them into the result for the
report and for effective_focal_mm, and doesn’t use them to solve. Once
you call with_metadata, the individual setters such as hint are
ignored.
The image-solver command has no flags for the position or the epoch, so
an image without them in its header needs the library.
Next steps
- If the solve still fails with good metadata, read When Solving Fails.
- For every flag of the command, see The image-solver Command.
The Star Catalog
The solver matches your stars against a catalog file, and that file is the biggest thing you’ll download. It comes in three sizes, from 276 MB to 6.2 GB. Which one you need depends mostly on how much sky your images cover.
What the catalog holds
Each catalog is built from Gaia DR3, with Hipparcos stars merged in.
Where Gaia’s cross-match table links a Hipparcos star to its Gaia record,
the file keeps one copy. forge pairs most stars without a link by
position and magnitude, and about a dozen bright stars still appear
twice; Where the stars come from has the details. Every
file holds stars down to Gaia G magnitude 18.5, with positions and proper
motions at epoch J2016.0. The solver moves each star to the date of your
image before it matches.
The stars are sorted into HEALPix pixels, a scheme that divides the sky into cells of equal area. The file is memory-mapped, so opening it reads only a header and an index, and a search reads only the cells it touches. The celestial-catalog README covers the file format and how to query it yourself.
A catalog keeps at most a fixed number of stars in each cell, the brightest ones. That cap is what sets a catalog’s size. Away from the Milky Way, a cell may hold fewer stars than the cap down to G 18.5, so all of them are kept. Along the galactic plane, the cap fills up with stars much brighter than 18.5.
The three sizes
Download them from the catalog folder.
| File | HEALPix order | Cell size | Stars per cell | Stars | Size | Most stars per square degree |
|---|---|---|---|---|---|---|
catalog-full.bin | 8 | 13.7’ | 200 | 111,072,265 | 6.2 GB | 3,812 |
catalog-standard.bin | 8 | 13.7’ | 50 | 38,841,656 | 2.2 GB | 953 |
catalog-small.bin | 6 | 55’ | 100 | 4,915,200 | 276 MB | 119 |
The last column is the cap divided by the cell area, so it’s the most stars any patch of sky can have in that file. Multiply it by your field’s area to see how many catalog stars the solver has to work with. The M106 frame on the first page covers 22’ x 17’, or 0.10 square degrees: about 400 stars from the full catalog, 100 from standard and 12 from small.
Every cell of the small catalog is full, so its density is close to the same everywhere on the sky.
How each size did on the test images
These are the test images this crate is developed against, solved with
image-solver and each catalog. Control points are the stars the final
fit used. The jellyfish nebula frame has no FOCALLEN in its header, so
it was solved with --focal-length 2900.
| Image | Field | Full | Standard | Small |
|---|---|---|---|---|
| M106 | 22’ x 17’ | 24 | 24 | 10, no SIP |
| Jellyfish nebula | 42’ x 28’ | 197 | 128 | 41 |
| Cygnus Wall | 2.0° x 1.3° | 520 | 520 | 180 |
| Elephant’s Trunk | 2.0° x 1.3° | 560 | 560 | 171 |
| Rosette nebula | 2.3° x 1.7° | 733 | 733 | 403 |
| Bode’s galaxies, L | 4.1° x 3.1° | 844 | 844 | 844 |
| Bode’s galaxies, Hα | 4.1° x 3.1° | 783 | 783 | 783 |
Every image solved with every catalog. Solve times were 50 to 200 ms per image, and the catalog made no consistent difference: on the Rosette frame, star detection took 156 ms of a 190 ms solve. The first solve after opening a catalog can take longer, while the operating system reads its pages from disk.
The narrow fields show the cost of a small catalog. With 10 matched stars, the M106 solution had too few to fit distortion terms, and its RMS rose from 0.21 px to 0.32 px. Fewer control points also leave the corners of the frame with less coverage, which is where distortion is largest.
Choosing one
- Wide fields, about 1° across or more:
catalog-small.binholds enough stars, and it’s a quick download. A camera lens or a short refractor is in this range. - Fields from about 20’ to 1°:
catalog-standard.bin. It’s the default in these pages. - Fields under about 20’, or crowded fields along the Milky Way:
catalog-full.bin. A long-focus SCT or a small sensor is in this range, and on the 42’ jellyfish frame the full catalog gave 197 stars against 128 for standard.
If you aren’t sure, start with the standard file. If the solve reports
few control points, or fails with a NoMatch error on a narrow field, try
the full one.
Next steps
- Solve Your First Image uses
catalog-standard.bin. - When Solving Fails covers a solve that finds too few stars.
When Solving Fails
A failed solve ends with one line that starts with Error:, and that line
says which stage gave up. This page goes through the messages in pipeline
order, says what each one means, and what to try. How Solving
Works describes the stages themselves.
See what the solver saw
Two flags show more than the final error. --verbose logs each stage:
how many stars detection kept and why it dropped the rest, how big the
catalog search was, and the best log-odds each orientation reached.
image-solver --image cygnus.fit --catalog catalog-standard.bin --verbose
[INFO ] [detect] components: 1.836125ms (253 regions)
[INFO ] [detect] centroid: 514.25µs (83 passed, 170 rej_snr, 0 rej_sat)
[INFO ] [detect] sort+dedup: 10.666µs (66 after dedup)
[INFO ] [solve] detect: 9.2515ms (66 stars)
[DEBUG] match_field: radius=0.176°, scale=1.461"/px
[DEBUG] match_field: 90 catalog stars, 6961 catalog quads
[DEBUG] match_field [det(CD) < 0]: 4954 img quads, 130 raw matches, 19 pairs, best log-odds 2.96 over 130 hypotheses
[DEBUG] match_field [det(CD) > 0]: 4954 img quads, 147 raw matches, 27 pairs, best log-odds 7.01 over 147 hypotheses
Error: no quad match passed verification: det(CD) > 0: best log-odds 7.01 over 147 hypotheses, det(CD) < 0: best log-odds 2.96 over 130 hypotheses (acceptance needs log-odds above 20.72, odds of 1e9)
This is the output from a 512 x 512 cutout of a larger Cygnus Wall stack, trimmed to the lines that matter. The section The hint is too far off below solves it.
--debug DIR writes two PNG files after a successful solve.
detections.png circles every detected star, green when it was matched to
the catalog and amber when it wasn’t. solve.png marks each matched
catalog star with a cyan cross and draws its residual as a magenta line,
stretched 20 times. The residuals are those of the linear fit, so the
lines show the field’s distortion pattern.
Missing header values
Error: image is missing required header: FOCALLEN
Error: no position hint: need CRVAL1/2, RA/DEC, or OBJCTRA/OBJCTDEC
The solver stops before it looks at a pixel when the header has no
position, plate scale or time. On the command line, --focal-length and
--pixel-size supply the plate scale. A missing position or time needs
the library, through the hint and epoch setters or with_metadata.
Hints and Image Metadata has examples of each.
No stars detected
Error: no stars detected
Detection found nothing that looked like a star. Check that the frame isn’t blank, a dark or bias frame, or so far out of focus that stars spread over more than 2000 pixels. A frame dominated by clouds or moonlight can also leave no star above a signal-to-noise ratio of 5.
When detection finds stars but too few, the failure shows up later as a
no quad match error. --verbose prints how many detections survived. The
M106 frame on the first page solved with 24.
No quad match passed verification
Error: no quad match passed verification: det(CD) > 0: best log-odds 7.01 over 147 hypotheses, det(CD) < 0: best log-odds 2.96 over 130 hypotheses (acceptance needs log-odds above 20.72, odds of 1e9)
The matcher tried every candidate in both orientations and none reached
the acceptance threshold of 20.72. det(CD) > 0 and det(CD) < 0 are the
normal and mirrored orientations. A best log-odds near zero, or a handful
of hypotheses, means the image and catalog stars had nothing in common.
That points to the wrong patch of sky or the wrong scale, rather than to a
match that came close.
What to try, most likely first:
- Check the plate scale. A focal length off by more than a factor of
about 2 makes the matcher look for patterns at the wrong size. Compare
FOCALLENandXPIXSZwith your optics, and remember reducers, Barlows and binning. - Check the hint. Is the header position for this frame? A crop, a mosaic panel or a frame taken during a slew can be far from it. See the next section.
- Try a deeper catalog. On a narrow field,
catalog-small.binorcatalog-standard.binmay hold too few stars. See The Star Catalog. - Raise
--max-stars. The default of 100 image stars is plenty for most frames. A field crowded with faint stars or full of false detections may need more. Matching takes longer as it grows.
The hint is too far off
The Cygnus Wall cutout above keeps the header of the stack it came from, and that header gives the center of the full stack. The cutout is about 1° from it, and its own field is only 12 arcminutes across, so the catalog search around the hint missed it.
image-solver can’t widen the search, but the library can. Set a larger
catalog search radius and turn off the check that the solution lies near
the hint:
use celestial_catalog::query::catalog::Catalog;
use celestial_images::formats::image::Image;
use celestial_solver::match_field::MatchParams;
use celestial_solver::solve::{solve, SolveParams};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("cygnus.fit")?;
let catalog = Catalog::open("catalog-standard.bin")?;
let params = SolveParams {
matching: MatchParams {
search_radius_deg: Some(1.0),
..MatchParams::default()
},
max_center_offset_fov: f64::INFINITY,
..SolveParams::default()
};
let result = solve(&img, &catalog).params(params).run()?;
println!("center: {:.4}°, {:.4}°", result.wcs.crval1, result.wcs.crval2);
println!("{} matched, log-odds {:.1}", result.pairs.len(), result.log_odds);
Ok(())
}
center: 315.1465°, 43.8118°
32 matched, log-odds 197.0
With the search radius alone, matching succeeds, but the solve stops at the center check:
initial WCS center 1.016° from hint exceeds 0.289° (1× FOV diagonal 0.289°)
A wider search costs time, because the catalog side builds quads across
the whole cone. Widen it as far as your hint is wrong, not
further. When you know the right position, passing it with hint is
faster than either.
The scale or center disagrees with the hint
Error: initial WCS plate scale 0.527"/px diverges from hint 0.222"/px by factor 2.38 (limit 2.00)
Error: initial WCS center 1.016° from hint exceeds 0.289° (1× FOV diagonal 0.289°)
The matcher found a match it believes, but the fitted scale or position
contradicts the header. The message gives the fitted value, the header
value and the limit. When the fitted value matches your optics or your
target, the header is wrong: fix it, or override it as Hints and Image
Metadata describes. The first error above came from
--focal-length 7000 on a frame taken at 2943 mm.
Both limits are in SolveParams. max_scale_factor defaults to 2 and
max_center_offset_fov to 1 diagonal. Raising them is a last resort,
because the checks are what stop a wrong header from producing a wrong
answer quietly.
A solve that succeeds but looks wrong
The log-odds test makes a false solution very unlikely, but a correct solution can still be poor. Look at these lines of the report:
- Control points under about 10 leave the fit with little to work
with, and often too few stars to fit distortion terms. Against
catalog-small.bin, the M106 frame matched 10 stars and got no distortion terms. A deeper catalog helps. - SIP RMS well above 1 pixel suggests trailed or doubled stars, or a
frame with strong distortion that order 4 can’t model.
solve.pngfrom--debugshows where the large residuals are.
In Rust, result.refinement says whether you got the refined solution.
When it’s anything other than Refinement::Refined, the solver fell back
to its first fit, or left the distortion terms out, and the value holds
the error that caused it.
Handle failures in code
SolveError has one variant per kind of failure, so a program can react
to each:
use celestial_catalog::query::catalog::Catalog;
use celestial_images::formats::image::Image;
use celestial_solver::error::SolveError;
use celestial_solver::solve::solve;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let img = Image::open("jellyfish.fit")?;
let catalog = Catalog::open("catalog-standard.bin")?;
match solve(&img, &catalog).run() {
Ok(result) => println!("solved with {} stars", result.pairs.len()),
Err(SolveError::Metadata(e)) => println!("fix the header or set it: {e}"),
Err(SolveError::NoStars) => println!("no stars found; check the exposure"),
Err(SolveError::NoMatch { reason }) => println!("no match: {reason}"),
Err(e) => return Err(e.into()),
}
Ok(())
}
fix the header or set it: image is missing required header: FOCALLEN
NoMatch covers the three checks above: no verified quad match, a scale
or center that disagrees with the hint, and a final solution that failed
verification. InvalidParameter means a value in SolveParams is out of
range, and its message names the field.
Next steps
- The image-solver Command lists every flag.
- How Solving Works explains log-odds and the checks in more depth.
The image-solver Command
Reference for the image-solver binary. Build it with the cli
feature:
cargo install --path celestial-solver --features cli
Usage
image-solver [OPTIONS] --image <IMAGE> --catalog <CATALOG>
| Flag | Meaning |
|---|---|
-i, --image PATH | The image to solve, FITS or XISF. Required. |
-c, --catalog PATH | The catalog file. Required. See The Star Catalog. |
-o, --output PATH | Write a copy of the image with the solution in its header. The extension picks the format: .fits, .fit, .fts or .xisf. |
--focal-length MM | Use this focal length instead of the FOCALLEN header. |
--pixel-size UM | Use this pixel size instead of the XPIXSZ header. |
--max-stars N | The most image stars to build quads from. Default 100. |
--debug DIR | Write detections.png and solve.png to DIR, creating it if needed. |
--verbose | Log each stage of the solve to standard error. |
-h, --help | Print the flags. |
The image must carry a position hint, an observation time and a plate scale, or the flags above must supply the plate scale. Hints and Image Metadata lists the header keywords read for each.
An --output path with another extension is rejected before the solve
starts. The output directory is created if it doesn’t exist.
Output streams and exit status
The solution report goes to standard output. Timings, --verbose logs,
wrote PATH after --output, and errors go to standard error.
The exit status is 0 when the image solved and 1 when it didn’t. A failure
prints one line that starts with Error:. When Solving
Fails explains each message.
RUST_LOG overrides the log level, for example RUST_LOG=info for the
stage timings without the debug lines.
The report
The report for the M106 frame is on Solve Your First Image. Its lines, in order:
| Line | Meaning |
|---|---|
| Creation time | When the report was made, UTC. |
| Creation software | The solver version. |
| Reference catalog | The catalog library version. |
| Linear transformation matrix | The linear part of the solution: tangent-plane offsets in degrees from report pixel coordinates. The third column is the offset of report pixel (0, 0). |
| Projection | Gnomonic (TAN-SIP) with distortion terms, Gnomonic (TAN) without. |
| Projection origin | The reference pixel, in report pixel coordinates, and its sky position. |
| Resolution | Plate scale in arcseconds per pixel. “Linear approximation” marks a solution with distortion terms, where the scale varies across the field. |
| Rotation | Angle from image up to north, in degrees, positive clockwise. (flipped) marks a mirrored image. |
| Reference system | Always ICRS. |
| Observation start time | The time the solve used, from MJD-OBS or DATE-OBS. |
| Geodetic coordinates | The observing site, when the header gives one. |
| Focal distance | The focal length the fitted scale implies for the header’s pixel size. Present when the pixel size is known. |
| Pixel size | The pixel size used, in microns. |
| Field of view | Width x height of the frame on the sky. |
| Image dimensions | Width x height in pixels. |
| Image center, Image bounds | Sky positions of the center and the four outer corners. ex and ey are the mean residual, in pixels, of the five fitted stars nearest that point. |
| SIP distortion order | The order of the distortion polynomials, followed by their coefficients. Present only when distortion terms were fitted. |
| Control points | The number of stars in the final fit. |
| Linear RMS | The RMS residual of the linear fit alone. |
| SIP RMS | The RMS residual with the distortion terms. |
| Weighted SIP RMS | The same, with each star weighted by the precision of its centroid. |
| Improvement | How much the distortion terms reduced the RMS. |
Without distortion terms, the last four lines are replaced by
RMS error and Weighted RMS.
Pixel coordinates
The report, the FITS header and the library put the first pixel at different coordinates:
| Where | Center of the first pixel |
|---|---|
| The report | (0.5, 0.5): the outer corner of the first pixel is (0, 0) |
The FITS header (CRPIX1, CRPIX2) | (1, 1) |
SolveResult::pixel_to_sky and sky_to_pixel | (0, 0) |
The M106 report puts the projection origin at (1164.5, 880.5). The same
point is CRPIX (1165, 881) in the FITS header and (1164, 880) in the
library.
What --output writes
The output is a copy of the input with its old WCS keywords removed and the new solution added:
CTYPE1/CTYPE2(RA---TAN-SIPandDEC--TAN-SIPwith distortion terms,RA---TANandDEC--TANwithout),CUNIT1/CUNIT2,CRPIX1/CRPIX2,CRVAL1/CRVAL2, theCD1_1toCD2_2matrix andLATPOLE.- With distortion terms,
A_ORDER,B_ORDERand theA_p_qandB_p_qcoefficients, plus the inverseAP_ORDER,BP_ORDER,AP_p_qandBP_p_qcoefficients for mapping sky to pixel. RADESYS = 'ICRS'.
Other keywords, including EQUINOX and EPOCH, are kept. An XISF output
also gets the solution as PCL:AstrometricSolution properties, with a
spline fitted through the matched stars, when there are at least 5 of
them.
Debug images
--debug DIR writes two PNG files, with the image stretched so faint
stars show:
detections.pngcircles every detected star: green when it was matched to a catalog star, amber when it wasn’t.solve.pngmarks each matched catalog star with a cyan cross, and draws a magenta line from the detected star along its residual, stretched 20 times. The residuals are those of the linear fit.
Pointing Models
celestial-pointing fits pointing models for equatorial telescope mounts and
applies them at the telescope.
This crate is experimental. Its API and the pointing shell’s command set
may change between releases, and it supports equatorial mounts only for now.
Why a mount needs a model
Send a mount to a star and it rarely lands on it. The polar axis is a little
off the pole, the axes aren’t quite perpendicular, the tube sags as it tips
toward the horizon, and the encoders have their own zero points. Each of those
errors moves the pointing by a predictable amount that depends on where the
telescope is aimed. A pointing model describes them as a short list of named
terms, such as ME (the polar axis is too high or too low) and CH (the
optical axis isn’t square to the declination axis).
You measure the terms by pointing at stars. For each star you record where the star really is and where the mount’s encoders say the telescope is pointing. The differences, fitted across the sky, give you each term’s size. Once you have the model, you run it backwards to find where to send the mount so the star lands in the middle of the field.
Here is a six-term fit to 98 stars from one night, in the pointing shell:
*INDAT warp-astron.dat
...
*USE IH ID NP CH ME MA
*FIT
coeff change value sigma
1 IH +8512.559 +8512.56 14.883
2 ID +7206.960 +7206.96 18.313
3 NP -22.682 -22.68 30.817
4 CH -1234.764 -1234.76 16.706
5 ME -133.523 -133.52 14.296
6 MA +64.384 +64.38 25.283
Sky RMS = 109.11
Popn SD = 112.61
Observation #61 is a weak outlier candidate.
Every value is in arcseconds. NP is smaller than its sigma, so this night’s data doesn’t support it, and the other five are measured well. Fit Your First Model walks through this output line by line.
What you get
- The standard equatorial terms and harmonics. The six basic terms, the common flexure and centering terms, and harmonic terms you build by name for errors with no physical model. Pointing Terms lists them.
- INDAT in, OUTMOD out. Observations are read from INDAT files and models are written as OUTMOD files, plain-text formats that other pointing tools also read, so you can move data and models between programs.
- A search for the terms your data supports. Automodel adds harmonics, drops weak terms and masks outliers, and logs every decision, so you can see why each term is there. See Automodel and Vetting.
- The model in both directions.
Pointerturns an ICRS target into a mount reading and a mount reading back into an ICRS direction, so a mount driver can slew with the model. See Point the Telescope with a Model. - Polar alignment. The fitted ME and MA terms become “raise the axis by this much, turn it by that much”. See Polar Alignment.
- Live runs. A
PointingRunrefits after each star, so you can watch the model settle while you’re still observing. See A Live Pointing Run. - A command shell.
pointingruns the fitting commands interactively, from a script, or in a full-screen UI with plots. See The Command Shell.
Limitations
- Equatorial mounts only. There’s no alt-azimuth mount model, so INDAT
files marked
:ALTAZor:GIMBALare rejected when they’re read. - No azimuth or elevation harmonics. Harmonic terms with the result codes S, A and E (moves across the vertical circle, in azimuth and in elevation) are rejected as unsupported terms. Harmonics in the other result codes may still take azimuth, zenith distance or elevation as their input angle.
- No mount control. The crate fits and applies models. Talking to the mount, plate solving the frames and recording encoder readings are up to your program.
- The live run’s term schedule is for German equatorial mounts. It grows
the model through the six basic terms. A fork mount can still be fitted
with any terms in the shell or with
fit.
Background and credits
The approach this crate takes comes from Patrick Wallace’s TPOINT, a telescope pointing analysis system whose origins go back to his work on the Anglo-Australian 3.9 m telescope in the 1970s. The term names and sign conventions (IH, ID, NP, CH, ME, MA and the harmonic notation), the INDAT observation format, the OUTMOD model format and the shell’s command names all follow the TPOINT manual. Keeping them means equatorial INDAT files and OUTMOD models need no conversion, and the manual’s explanations of the terms apply here too.
- P. T. Wallace, TPOINT: a telescope pointing analysis system, Version 18.20 for Unix, Tpoint Software, 10 December 2011.
celestial-pointing is an independent implementation. It isn’t affiliated with or endorsed by Tpoint Software. TPOINT is a trademark of Tpoint Software.
Where to start
- To fit a model from an INDAT file you already have, start with Fit Your First Model.
- To understand what the terms mean and which ones to fit, read Pointing Terms.
- To build a model into a mount driver, read Point the Telescope with a Model and A Live Pointing Run.
- For every shell command, the graphs and procedures, see The Command Shell.
Fit Your First Model
You have a night of pointing data in an INDAT file and you want a model you can
load into your mount software. This page fits the six basic equatorial terms
to warp-astron.dat, reads the result, finds the worst star, and saves the
model as an OUTMOD file. It takes a few minutes, first in the pointing shell
and then in Rust.
What you need
- The
pointingshell, built with theclifeature:
cargo install --path celestial-pointing --features cli
- An INDAT file. The examples use
warp-astron.datfromcelestial-pointing/tests/data: 98 stars observed from latitude +39° on 2026 April 21.
An INDAT file starts with a caption, option lines and a run record, followed by
one line per star. After a ! comment line, warp-astron.dat begins:
ASCOM Mount
:NODA
:EQUAT
+39 00 26 2026 4 21 20.55 761.74 228.00 0.60 0.5500 0.0065
14 36 55.4451 +72 03 24.120 02 50 45.3800 +105 57 19.273 10 22.219
15 21 01.1992 +71 44 28.166 03 34 46.4042 +106 16 25.098 10 23.341
05 38 55.5074 +79 14 20.514 05 40 49.7057 +77 16 22.670 10 24.698
The run record gives the site latitude, the date and the weather: temperature
in °C, pressure in hPa, height in metres, relative humidity, wavelength in µm
and lapse rate in K/m. Each star line has the star’s apparent RA and Dec, the
mount’s RA and Dec as its encoders report them, and the local sidereal time in
hours and minutes. A mount declination beyond ±90°, such as +105 57 19,
means the telescope was on the far side of the pier, beyond the pole.
Fit the six basic terms
Start the shell in line mode and give it four commands:
$ pointing --plain
*INDAT warp-astron.dat
...
*USE IH ID NP CH ME MA
*FIT
coeff change value sigma
1 IH +8512.559 +8512.56 14.883
2 ID +7206.960 +7206.96 18.313
3 NP -22.682 -22.68 30.817
4 CH -1234.764 -1234.76 16.706
5 ME -133.523 -133.52 14.296
6 MA +64.384 +64.38 25.283
Sky RMS = 109.11
Popn SD = 112.61
Observation #61 is a weak outlier candidate.
INDAT reads the file and prints it back. USE adds terms to the model at
zero, and FIT fits them by least squares. Without --plain, pointing
opens a full-screen UI that runs the same commands and adds plots beside them.
Read the result
Each row gives a term’s change in this fit, its value and its sigma, all in arcseconds. A term is measured when its value is several times its sigma. Here IH, ID, CH and ME are many sigma from zero. MA is at 2.5 sigma, so it’s probably real. NP is smaller than its sigma, so this night’s data can’t tell it from zero.
IH and ID are over two degrees. The index terms take up the zero points of the encoders, however far off they are, so a mount whose encoders were never synced to the sky shows large index terms and still fits well.
Sky RMS is the RMS distance on the sky between where the model says each star is and where it was, 109 arcseconds here. Popn SD, the population standard deviation or PSD, is the same quantity corrected for the number of terms fitted. It grows when you add a term that doesn’t earn its place, so it’s the number to watch when you compare models.
A Sky RMS of 109 arcseconds means the six basic terms leave a lot unexplained. Pointing Terms shows how to find the pattern that’s left, and Automodel and Vetting searches for it automatically.
Find the worst star
The last line of the fit names the observation least like the others. SLIST
lists each star’s residuals, and a number after it leaves out the stars below
that many arcseconds:
*SLIST 200
# HA Dec Az ZD dX dD dS dZ dR
61 +00 15 46.7 -29 47 22 183.67 68.89 -146.01 -152.43 154.40 143.87 211.06
RMS of 98 unmasked observations 57.73 92.59 109.11
Observations with dR below 200.00" are not listed
Star 61 was low in the south, 69° from the zenith, and missed by 211
arcseconds. “Weak outlier candidate” means a miss that large happens by chance
in 1 to 5 percent of typical stars, so it isn’t evidence of a bad observation
by itself. To try the fit without it, type MASK 61 and FIT again.
UNMASK 61 puts it back. The Command Shell has the
full table of outlier grades.
Save the model
OUTMOD writes the model and the statistics of the last fit:
*OUTMOD warp.mod
*END
ASCOM Mount
T 98 109.1074 42.095 -0.0498
IH +8512.5593 14.88251
ID +7206.9603 18.31300
NP -22.6823 30.81694
CH -1234.7643 16.70552
ME -133.5232 14.29577
MA +64.3841 25.28287
END
The first line is the INDAT caption. The statistics record holds the fit
method, the number of observations, the Sky RMS, and the refraction constants
A and B in arcseconds that the fit used. Each term follows with its value and
sigma. A fixed term is marked = and has no sigma.
INMOD warp.mod reads the model back into the shell. The file holds the terms
and not the mask, so mask the same stars again before you refit.
Fit from Rust
The same fit in a program reads the file, reduces each star to an observed hour angle and declination, and fits the model:
use std::path::Path;
use celestial_core::constants::ARCSEC_TO_RAD;
use celestial_pointing::astrometry::{RefractionModelKind, RunRefraction};
use celestial_pointing::fit::{fit, FitOptions};
use celestial_pointing::model::{model_from_names, Model};
use celestial_pointing::observation::ObservationSet;
use celestial_pointing::outmod::{format_outmod, OutmodFile};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let observations = ObservationSet::read_indat(
Path::new("warp-astron.dat"),
RunRefraction::FromWeather(RefractionModelKind::Ciddor),
)?;
let reduced = observations.reduce()?;
let start = Model::new(model_from_names(&["IH", "ID", "NP", "CH", "ME", "MA"]))?;
let outcome = fit(&reduced, &start, &FitOptions::default())?;
let outmod = OutmodFile {
caption: observations.caption.clone(),
method: "T".to_string(),
count: outcome.residual_x.len(),
rms: outcome.rms,
refraction_a: observations.refraction.a / ARCSEC_TO_RAD,
refraction_b: observations.refraction.b / ARCSEC_TO_RAD,
terms: outcome.model.terms().to_vec(),
sampled_psd: None,
};
std::fs::write("warp.mod", format_outmod(&outmod)?)?;
print!("{}", format_outmod(&outmod)?);
Ok(())
}
It prints the same file the shell wrote. read_indat computes the refraction
constants from the weather in the run record with the Ciddor model.
RunRefraction::Constants takes them directly instead, for a file without
weather. outcome.model holds the fitted terms, and outcome.rms and
outcome.psd the two statistics. The library API is being reshaped, so expect
these names to change.
Next steps
- To learn what each term means and how to look for the error the six basic terms miss, read Pointing Terms.
- To let the search pick the terms, read Automodel and Vetting.
- To use the saved model at the telescope, read Point the Telescope with a Model.
- For the graphs and the full command list, see The Command Shell.
Pointing Terms
A pointing model is a list of terms, and each term is one way a mount can be built or set up wrong. Fitting tells you how big each error is. Choosing which terms to fit is the part that takes judgment: too few and a real error is left in the residuals, too many and the fit starts explaining noise. This page describes each term and then how to choose.
Every term is a coefficient in arcseconds. h and d are the hour angle and
declination, and Z is the zenith distance. The formulas give each term’s
effect on the pointing when the errors are small.
The six basic terms
Almost every equatorial model starts with these six:
| Term | Error | Effect |
|---|---|---|
IH | hour-angle index error: the zero point of the hour-angle encoder | dh = IH |
ID | declination index error: the zero point of the declination encoder | dd = ID |
CH | collimation error: the optical axis isn’t square to the declination axis | dh = CH sec d |
NP | the declination axis isn’t square to the polar axis | dh = NP tan d |
ME | the polar axis is too high or too low | dh = ME sin h tan d, dd = ME cos h |
MA | the polar axis points east or west of the pole | dh = −MA cos h tan d, dd = MA sin h |
IH, CH and NP all move the telescope in hour angle, and they differ only in how the move grows toward the pole: constant, sec d and tan d. To separate them, the stars need a wide spread in declination. ME and MA are the polar alignment errors, and Polar Alignment turns them into adjustments.
Flexure and other physical terms
These describe errors that have a known mechanical cause:
| Term | Error | Effect |
|---|---|---|
TF | tube flexure, the tube sagging under gravity | the pointing drops by TF sin Z |
TX | tube flexure that grows faster toward the horizon | the pointing drops by TX tan Z |
TX10 | TX with tan Z capped at its value at Z = 80° | as TX, limited near the horizon |
FLOP | a constant drop, whatever the direction | the pointing drops by FLOP |
FO | fork flexure | dd = FO cos h |
DAF | declination axis flexure | dh = −DAF (sin φ tan d + cos φ cos h), φ the latitude |
HCES, HCEC | the hour-angle encoder is off center | dh = HCES sin h, dh = HCEC cos h |
DCES, DCEC | the declination encoder is off center | dd = DCES sin d, dd = DCEC cos d |
DNP | NP that changes with hour angle | dh = DNP sin h tan d |
X2HC | collimation that changes twice per turn of the polar axis | dh = X2HC cos 2h sec d |
TF and TX are the two common forms of flexure. Fit one of them, not both: both grow from zero at the zenith, so the fit can barely tell them apart.
Harmonic terms
Some errors have no tidy physical model: a periodic error in a gear, a cable that drags at one end of the travel. Harmonic terms fit those with sines and cosines. You build a harmonic’s name from parts:
H <result> <S|C><angle>[multiple] ...
The result code says what the term moves:
| Code | Moves | Like |
|---|---|---|
H | hour angle | IH |
D | declination | ID |
X | east-west, growing as sec d | CH |
P | hour angle, growing as tan d | NP |
L | as the polar axis azimuth does | MA |
U | as the polar axis elevation does | ME |
Z | down, toward the horizon | FLOP |
Then come one or more factors. S or C picks sine or cosine, and the angle
code picks its input: H hour angle, D declination, A azimuth, Z zenith
distance, E elevation or Q parallactic angle. A whole number after the
angle multiplies it, and % halves it.
| Name | Reads as |
|---|---|
HDSH | declination moves by HDSH · sin h |
HDCD6 | declination moves by HDCD6 · cos 6d |
HHSD | hour angle moves by HHSD · sin d |
HDCH3CD8 | declination moves by HDCH3CD8 · cos 3h · cos 8d |
HHSH% | hour angle moves by HHSH% · sin(h / 2) |
Harmonics usually come in sine and cosine pairs at the same frequency, such as
HDSD and HDCD, because you don’t know the phase of a periodic error in
advance. The pair fits any phase.
Order matters
The model applies its terms in the order they’re listed, the way the errors
build up in the mount, from the encoders out to the sky. Each term is
evaluated at the place the terms before it produced. USE adds terms at the
end of the list. In an OUTMOD file, a term marked & is evaluated at the same
place as the term before it.
The six basic terms don’t depend on where the telescope points, so their order
doesn’t change the fit. Terms that do depend on it, such as TF and the
harmonics, see a slightly different place in a different order. On
warp-astron.dat, fitting HDSD HDCD TF after the six basic terms gives HDSD
−160.19 arcseconds. Putting them first gives −153.92, a difference well inside
the 19-arcsecond sigma. Keep the basic terms first, as automodel does, so the
other terms are evaluated close to where the telescope really points.
Choose the terms
Start with the six basic terms and fit:
*USE IH ID NP CH ME MA
*FIT
Then look at three things.
Sigmas. A term whose value is less than about two sigmas isn’t measured by
this data. MVET ranks the terms by value over sigma and removes weak ones for
you. Automodel and Vetting shows it.
Residual plots. A pattern in the residuals is an error the model doesn’t
describe yet. On warp-astron.dat, the declination residuals of the six-term
fit swing with declination:
*G D D
G D D
dD declination (arcsec)
+200 ┤
│ ⢀ ⠠ ⢀ ⠄ ⡀
│ ⢂ ⡀ ⠠⠁⢀
│ ⢀⠠⡄ ⠁⠠ ⢀⡀⢀ ⠂ ⠂
│ ⠠ ⠁⡀⢀ ⢀⢀ ⠐ ⡀
+100 ┤ ⠁ ⠄ ⠂
│ ⠁⠠ ⠃ ⠁⢀ ⢀
│ ⢀ ⠠⢀
│ ⢀ ⡀ ⠐ ⢀
│ ⠠⠄ ⠔⠂ ⠠⠐ ⢂
0 ┤⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁⢄⠁ ⠁ ⠃ ⠃ ⠉⡀⠑⠐⠁⠐⠋⡀⡁⢀⠁ ⠁⠡⠁ ⠁ ⠁ ⠁ ⠁
│ ⠈ ⠂ ⠂ ⠐ ⠐ ⠄
│ ⢀ ⢀ ⠈
│ ⠐ ⡀ ⠐
│ ⠐ ⠘ ⠁ ⡀
-100 ┤ ⠁
│ ⠈ ⠐
│ ⠠ ⠂
│ ⠠
│
-200 ┤
└┬─────────┬──────────┬──────────┬─────────┬──────────┬──────────┬
-90 -60 -30 0 30 60 90
declination (deg)
98 observations, scale 200 arcsec
Most stars south of the equator miss low, and most stars from +30° to +60° miss high. A
declination error that follows declination is a job for HDSD and HDCD:
*USE HDSD HDCD
*FIT
coeff change value sigma
1 IH +7.173 +8519.73 9.001
2 ID +50.050 +7257.01 12.203
3 NP -92.668 -115.35 22.477
4 CH -5.126 -1239.89 10.042
5 ME +144.799 +11.28 20.803
6 MA +58.196 +122.58 15.861
7 HDSD -158.005 -158.01 18.445
8 HDCD -167.530 -167.53 19.667
Sky RMS = 65.58
Popn SD = 68.44
Observation #2 is a possible outlier candidate.
The Sky RMS drops from 109 to 66 arcseconds, and both new terms are about 8 sigma.
What the other terms did. ME went from −134 to +11 arcseconds, and NP from −23 to −115. Over the stars observed, the harmonics and the basic terms overlap, so the fit traded one for the other. The residuals got smaller, but ME no longer reads as the polar axis error. That’s the price of a flexible model: the more terms you add, the less each physical term means on its own. When you need a physical term’s value, as for polar alignment, read it from a model that doesn’t have harmonics competing with it.
How many stars you need
A fit needs more observations than floating terms, so that the PSD is defined. That’s a floor, not a target. Each star gives two residuals, and a model with a dozen terms wants several dozen stars spread over the sky to measure them well. On a German equatorial mount, take stars on both sides of the pier.
Next steps
- To rank the terms and let the search add harmonics, read Automodel and Vetting.
- For the other residual plots,
G,GSCATandGDIST, see The Command Shell.
Automodel and Vetting
Picking terms by hand means fitting, plotting, adding a pair of harmonics, fitting again and deciding whether the new terms are real. That’s fine for one night. For a run with a hundred stars and a dozen candidate harmonics, you want the program to try them and tell you what it found. Two commands do that:
MVETranks the terms you already have and removes the weak ones.FAUTObuilds a model from scratch. It adds the terms the data supports, removes the ones it doesn’t, and masks outliers. The search is called automodel.
Both use the same test for a weak term: its value is under the significance threshold, two sigma by default, or removing it doesn’t raise the PSD. A term that fails the second test isn’t paying for itself, because the fit is as good without it.
Rank the terms with MVET
Fit the six basic terms to warp-astron.dat, then ask MVET to remove at most
one term:
*INDAT warp-astron.dat
...
*USE IH ID NP CH ME MA
*FIT
...
*MVET 1
Model terms, strongest first:
IH
ID
CH
ME
MA
| NP
Model term NP is the weakest, and has been removed.
IH
ID
CH
ME
MA
No weak terms detected.
The | marks a weak term. MVET removed NP, refitted the other five and ranked
them again. With no number, MVET ranks the terms without removing anything,
which is a quick way to check a model you built by hand. MVET leaves fixed
terms alone.
Build a model with FAUTO
FAUTO starts from the basic terms and searches from there. Its log has one
line per decision:
*INDAT warp-astron.dat
...
*FAUTO
start IH ID CH NP ME MA psd 112.609
fix at zero NP (0.7 sigma); psd 112.311
add HDSD -172.64+-20.53, HDCD -110.74+-18.31; psd 112.311 -> 76.659
add DAF +254.46+-37.15; psd 76.659 -> 63.400
add HHSD -110.15+-27.93, HHCD -0.71+-24.56; psd 63.400 -> 59.385
remove HHCD (0.0 sigma); psd 59.050
add HDSH4 -17.43+-8.65, HDCH4 -27.69+-8.27; psd 59.050 -> 55.590
fix at zero MA (1.9 sigma); psd 56.319
add HDSD6 -1.65+-7.43, HDCD6 +20.70+-7.75; psd 56.319 -> 55.004
remove HDSD6 (0.2 sigma); psd 54.701
add TF -58.40+-23.65; psd 54.701 -> 53.382
fix at zero ME (0.0 sigma); psd 53.075
mask obs 98; psd 49.031
Masked observations: 98
coeff change value sigma
1 IH +8521.26 7.655
2 ID +7298.46 7.269
3 CH -1016.47 25.291
4 NP +0.00
5 ME +0.00
6 MA +0.00
7 HDSD -124.72 12.539
8 HDCD -161.97 9.388
9 DAF +325.76 29.809
10 HHSD -172.32 18.083
11 HDSH4 -31.08 7.143
12 HDCH4 -29.79 6.847
13 HDCD6 +27.78 7.079
14 TF -55.74 15.502
Sky RMS = 46.17
Popn SD = 49.03
Read the log top to bottom:
- start fits the basic model. Its size depends on the number of stars: two terms for one or two stars, up to all six from six stars on.
- add scores every candidate with a quick estimate of its significance, fits the five best in full, and adds the most promising one whose fit lowers the PSD and reaches the significance threshold. The line gives each new term’s value and sigma. The candidates are TF, TX10, DAF and sine/cosine harmonic pairs in hour angle and declination. A harmonic comes in as a pair, and a weak half can be removed later, as HHCD was here.
- remove drops a term that turned weak after another term came in.
- fix at zero drops a basic term but leaves it in the model, fixed at zero, so you can see it was tried. IH and ID are never dropped.
- mask obs runs when nothing more can be added or removed. If the star with the largest leave-one-out residual is further out than chance allows, the search masks it and carries on with the candidates not yet tried.
Over the search, the PSD went from 112.6 to 49.0 arcseconds, and star 98 was masked. The search tries each candidate at most once, so it always ends.
FAUTO 4 offers harmonics up to the fourth instead of the eighth, and
FAUTO 8 3 keeps only terms of 3 sigma or more. FAUTO CROSS also offers
single cross harmonics such as HDCH3CD8, which multiply an hour-angle factor
by a declination factor. CROSS multiplies the number of candidates, so the
search takes longer.
Check the result
A search that adds terms until the PSD stops falling can fit noise. LOO
checks for that. For each star it estimates the fit without that star and
measures how far the star lands from that fit’s prediction. The RMS of
those misses is the jackknife PSD:
*LOO
...
Jackknife PSD = 49.11
The jackknife PSD of 49.11 is close to the PSD of 49.03, so the model predicts stars it wasn’t fitted to about as well as the ones it was. A jackknife PSD well above the PSD means some terms describe this night’s noise and won’t help tomorrow.
Automodel and the physical terms
FAUTO fixed ME and MA at zero on this data. That doesn’t mean the polar axis is aligned: the six-term fit measured ME at more than 9 sigma. Over these stars the harmonics overlap with ME and MA, and once they were in, ME and MA fell below two sigma. The model points as well, but its ME and MA no longer measure the polar axis. Read polar alignment from a basic fit, as Polar Alignment does.
From Rust
automodel runs the same search on a reduced observation set:
use std::path::Path;
use celestial_pointing::astrometry::{RefractionModelKind, RunRefraction};
use celestial_pointing::automodel::{automodel, AutomodelOptions};
use celestial_pointing::observation::ObservationSet;
use celestial_pointing::progress::NoProgress;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let observations = ObservationSet::read_indat(
Path::new("warp-astron.dat"),
RunRefraction::FromWeather(RefractionModelKind::Ciddor),
)?;
let result = automodel(
&observations.reduce()?,
&AutomodelOptions::default(),
&mut NoProgress,
)?;
let names: Vec<&str> = result.fit.model.terms().iter().map(|t| t.name.as_str()).collect();
println!("terms: {}", names.join(" "));
println!("masked: {:?}", result.masked);
println!("Sky RMS {:.2}, PSD {:.2}", result.fit.rms, result.fit.psd);
Ok(())
}
terms: IH ID CH NP ME MA HDSD HDCD DAF HHSD HDSH4 HDCH4 HDCD6 TF
masked: [ObsId(98)]
Sky RMS 46.17, PSD 49.03
result.log holds the log lines. To watch them as the search writes them, or
to cancel a long search, pass your own Progress instead of NoProgress.
Its line method receives each log line, and the search stops with
Error::Cancelled when cancelled returns true.
MVET has no function of its own. Run it, or any other shell command, on a
Session with commands::execute:
use celestial_pointing::commands::{execute, CommandOutput};
use celestial_pointing::progress::NoProgress;
use celestial_pointing::session::Session;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut session = Session::default();
execute(&mut session, "INDAT", &["warp-astron.dat"], &mut NoProgress)?;
execute(&mut session, "USE", &["IH", "ID", "NP", "CH", "ME", "MA"], &mut NoProgress)?;
execute(&mut session, "FIT", &[], &mut NoProgress)?;
if let CommandOutput::Mvet(report) = execute(&mut session, "MVET", &["1"], &mut NoProgress)? {
println!("removed {:?}", report.removed);
for term in &report.rankings[0] {
println!("{:4} {:5.1} sigma{}", term.name, term.strength, if term.weak { " weak" } else { "" });
}
}
Ok(())
}
removed ["NP"]
IH 572.0 sigma
ID 393.5 sigma
CH 73.9 sigma
ME 9.3 sigma
MA 2.5 sigma
NP 0.7 sigma weak
Next steps
- To use the model at the telescope, read Point the Telescope with a Model.
- For the graphs that show what a model leaves behind, see The Command Shell.
Point the Telescope with a Model
A fitted model is only useful once your mount driver applies it. Two questions
come up at the telescope. Where do I send the mount so a target lands in the
middle of the field? And where is the telescope really pointing, given what the
encoders say? Pointer answers both from an OUTMOD model, your site and the
time.
Find the mount reading for a target
This loads the model saved in Fit Your First Model and finds where to send the mount for Arcturus, on both sides of the pier:
use std::path::Path;
use std::sync::Arc;
use celestial_coords::eop::EopProvider;
use celestial_coords::frames::icrs::ICRSPosition;
use celestial_core::angle::Angle;
use celestial_core::constants::ARCSEC_TO_RAD;
use celestial_core::location::Location;
use celestial_pointing::astrometry::Refraction;
use celestial_pointing::frames::PierSide;
use celestial_pointing::model::Model;
use celestial_pointing::outmod::read_outmod;
use celestial_pointing::pointer::Pointer;
use celestial_pointing::sexagesimal::signed_sexagesimal;
use celestial_time::scales::utc::utc_from_calendar;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let outmod = read_outmod(Path::new("warp.mod"))?;
let pointer = Pointer {
model: Model::new(outmod.terms)?,
site: Location::from_degrees(39.0072, -104.881, 1840.0)?,
refraction: Refraction::new(
outmod.refraction_a * ARCSEC_TO_RAD,
outmod.refraction_b * ARCSEC_TO_RAD,
)?,
eop: Some(Arc::new(EopProvider::bundled()?)),
};
// Arcturus, ICRS
let arcturus = ICRSPosition::new(
Angle::from_hours(14.0 + 15.0 / 60.0 + 39.672 / 3600.0),
Angle::from_degrees(19.0 + 10.0 / 60.0 + 56.67 / 3600.0),
)?;
let utc = utc_from_calendar(2026, 4, 22, 5, 30, 0.0)?;
let bare = Pointer { model: Model::default(), ..pointer.clone() };
let plain = bare.mount_for(&arcturus, &utc, PierSide::Normal)?;
println!(
"no model: HA {} Dec {}",
signed_sexagesimal(Angle::from_radians(plain.h()).hours(), 1)?,
signed_sexagesimal(Angle::from_radians(plain.d()).degrees(), 0)?,
);
for side in [PierSide::Normal, PierSide::BeyondPole] {
let reading = pointer.mount_for(&arcturus, &utc, side)?;
println!(
"{side:?}: HA {} Dec {}",
signed_sexagesimal(Angle::from_radians(reading.h()).hours(), 1)?,
signed_sexagesimal(Angle::from_radians(reading.d()).degrees(), 0)?,
);
let back = pointer.sky_for(reading, &utc)?;
println!(
" points at {:.3}\" from the target",
arcturus.angular_separation(&back).arcseconds()
);
}
Ok(())
}
no model: HA -01 45 15.0 Dec +19 03 44
Normal: HA -01 53 14.9 Dec +17 06 07
points at 0.000" from the target
BeyondPole: HA +10 03 49.8 Dec +158 53 39
points at 0.000" from the target
mount_for takes the target from ICRS to its apparent place at the site and
time, adds refraction, and runs the model backwards to find the mount reading
that puts the star on the optical axis. With an empty model you get the
refracted apparent place, and the difference between the first two lines is
the model’s correction: eight minutes of hour angle and two degrees of
declination, most of it the index errors.
sky_for goes the other way. Given a mount reading, it returns the ICRS
direction the telescope points at. Here it returns Arcturus to within a
thousandth of an arcsecond, because it’s the inverse of mount_for. Use it to
show the telescope’s true position in a planetarium program, or to turn the
encoders’ position into the center of a frame.
The parts of a Pointer
modelis the fitted model.Model::newchecks every term name, so a model with a term the crate doesn’t support fails here, not at the telescope.siteis the observatory’s location. The model was fitted at one latitude, so use it at that site.refractionholds the refraction constants A and B in radians. The OUTMOD statistics record stores the ones the fit used, in arcseconds, and using the same ones at the telescope keeps the model consistent with its fit.eopgives UT1−UTC and polar motion for each time. WithNonethey’re taken as zero, which moves the hour angle by up to about 0.9 seconds of time. A time outside the provider’s table is an error. Earth Orientation Parameters covers the bundled table and how to refresh it.
Pier sides and mount readings
A German equatorial mount can reach most stars from either side of the pier.
mount_for doesn’t choose: you pass PierSide::Normal or
PierSide::BeyondPole, because the choice depends on your mount’s limits and
where it is now.
A MountReading holds the hour angle and the mechanical declination in
radians. Beyond the pole, the mechanical declination is past ±90°, and the
hour angle is about twelve hours away from the star’s. That’s why the second reading
above is +10 03 49.8 and +158 53 39 for a star at declination +19°.
reading.pier_side() tells you which side a reading is on.
Raw encoder readings
When you record observations for the next fit, record the raw encoder reading, with no pointing model applied, neither this one nor the mount’s own. A fit measures the mount’s errors from scratch. If the readings already include a correction, the fit measures what’s left of the errors after that correction, and the new model can’t stand on its own.
Next steps
- To refit the model while you observe, read A Live Pointing Run.
- To fix the polar axis instead of modelling it, read Polar Alignment.
Polar Alignment
A pointing model can correct a misaligned polar axis, but tracking can’t: a
mount whose axis is off the pole drifts in declination during a long exposure,
whatever the model says. ME and MA measure the misalignment, so a pointing run
doubles as a polar alignment check. PolarAlignment turns the two terms into
the adjustments you make with the mount’s altitude and azimuth bolts.
From a fit to adjustments
Fit the six basic terms and pass the fit and the INDAT run record to
PolarAlignment::from_fit:
use std::path::Path;
use celestial_pointing::astrometry::{RefractionModelKind, RunRefraction};
use celestial_pointing::fit::{fit, FitOptions};
use celestial_pointing::model::{model_from_names, Model};
use celestial_pointing::observation::ObservationSet;
use celestial_pointing::polar_alignment::PolarAlignment;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let observations = ObservationSet::read_indat(
Path::new("warp-astron.dat"),
RunRefraction::FromWeather(RefractionModelKind::Ciddor),
)?;
let start = Model::new(model_from_names(&["IH", "ID", "NP", "CH", "ME", "MA"]))?;
let outcome = fit(&observations.reduce()?, &start, &FitOptions::default())?;
let alignment =
PolarAlignment::from_fit(&outcome, &observations.run, RefractionModelKind::Ciddor)?;
println!("ME target {:+.1}\"", alignment.me_target);
if let Some(raise) = alignment.raise_polar_axis {
println!("raise the polar axis {:+.1}\" +- {:.1}\"", raise.arcsec, raise.sigma);
}
if let Some(turn) = alignment.rotate_anticlockwise {
println!("turn anticlockwise {:+.1}\" +- {:.1}\"", turn.arcsec, turn.sigma);
}
Ok(())
}
ME target -51.8"
raise the polar axis -81.7" +- 14.3"
turn anticlockwise +82.9" +- 32.5"
For this mount, lower the polar axis by about 82 arcseconds and turn it anticlockwise, seen from above, by about 83 arcseconds. A negative amount reverses the direction. The sigmas come from the fit: the elevation adjustment is at almost 6 sigma, and the azimuth one at 2.5 sigma. An adjustment smaller than about twice its sigma isn’t measured well enough to be worth making.
Why the ME target isn’t zero
Refraction lifts every star, and the celestial pole with them, so the pole
you’d see through the telescope is above the true pole. The polar axis is
best aligned with that raised pole, so an aligned mount’s ME is not zero but
me_target: minus the lift in the northern hemisphere, plus the lift in the
southern. PolarAlignment computes the lift from the run’s weather and
latitude, here 51.8 arcseconds at latitude +39°. The ideal MA is zero in both
hemispheres.
raise_polar_axis is the distance from the fitted ME to that target, and
rotate_anticlockwise is MA divided by the cosine of the latitude, because a
turn in azimuth moves the axis less, measured on the sky, the higher the pole
is.
When there’s no answer
- An adjustment is
Nonewhen its term isn’t in the model or is fixed. FAUTO can fix ME and MA at zero when harmonics take up their signal, so read polar alignment from a basic six-term fit, not from an automodel. Automodel and Vetting shows an example. from_fitfails withError::MissingWeatherwhen the run record has no temperature, or neither pressure nor height, because the lift depends on them.- It fails with
Error::PolarAlignmentLatitudewhen the pole is less than 10° above the horizon. That close to the horizon the refraction formula isn’t reliable enough to set the target.
After you adjust
Moving the polar axis changes ME and MA, so the old model no longer fits the mount. Take a new run, even a short one, and fit again. Repeat until the adjustments are inside their sigmas.
Next steps
- To take that new run star by star and watch the model settle, read A Live Pointing Run.
A Live Pointing Run
Fitting after the night is over tells you whether the run was any good when
it’s too late to take more stars. A live run refits after every star. You see
the model settle as the stars come in, you see how far each new star landed
from where the current model predicted, and you can stop when the predictions
are good enough. PointingRun does this in a mount driver: you give it each
star and the mount’s encoder reading, and it hands back the refitted model.
Simulate a run
The example below runs ten stars through a simulated mount. The mount’s errors are a known six-term model, and each “observation” is the encoder reading that puts the star in the middle of the field, plus a couple of arcseconds of centering error. That lets you compare what the run fits with the truth. At a real telescope, the encoder reading comes from the mount after you’ve centered the star or plate solved the frame.
use celestial_coords::frames::icrs::ICRSPosition;
use celestial_core::angle::Angle;
use celestial_core::constants::ARCSEC_TO_RAD;
use celestial_core::location::Location;
use celestial_pointing::astrometry::{RefractionModelKind, RunRefraction};
use celestial_pointing::frames::{MountReading, PierSide};
use celestial_pointing::model::{model_from_names, Model};
use celestial_pointing::observation::ObsId;
use celestial_pointing::pointer::Pointer;
use celestial_pointing::pointing_run::PointingRun;
use celestial_pointing::run_params::RunWeather;
use celestial_time::scales::utc::utc_from_calendar;
// (name, RA hours, Dec degrees), ICRS
const STARS: [(&str, f64, f64); 10] = [
("Regulus", 10.1395, 11.9672),
("Dubhe", 11.0621, 61.7510),
("Pollux", 7.7553, 28.0262),
("Spica", 13.4199, -11.1613),
("Alphard", 9.4598, -8.6586),
("Alkaid", 13.7923, 49.3133),
("Procyon", 7.6550, 5.2250),
("Arcturus", 14.2610, 19.1824),
("Kochab", 14.8451, 74.1555),
("Denebola", 11.8177, 14.5721),
];
// Centering errors in arcseconds, standing in for the observer's.
const NOISE: [(f64, f64); 10] = [
(1.2, -0.8), (-2.1, 0.4), (0.3, 1.9), (-0.7, -1.5), (1.8, 0.2),
(-0.4, -2.2), (2.3, 1.1), (-1.6, 0.9), (0.5, -0.3), (-1.1, 1.4),
];
fn main() -> Result<(), Box<dyn std::error::Error>> {
let weather = RunWeather {
temperature_c: Some(8.0),
pressure_hpa: Some(812.0),
..RunWeather::default()
};
let mut run = PointingRun::new(
Location::from_degrees(39.0072, -104.881, 1840.0)?,
Some((2026, 4, 22)),
weather,
RunRefraction::FromWeather(RefractionModelKind::Ciddor),
)?;
// The errors of the simulated mount, in arcseconds.
let mut truth = model_from_names(&["IH", "ID", "NP", "CH", "ME", "MA"]);
for (term, value) in truth.iter_mut().zip([300.0, -200.0, 20.0, 100.0, -80.0, 45.0]) {
term.value = value;
}
let mount = Pointer { model: Model::new(truth)?, ..run.pointer(None) };
for (n, ((name, ra, dec), (nx, nd))) in STARS.iter().zip(NOISE).enumerate() {
let star = ICRSPosition::new(Angle::from_hours(*ra), Angle::from_degrees(*dec))?;
let utc = utc_from_calendar(2026, 4, 22, 4, 2 * n as u8, 0.0)?;
// East of the meridian the telescope is beyond the pole.
let east = mount.mount_for(&star, &utc, PierSide::Normal)?.h() < 0.0;
let side = if east { PierSide::BeyondPole } else { PierSide::Normal };
let exact = mount.mount_for(&star, &utc, side)?;
let encoder = MountReading::new(
exact.h() + nx * ARCSEC_TO_RAD,
exact.d() + nd * ARCSEC_TO_RAD,
)?;
let observation = run.observation(ObsId(n + 1), &star, &utc, None, encoder)?;
let step = run.add(observation)?;
let miss = match step.predicted_miss {
Some(miss) => format!("{miss:7.1}\""),
None => " -".to_string(),
};
let names: Vec<&str> = step.refit.model.terms().iter().map(|t| t.name.as_str()).collect();
let rms = step.refit.fit.as_ref().map_or(0.0, |fit| fit.rms);
println!("{:2} {name:9} miss {miss} rms {rms:5.2} {}", n + 1, names.join(" "));
for line in &step.refit.log {
println!(" {line}");
}
}
for term in run.model().terms() {
println!("{:3} {:+8.2} +- {:.2}", term.name, term.value, term.sigma.unwrap_or(0.0));
}
std::fs::write("run.dat", run.to_indat()?)?;
Ok(())
}
1 Regulus miss - rms 0.00 IH ID
2 Dubhe miss 247.9" rms 146.68 IH ID
3 Pollux miss 61.8" rms 62.38 IH ID CH
4 Spica miss 127.4" rms 5.30 IH ID CH ME MA
5 Alphard miss 16.2" rms 7.36 IH ID CH ME MA
6 Alkaid miss 7.7" rms 1.28 IH ID NP CH ME MA
7 Procyon miss 1.3" rms 1.25 IH ID NP CH ME MA
8 Arcturus miss 1.6" rms 1.27 IH ID NP CH ME MA
9 Kochab miss 0.9" rms 1.23 IH ID NP CH ME MA
10 Denebola miss 2.4" rms 1.33 IH ID NP CH ME MA
IH +299.75 +- 0.54
ID -199.89 +- 0.74
NP +21.48 +- 1.36
CH +98.61 +- 0.58
ME -80.24 +- 0.52
MA +44.49 +- 1.18
Each line is one star: the miss the model had predicted before that star was added, the Sky RMS after the refit, and the terms in the model. After one star the Sky RMS is zero, because two terms fit its two residuals exactly. The fitted terms end up within about 1.5 arcseconds of the simulated mount’s errors, which is the size of the centering errors.
How the model grows
A model with six terms can’t be fitted to two stars, so the run grows the model with the number of stars kept:
| Stars kept | Terms tried |
|---|---|
| 1, 2 | IH ID |
| 3 | IH ID CH |
| 4, 5 | IH ID CH ME MA |
| 6 or more | IH ID NP CH ME MA |
From the third star on, each refit vets the model: a term below 2 sigma, or
whose removal doesn’t raise the PSD, is dropped. If vetting drops ID, ID is
added back for the last fit, because a declination zero point is always there.
step.refit.log lists each decision, and was empty in this run because every
term was strong enough to keep.
A star below 10° elevation, or within 0.2° of the zenith or a celestial pole,
is kept in the run but not fitted: step.rejected is true and the model stays
as it was.
The schedule only grows through the six basic terms, which suit a German
equatorial mount. To add flexure or harmonics once enough stars are in, call
run.automodel(&AutomodelOptions::default()). It searches as
FAUTO does and makes the result the run’s model. The stars
it masks join the run’s mask.
Read the predicted miss
step.predicted_miss is the distance in arcseconds between where the star
really was and where the model before this star said the mount was pointing.
It’s the miss you would have seen if you had slewed to the star with that
model. It’s None for the first star, when there’s no model yet.
In the run above the miss falls from 248 arcseconds at the second star to 1 or 2 arcseconds from the seventh on, once NP is in the model. That’s the signal to stop: more stars won’t make the pointing better than the centering errors.
A large miss on one star, when the stars around it were predicted well, usually
means a bad observation: a misidentified star or a mount that hadn’t settled.
run.mask(ObsId(n)) leaves it out and refits, and run.unmask puts it back.
Use the model during the run
run.pointer(eop) returns a Pointer with the run’s current
model, site and refraction, so the driver can slew to the next star with the
best model so far. The encoder reading you record for that star must still be
the raw one. The run measures the mount’s errors from scratch, so a reading
with the model applied would measure only what the model missed.
Save the run
run.to_indat() returns the run as INDAT text, and the example writes it to
run.dat. The pointing shell reads it like any other INDAT file, so you can
look at the plots, try other terms or run FAUTO after the night is over:
*INDAT run.dat
...
*USE IH ID NP CH ME MA
*FIT
coeff change value sigma
1 IH +299.755 +299.75 0.539
2 ID -199.892 -199.89 0.741
3 NP +21.483 +21.48 1.356
4 CH +98.611 +98.61 0.581
5 ME -80.243 -80.24 0.516
6 MA +44.485 +44.49 1.177
Sky RMS = 1.33
Popn SD = 2.10
Observation #6 is a very weak outlier candidate.
The INDAT file stores the run’s observations, not its mask. Mask the same stars again in the shell.
Next steps
- To turn the fitted ME and MA into polar axis adjustments, read Polar Alignment.
- For the plots and the other shell commands, see The Command Shell.
The Command Shell
You’ve pointed the mount at a few dozen stars and saved the run as an INDAT
file. Now you want to know which pointing terms the data supports, how well
they fit, and which stars don’t belong. pointing is a command shell for that
job. It reads the observations, fits the terms you ask for, lets you look at
the residuals, and writes the model as an OUTMOD file.
Pointing models here are for equatorial mounts. Alt-azimuth mounts aren’t
supported yet, and INDAT files marked :ALTAZ or :GIMBAL are rejected.
Build the shell with the cli feature:
cargo install --path celestial-pointing --features cli
Starting the Shell
| Command | Reads commands from |
|---|---|
pointing | the terminal, in the full-screen UI |
pointing --plain | the terminal, one line at a time after a * prompt |
pointing run.txt | the file run.txt |
pointing < run.txt | standard input |
pointing opens the full-screen UI (see The Full-Screen UI)
when both standard input and standard output are terminals. Otherwise, and
with --plain, it runs in line mode, which prints exactly what a script
prints.
In a script, the shell prints each line after a * before it runs it. A
failing line prints Error: ... and the script goes on to the next line, so
one typo doesn’t throw away the rest of the run. The exit status is 1 when any
line failed.
*foo
Error: unknown command: foo
Line Editing and Completion
In line mode at a terminal, the shell edits lines with the usual readline keys: the
arrow keys, Ctrl-A and Ctrl-E, Ctrl-R to search the history. History is
saved in ~/.celestial_pointing_history, read from the HOME environment
variable. Without HOME, the shell says so once and keeps no history.
Ctrl-C drops the line being typed, and Ctrl-D leaves the shell.
Tab completes the word before the cursor. A second Tab lists the choices when there is more than one.
| After | Tab completes |
|---|---|
| the prompt | command names, in any case |
. | procedure names |
USE, LOSE, FIX, UNFIX | term names, and the terms in the model |
CALL | procedure names |
INDAT, INMOD, OUTMOD, FLIST, INPRO, GC P, GC B | file and directory names |
Harmonic terms complete one factor at a time. HD and Tab lists HDSH,
HDCH, HDSD and the other sine and cosine factors, and HDSH and Tab
lists the second factors. Type the multiple, such as 2 or %, by hand.
A path that starts with " stays quoted, so file names with spaces work:
*INDAT "runs/april n<Tab>
*INDAT "runs/april night.dat"
Scripts and piped input are read as plain text, with no editing.
The Full-Screen UI
The full-screen UI runs every line exactly as line mode does. The session
pane on the left shows the same text a script prints, with each line after
a *, and the input line is under it. The sidebar on the right shows plots
and tables of the current fit. The status bar at the bottom shows the INDAT
caption, the observation, mask and term counts, and the Sky RMS and PSD of
the last fit.
┌ Session ─────────────────────────────────┐┌──────────────────────────────────┐
│*USE IH ID CH ME MA ││ GSCAT G D H GDIST Model O│
│*FIT ││dD north-south (arcsec) │
│ ││+2 ┤ ⢀⡠⠴⠒⠊⠉⠉⠍⠉⠑⠒⠦⢄⡀ │
│ coeff change value sig││ │ ⢀⡠⠚⠁ ⠅• ⠈⠓⢄⡀ │
│ ││ │ ⣠⠊ ⠅ • ⠑⣄ │
│ 1 IH +299.786 +299.79 0.7││ │ ⡰⠁ ⣠⠴⠒⠒⠗⠒⠦⣄ ⠈⢆ │
│ 2 ID -200.299 -200.30 0.7││ │⢰⠃ ⣠⠋ ⢀•⣅⡀ ⠙⣄ ⠘⡆ │
│ 3 CH +100.232 +100.23 0.5││ │⡎ •⠃ ⢀⡔⠉•⠅⠉⢢⡀ ⠘⡆ ⢱ │
│ 4 ME -79.899 -79.90 0.6││ 0 ┤⡇⠄⠄⠄⠄⠄⢼⠄⠄⢼⠄⠄⠄⡥⠠⠠⡧⠠⠠⡧⠠⠠⠠⠠⠠⢸ │
│ 5 MA +1.423 +1.42 0.9││ │⢇ ⠸⡄ ⠈⠣⣀ ⡂⣀⠜⠁ ⢠⠇ ⡸ │
│ ││ │⠸⡄ ⠙⣄ ⠈⠉⡋⠁ ⣠⠋ ⢠⠇ │
│Sky RMS = 1.28 ││ │ ⠱⡀ ⠙⠲⠤⠤⡦⠤⠖⠋ ⢀⠎ │
│Popn SD = 2.39 ││ │ ⠙⢄ • ⡂ ⡠⠋ │
│ ││ │ ⠈⠑⢤⡀ • ⡂ ⢀⡤⠊⠁ │
│Observation #1 is a very weak outlier cand││-2 ┤ ⠈⠑⠲⠤⢄⣀⣀⣂⣀⡠⠤⠖⠊⠁ │
│ ││ └┬────────────┬───────────┬ │
│Sky RMS 1.28 ││ -2 0 +2 │
│ ││ dX east-west (arcsec) │
├──────────────────────────────────────────┤│circles at 0.5, 1, 2 arcsec │
│* ││7 observations, radial RMS 1.28 ar│
│F1 help · Tab completes · F6 sidebar ││Arrows or a click select a point. │
└──────────────────────────────────────────┘└──────────────────────────────────┘
probe: M… · 7 obs · 0 masked · 5 terms, 0 fixed · Sky 1.28 · PSD 2.39 · F1 help
The status bar uses the INDAT file name when the caption is blank, and leaves out the PSD when the last fit has none.
The input line edits and completes as line mode does and shares its history file. Tab opens a list of the choices, with each command’s description; Tab or the arrow keys move through it and Enter takes one. The line under the input shows the arguments of the command being typed.
| Key | Does |
|---|---|
F1, or ? on an empty line | show the keys and every command’s description |
| PgUp, PgDn, mouse wheel | scroll the session pane |
| Ctrl-C | clear the line |
| Ctrl-D on an empty line | leave, as END does |
| F6 | move the focus between the input line and the sidebar |
[ and ] | narrow or widen the sidebar, on an empty line or in the sidebar |
| F7 | zoom the sidebar to the full width and back |
| F9 | turn mouse capture off, so the terminal selects text, and on again |
Drag the divider between the panes with the mouse to resize the sidebar.
While mouse capture is on, most terminals still select text with
Shift-drag. Set NO_COLOR to draw without colors.
Sidebar Tabs
The sidebar has five tabs. Each is recomputed after every command line, so
it follows FIT, MASK, USE and INDAT. A tab that needs a fit says so
until there is one.
| Tab | Shows |
|---|---|
| GSCAT | the scatter diagram of GSCAT, square, with its circles |
| G | the residual plot of the last G line, G D H until there is one |
| GDIST | the histograms of GDIST |
| Model | each term’s value and sigma, and a bar one cell per sigma of strength; terms below 2 sigma are dimmed, fixed terms are marked |
| Obs | the rows of SLIST, masked rows dimmed and marked M |
Typing G, GSCAT or GDIST switches to its tab with the line’s
arguments and still prints the plot in the session pane, so GC P and
GC B write it as before.
| Key, in the sidebar | Does |
|---|---|
Tab, Shift-Tab, 1 to 5 | switch tabs; a click on a title does the same |
| arrow keys on G and GSCAT | select the nearest point in the arrow’s direction; a click selects the point nearest to it |
| Up, Down, Home, End | move the selection in Obs and Model |
| PgUp, PgDn | move the selection in Obs by a page |
s, r | sort Obs by the next column, reverse the order; a click on a heading sorts by it |
m, u on G, GSCAT and Obs | run MASK n or UNMASK n for the selected observation, then FIT |
| Enter on Obs | mask or unmask the selected row, then FIT |
f, u, d or Delete on Model | run FIX, UNFIX or LOSE for the selected term, then FIT |
| Esc | return to the input line |
The plots and the Obs tab share one selected observation. The line under a plot gives its hour angle, declination and residuals.
Every key that changes the session runs command lines, which show in the session pane and go into the history as if typed:
*MASK 3
*FIT
...
Sky RMS 1.28 -> 1.37
After each FIT the session pane gives the Sky RMS of the fit before and
of this one.
Long Searches
An automodel search can take several seconds, and you don’t want the screen
to freeze while it runs. Lines run in the background, so the screen keeps
drawing. While FAUTO searches, the session pane shows its log as it is
written, a spinner and the seconds taken. Here it runs on paramount.dat:
*FAUTO 8
start IH ID CH NP ME MA psd 85.173
fix at zero NP (0.8 sigma); psd 85.112
add DAF +397.72+-29.41; psd 85.112 -> 62.963
⠙ FAUTO 8 · 2 s · Esc cancels
Esc or Ctrl-C cancels. FAUTO stops between steps with the error
the search was cancelled, and leaves the model, the mask and the last fit
as they were. Lines not yet run are skipped. You can keep typing while a line
runs, and Enter waits until it ends. Line mode prints the log with the
result.
A Session
This session fits the six basic equatorial terms to warp-astron.dat, 98
observations from one night, then asks MVET whether every term earns its
place. The data files are in celestial-pointing/tests/data.
*INDAT warp-astron.dat
...
*USE IH ID NP CH ME MA
*FIT
coeff change value sigma
1 IH +8512.559 +8512.56 14.883
2 ID +7206.960 +7206.96 18.313
3 NP -22.682 -22.68 30.817
4 CH -1234.764 -1234.76 16.706
5 ME -133.523 -133.52 14.296
6 MA +64.384 +64.38 25.283
Sky RMS = 109.11
Popn SD = 112.61
Observation #61 is a weak outlier candidate.
*MVET 1
Model terms, strongest first:
IH
ID
CH
ME
MA
| NP
Model term NP is the weakest, and has been removed.
IH
ID
CH
ME
MA
No weak terms detected.
INDAT prints the file it reads, and clears the mask and the last fit. FIT prints each term’s change in this fit, its value and its sigma, all in arcseconds. A fixed term has no sigma. The population SD is printed only when there are more observations than floating terms.
The outlier line names the observation least like the others. The grade comes from the probability of a residual that large if the observation were typical:
| Probability | Grade |
|---|---|
| 0.05 or more | very weak |
| 0.01 to 0.05 | weak |
| 0.001 to 0.01 | possible |
| below 0.001 | strong |
MVET ranks the floating terms and marks weak ones with |. MVET n removes
the weakest term, refits and ranks again, up to n times. With no n, it
fits and ranks without removing anything. Here MVET removes NP and finds no
weak terms among the five left.
Procedures
Procedures save typing when you run the same steps on night after night of
data. A library file holds procedures between PROC <name> and RETURN.
Lines outside a procedure are ignored. ! starts a comment, and a line that ends
with \ continues on the next line.
! ramp.pro
PROC STEP
INDAT $1
USE IH ID
FIT
RETURN
*INPRO ramp.pro
Reading procedures from file ramp.pro ...
The library now contains 5 lines.
*CALL STEP april.dat
.STEP april.dat is short for CALL STEP april.dat. $1, $2 and so on
are replaced by the arguments. A procedure stops at its first error.
Procedure names match in any case. Reading a library replaces any procedure
of the same name, and INPRO with no path empties the library.
Echo is off at the start. ECHO or ECHO ON makes the shell print each
command a procedure runs after a >, and ECHO OFF stops it.
Commands
HELP lists every command with its arguments. Command names match in any
case. The model and fitting commands are:
| Command | Does |
|---|---|
INDAT <path> | read observations, clearing the mask and the last fit |
APPEND [ON|OFF] | add the next INDAT file’s observations to those already read |
USE [<term>...] | add terms at zero and set them floating, keeping the values of terms already present; with no terms, float every term |
LOSE [<term>...] | remove terms; with no terms, remove them all |
FIX / UNFIX <term>... | hold terms at their values, or let them float |
MASK <n>... | leave observations out of the fit, numbered among those kept on reading |
UNMASK [<n>...] | return observations to the fit; with no numbers, all of them |
REFRACT <A> <B> | set the refraction constants in arcseconds |
REFMODEL [CIDDOR|HS|CLOSED] | choose how refraction is computed from the INDAT weather when REFRACT has not set it (default CIDDOR); with no argument, report the model and the constants in use |
FIT | fit the floating terms |
MVET [<n>] | rank the terms and remove up to n weak ones |
SLIST [<r>] [P] | residuals of each observation, leaving out those below r arcseconds |
LOO | leave-one-out residuals and the jackknife PSD |
FAUTO [<max harmonic> [<significance>]] [CROSS] | build an automodel; see below |
G <ydata> <xdata> [<scale>] | plot one residual component against one coordinate |
GSCAT [E|A] [<radius>] | plot the residuals as a scatter diagram |
GDIST | plot histograms of the residuals |
GC [C|P|B] [<path>] | forget the last graph, or write it as an SVG file |
INMOD / OUTMOD <path> | read or write the model |
FLIST <path> | write the residuals of the unmasked observations to a file |
END, QUIT, QU, Q | leave |
The shell’s own commands are INPRO, CALL, ECHO (see
Procedures), GC (see Writing a graph as SVG)
and HELP.
FAUTO searches for the terms the unmasked observations support. It starts
from a basic model whose size grows with the number of observations. Then it
offers harmonics up to <max harmonic> (default 8), and adds terms of at
least <significance> sigma (default 2). CROSS also offers single cross
harmonics such as HDCH3CD8. FAUTO replaces the model, and adds the outliers
it masks to the mask. Its log names each step:
*INDAT warp-astron.dat
...
*FAUTO
start IH ID CH NP ME MA psd 112.609
fix at zero NP (0.7 sigma); psd 112.311
add HDSD -172.64+-20.53, HDCD -110.74+-18.31; psd 112.311 -> 76.659
add DAF +254.46+-37.15; psd 76.659 -> 63.400
...
fix at zero ME (0.0 sigma); psd 53.075
mask obs 98; psd 49.031
Masked observations: 98
The fitted model follows, in the same layout as FIT prints.
Listing the Residuals
SLIST prints the residuals of every observation at the current
coefficients, with the RMS of dX, dD and dR over the unmasked observations.
Here it lists cgx-l-data.dat against the model in outmods/cgxl-outmod.dat:
*INDAT cgx-l-data.dat
...
*REFMODEL HS
*INMOD outmods/cgxl-outmod.dat
*MASK 14
*SLIST
# HA Dec Az ZD dX dD dS dZ dR
1b -05 19 56.7 +72 29 13 22.71 50.14 90.19 -47.50 -54.43 -86.23 101.97
...
14 M +01 12 37.7 +54 39 51 327.96 19.86 114.38 -429.37 387.60 -218.38 444.39
...
RMS of 147 unmasked observations 160.22 172.16 235.17
Each row has the star’s hour angle and declination, its azimuth (north
through east) and zenith distance in degrees, then the residuals in
arcseconds. b marks a mount reading beyond the pole and M a masked
observation. SLIST 300 leaves out the observations whose radial error dR is
below 300 arcseconds. Masked observations count as zero, so they appear only
without a threshold. A P (paged output) before or after the threshold is
accepted and ignored.
FLIST <path> writes the same residuals to a file at higher resolution, one
record per unmasked observation and a closing END. The first record of the
session above is:
1b -05 19 56.6945 +72 29 13.382 22.709 50.141 90.192 -47.500 -54.428 -86.229 101.965
A residual whose text takes 9 characters or more, such as -1798.640, joins
the field before it, with no space between them.
Graphs
The graph commands plot the residuals of the last fit, so run FIT first.
Masked observations are left out. The examples below fit five terms to the
218 observations of paramount.dat:
*INDAT paramount.dat
*USE IH ID CH ME MA
*FIT
Residuals are in arcseconds, in the sense telescope minus star, as SLIST
prints them. The terminal plots use braille characters, so the terminal font
needs them.
G: one residual component against one coordinate
G <ydata> <xdata> [<scale>] plots the residual component ydata against
the coordinate xdata. The scale is the largest residual the vertical axis
shows. By default it is the largest residual rounded up to 1, 2 or 5 times a
power of ten. Points beyond the scale are left out and counted.
| ydata | Residual |
|---|---|
H | in hour angle |
X | east-west: the hour-angle residual times cos(dec) |
D | in declination |
A | in azimuth, increasing from south through east, so that S is A times cos(elevation) |
S | left-right |
Z | in zenith distance |
E | in elevation, minus Z |
R | total |
| xdata | Coordinate of the star |
|---|---|
H | hour angle, -12 to +12 h |
D | declination |
A | azimuth, north through east |
Z | zenith distance |
E | elevation, 90 degrees minus Z |
Q | parallactic angle |
N | observation number |
Pointing is equatorial-only, so E and Z describe the same direction.
P and V, the residuals that correspond to HA/Dec and Az/El
nonperpendicularity, are not supported.
*G D H
G D H
dD declination (arcsec)
+200 ┤
│
│
│ ⠠
│ ⡀⠠⠄⠒⡐ ⠁ ⠐ ⠂ ⠂ ⠄
+100 ┤ ⠰⢀ ⡂ ⠂⡀ ⠤
│ ⠁⠐⡀⢠ ⢀⡀ ⢀⠱⠠⡈⡀ ⠂
│ ⢠⠉⡀⠆⠠⠵⡨⠅⠜⡈ ⠈ ⠉⠈⠈⠂ ⡀ ⠁
│ ⠠⡂ ⠄⠒⠐ ⠁
│ ⠤⢀ ⠠⠁⠅⠄⠨ ⠘ ⠠⢀ ⠄⠠⠢⠂⠆⠂ ⢀
0 ┤⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠅ ⠁ ⠁⠄⠡ ⠁⢀⠩⠂⡁ ⠁ ⠁⡠⠉⠰⠹⡉⠉⠁⠁⢀⠅ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁ ⠁
│ ⠐ ⢀⢀⠄⣀ ⡐⢰⠠⠂⠐⢀ ⢀ ⠂⠂⢂⠈⠑ ⢀
│ ⠈⠄⠄ ⠠ ⠈ ⠐⠉⠔ ⢂ ⢀⠄ ⠠⠐⢉⡠ ⠠⠁
│ ⠢⠐⣀⠐⠠⠁ ⠠ ⠐⠘⡀⢀
│ ⠂⢀ ⢂ ⢄⠐⢀ ⠂ ⠊
-100 ┤ ⠐⠈⢠⠈ ⠠
│ ⠈ ⠐
│
│
│
-200 ┤
└┬───────────────┬───────────────┬───────────────┬───────────────┬
-12 -6 0 6 12
hour angle (h)
218 observations, scale 200 arcsec
GSCAT: scatter diagram
GSCAT [E|A] [<radius>] plots each observation’s residual as a point,
like shots on a target. E, the default, plots east-west against
north-south. A plots left-right against up-down, where up-down is the
elevation residual. The radius is 0.1 to 9999.9 arcsec. By default it is the
largest residual rounded up to 1, 2 or 5 times a power of ten. The circles
are at the 1, 2 and 5 steps between a tenth of the radius and the radius.
*GSCAT
GSCAT
dD north-south (arcsec)
+200 ┤ ⢀⠠⠐⠐⠐⠈⠈⠈⠍⠈⠈⠐⠐⠐⠠⢀
│ ⠄⠂⠁⠁ ⠅ ⠁⠁⠂⠄
│ ⡀⠔⠈ ⠅ ⠈⠐⠄⡀
│ ⠠⠐ • ⠅ ⠐⠠
│ ⡐⠁ ••••⠅ • • • ⠑⡀
│ ⡐ • ⡀⠄⠂⠂•⠍•••••• ⠐⡀
│ ⠌ ⠠••• • ⠅• •••⠁⢄•••• ⠈⠄
│⠠⠁ ⡠••• •••••⡀•••• ••• ⠡
│⠌ ⢐ ••⠔⠁• ⠅ •⠑• •• ⠡ ⠈⠄
│⠅ • ⡂• •••• •⠅ •••⠄••• • ⠅
0 ┤⠅⠁⠁⠁⠁⠁⠁⠁⠁⠁•••••⠅•••••••••⠅⠁•⠁⠁⠅⠁⠁⠁•⠁⠁⠁⠁⠁⠅
│⠅ ••••••••• •••⢀• •••⠠⠁• ⠅
│⠨ ••• •••••••••⠁••• ⢀⠅•• ⠨
│ ⠅ ⠡• •••• ••••• •⠔ • ⠅
│ ⠈⢂ • ••⠂⠄⡀• ⠅•⢀⢀⠠•• • • ⢀⠊
│ ⢂ • ⠁⠍• ••• ⢀⠂
│ ⠡⢀ • • ⢀⠠⠁
│ ⠂⢄ ⠅ ⢀⠄⠂
│ ⠈⠄⡀ ⠅ ⡀⠌
│ ⠁⠑⠠⢀⢀⢀ ⠅ ⢀⢀⢀⠠⠐⠁⠁
-200 ┤ ⠈⠈⠈⠉⠈⠈
└┬───────────────────┬───────────────────┬
-200 0 +200
dX east-west (arcsec)
circles at 50, 100, 200 arcsec
218 observations, radial RMS 84.13 arcsec
GDIST: histograms
GDIST draws one histogram for each of the east-west (X), north-south (D),
left-right (S), up-down (Z) and total (R) residuals, with the mean m and
the standard deviation sd. The number of bins is ceil(log2 n) + 1 for n
observations, at most 12. All five histograms share one range, the largest
residual rounded up to 1, 2 or 5 times a power of ten, and one count scale.
*GDIST
GDIST
X D S Z R
⣤ ⣀ ⣶ ⣀ ⣿ ⣀
⣿⣤⣶ ⣿⣤⣶ ⣿⣿⣿ ⣿ ⣤⣿
⣿⣿⣿ ⣿⣿⣿ ⣿⣿⣿ ⣶⣿ ⣿⣿⣿
⣿⣿⣿ ⣿⣿⣿ ⣿⣿⣿ ⣿⣿⣿⣿ ⣿⣿⣿
⣀⣿⣿⣿ ⣿⣿⣿ ⣿⣿⣿ ⣿⣿⣿⣿ ⣿⣿⣿⣤
⣿⣿⣿⣿⣤ ⣤⣿⣿⣿⣀ ⣀⣿⣿⣿ ⣿⣿⣿⣿⣶ ⣀⣿⣿⣿⣿
⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣶ ⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿ ⣀⣿⣿⣿⣿⣿
⣀⣿⣿⣿⣿⣿⣶ ⣤⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣀ ⣶⣿⣿⣿⣿⣿⣀ ⣿⣿⣿⣿⣿⣿⣤⣀
────┴──── ────┴──── ────┴──── ────┴──── ┴────────
-200 +200 -200 +200 -200 +200 -200 +200 0 +200
m +0.83 m +5.34 m -3.78 m -13.05 m +78.32
sd 58.62 sd 60.10 sd 56.86 sd 60.50 sd 30.72
X east-west, D north-south, S left-right, Z up-down, R total, in arcsec
218 observations, 9 bins, tallest bin 58
Writing a graph as SVG
GC P [<path>] writes the last graph drawn as an SVG file with colored pens,
and GC B [<path>] with black pens only. The path defaults to pointing.svg
in the current directory. In the SVG file, open markers are observations
whose mount reading is beyond the pole, and each marker shows its
observation number as a tooltip. GC or GC C forgets the last graph.
*GSCAT A
...
*GC P scatter.svg
Graph written to scatter.svg
Changelog
Changes in each release, newest first. Every crate in the workspace shares one version, so one entry covers all of them.
[0.3.0] - 2026-11-30
This release speeds up SER frame reads on captures that aren’t in the page cache yet. Only celestial-images changed. The other crates move to 0.3.0 because every crate shares one version.
celestial-images
- Breaking:
ImageError,FitsError,XisfErrorandSerErrorare#[non_exhaustive], so amatchon them needs a wildcard arm. Later variants won’t break callers. - Breaking:
SerErrorhas a new variant,RowsOutOfBounds, returned when a row range is reversed or ends past the frame height. SerReader::read_frame_intoreads a frame into a buffer the caller owns, andSerReader::read_rows_intoreads a band of rows from one. Both use a positioned read (preadon Linux and macOS) instead of the memory map. A 15 GB capture that isn’t in the page cache reads in 2.3 s instead of 19.6 s on one thread.read_frame_data,read_frame_u16andread_timestampread the same way. If the file is truncated while it’s open, these methods and the two new ones return an I/O error instead of raisingSIGBUS.read_frame,frame_slice,frame_slicesanditer_framesstill borrow the memory map.
[0.2.0] - 2026-11-29
This release changes the public API of every crate. Crate roots no longer re-export types, so imports come from the defining module. Functions that receive NaN, infinite or out-of-range input return errors. celestial-solver is published for the first time.
celestial-core
- Breaking: The crate root no longer re-exports anything. Import from the module that defines the item, for example
celestial_core::angle::Angle,celestial_core::matrix::{RotationMatrix3, Vector3},celestial_core::location::Locationandcelestial_core::errors::{AstroError, AstroResult, MathErrorKind}. The submodules ofnutation,precession,cioandlocationare now private, socelestial_core::precession::iau2006::PrecessionIAU2006becomescelestial_core::precession::PrecessionIAU2006. - Breaking: Functions that can receive non-finite or undefined input now return
AstroResultand need a?. This coverswrap_pm_pi,wrap_0_2pi,Angle::wrapped,Angle::normalized,gcrs_to_cirs_matrix,iau_2006_mean_obliquity,iau_1980_mean_obliquity,PrecessionIAU2006::npb_matrix_iau2006aandPrecessionIAU2006::fukushima_williams_angles. - Breaking: The nutation models,
PrecessionIAU2000::compute,PrecessionIAU2006::computeand both mean obliquity functions return an error for a non-finite date. They also return an error for a date more thanMAX_CENTURIES_FROM_J2000(20 Julian centuries) from J2000.0. In 0.1.1-alpha.2 they returned a value, NaN for NaN input. - Breaking:
PrecessionIAU2000::computetakes a two-part Julian Date(date1, date2)instead of TT centuries, the same asPrecessionIAU2006::compute.fukushima_williams_anglesreturns aFukushimaWilliamsAnglesstruct with fieldsgamma_bar,phi_bar,psi_barandepsilon_ainstead of a 4-tuple.fw_angles_to_matrix, thePrecessionCalculatortrait and theBiasMatrix,PrecessionMatrixandBiasPrecessionMatrixaliases are removed. UseRotationMatrix3in place of the aliases. - Breaking:
Locationfields are private. Read them withlatitude(),longitude()andheight().to_geocentric_kmandto_geocentric_metersreturn(f64, f64)instead of aResult.Location::from_degreesaccepts east longitudes in (180°, 360°] and stores the [-180°, 180°] equivalent. Validation errors reportMathErrorKind::NotFiniteorOutOfRangeinstead ofInvalidInput. - Breaking:
RotationMatrix3::from_arrayreturnsAstroResult. It rejects non-finite elements and any matrix that is not a proper rotation, with a tolerance of 1e-12.RotationMatrix3::get,set,IndexandIndexMutare removed, so read elements withelements().Vector3no longer implementsIndexorIndexMut, so use thex,yandzfields or the falliblegetandset.Vector3::normalizereturnsAstroResultand fails on a zero-length vector instead of returning it unchanged. - Breaking:
AstroErrorandMathErrorKindare#[non_exhaustive], somatchneeds a wildcard arm.AstroError::ExternalLibraryErrorandexternal_library_errorare removed.MathErrorKind::Overflow,UnderflowandPrecisionLossare removed.MathErrorKindnow implementsCopy,EqandDisplay, and error messages print the kind in words, for example “(division by zero)”. - Breaking: These items are removed:
NutationModel. UseNutationIAU2000Adirectly.EquationOfOrigins. Use the functioncio::equation_of_origins(npb, s).NormalizeModeandclamp_dec.validate_longitude, both the free function and theAnglemethod.- The angle helpers in
utils:normalize_longitude,normalize_latitude,normalize_angle_rad,normalize_angle_to_positiveandangular_difference. math::vincenty_angular_separation. It is replaced bymath::angular_separation(lon1, lat1, lon2, lat2), which matches ERFAeraSeps.
- Breaking: These constants are renamed:
MICROARCSEC_TO_RADtoTENTH_MICROARCSEC_TO_RAD. Its value was always 0.1 µas.MOON_EARTH_MASS_RATIOtoMOON_EMB_MASS_RATIO.J2000_OBLIQUITY_RADtoVSOP2013_OBLIQUITY_RAD.FRAME_BIAS_PHI_RADtoVSOP2013_PHI_RAD.
- Breaking: The
erfa-testsfeature is renamedtest-support.test_helpers, the nutation term tables and the fundamental-argument traits (IERS2010FundamentalArgs,MHB2000FundamentalArgs) are public only with that feature. - Add
ecliptic::vsop2013_to_icrsandecliptic::icrs_to_vsop2013. Addconstants::SPEED_OF_LIGHT_M_PER_Sandconstants::MAX_CENTURIES_FROM_J2000. - Fix
parse_angle, which read a bare number such as"45.5"as hours (682.5°). It now reads degrees, asParseAngle::to_angledoes. Sexagesimal parsing returns an error for non-ASCII digits such as"12:34:56"instead of panicking. - Fix
SPEED_OF_LIGHT_AU_PER_DAY. It is now 173.1446326742403, ERFA’sDC. Before, it was 173.1446326846693. Angleunit conversions are now correctly rounded, so results can differ from 0.1.1-alpha.2 by 1 ulp. With theserdefeature,Anglerejects NaN and infinity when it serializes and deserializes.LocationandRotationMatrix3run their constructor validation when they deserialize.
celestial-wcs
- Breaking: The crate root no longer re-exports types. Import each type from its module, for example
celestial_wcs::builder::{Wcs, WcsBuilder},celestial_wcs::coordinate::{CelestialCoord, PixelCoord},celestial_wcs::spherical::Projectionandcelestial_wcs::error::WcsError. - Breaking: Native and celestial coordinates hold
f64degrees.CelestialCoord::new(alpha_deg, delta_deg)andNativeCoord::new(phi_deg, theta_deg)take degrees in place ofAngle. The newalpha_deg(),delta_deg(),phi_deg()andtheta_deg()return degrees, andalpha(),delta(),phi()andtheta()still returnAngle.SphericalRotation::newandSphericalRotation::from_crvalalso take degrees, andfrom_crvaltakes aphi_0argument beforetheta_0.phi_p_degrees()anddelta_p_degrees()are renamedphi_p_deg()anddelta_p_deg().IntermediateCoord::x_rad()andy_rad()are removed. - Breaking:
Projectionis an opaque struct, so callers can no longer match on its variants. Build one with its constructor, such asProjection::tan()orProjection::zpn(coeffs).Projection::cop,coe,codandcootake a second argument,eta(PV2_2). Pass0.0to get the old behavior. - Breaking:
Wcs::pixel_to_celestialreturns celestial longitude in [0, 360] when CRVAL1 >= 0, and in [-360, 0] when CRVAL1 < 0. It used to return (-180, 180], so a field at CRVAL1 = 350 mapped its reference pixel to -10. - Breaking:
Wcs::pix2worldandWcs::world2pixare removed. Usepixel_to_celestialandcelestial_to_pixel.Wcs::crval()returns[f64; 2]in place of a tuple, andWcs::projection_code()returns&'static str.Wcs::new,Wcs::linear(),CoordType::from_ctype_prefixand theWcsErrorconstructor functions are no longer public.Wcs::cd_matrix()andWcs::native_reference()are new. - Breaking: TNX distortion is removed:
TnxDistortion,TnxSurface,SurfaceTypeandCrossTerms. TheDistortiontrait is also removed, and thedistortion::polynomialmodule is now private.DistortionModelhas two variants,SipandTpv. - Breaking:
SipDistortion::new,set_a,set_b,set_ap,set_bpandset_inverse_orderreturnWcsResult. They reject orders outside 2 to 9 for A and B, and outside 0 to 9 for AP and BP. They also reject a term above its order and a non-finite value. The old setters dropped these without an error.apply_inversealways solves A and B by Newton’s method and uses AP and BP only as the starting point. - Breaking:
TpvDistortion::set_pv(axis, index, value)andpv(axis, index)replaceset_pv1,set_pv2,get_pv1andget_pv2.TpvDistortion::new()returns the identity (PV1_1 = PV2_1 = 1), andidentity()is removed. Axis 2 now swaps ξ and η, as the TPV convention requires. Code that set PV2_2 = 1 for the η term must set PV2_1 instead. - Breaking:
WcsError::CoordinateErroris removed, and the crate no longer depends oncelestial-coords. The newWcsError::MissingBuilderFieldnames theWcsBuildersetter that was not called, andWcsErrorderivesClone. Every entry point returnsInvalidParameterfor NaN or infinite input.PixelCoord::to_array_indexreturnsWcsResult<(usize, usize)>, withOutOfBoundsfor a non-finite pixel or one below 0.5. - Breaking:
WcsBuilder::buildrejects more input. It rejects PV2_m values set beside an explicitprojection(), and projection parameters outside Paper II’s ranges, such as AZP with mu = -1.WcsBuilder::from_headerrejects a CTYPE1/CTYPE2 pair that is not a celestial pair. A CYP header without PV2_1 now uses Paper II’s default mu = 1. The old default was 0. WcsBuilder::from_headerreads more headers:- TAN-SIP and TPV headers, which used to fail with
UnsupportedProjection. CROTA2.CUNITin arcmin, arcsec, mas or rad.- Headers that list latitude first.
- PV2_0 to PV2_29 (up to PV2_20 before), and PV1_0 to PV1_4 for the fiducial point, LONPOLE and LATPOLE.
- Absent CRPIX and CRVAL now default to 0 and absent CDELT to 1, as Paper I specifies.
- TAN-SIP and TPV headers, which used to fail with
Wcs::to_keywordswrites CUNIT1 and CUNIT2, the SIP or TPV terms, PV1_m and the header’s own generic CTYPE prefixes. This lets a header read back as the same WCS. It leaves out PV2_m values that are at their Paper II defaults.- Fix three projection bugs:
- The pole longitude in
SphericalRotation::from_crvalwas wrong when CRVAL2 < 0 for projections whose fiducial point is on the native equator (CAR, MER, CEA, CYP, SFL, PAR, MOL, AIT, BON, PCO, TSC, CSC, QSC). Their reference pixel mapped 180 degrees away in RA. - Conic projections with a southern standard parallel flipped the sign of native longitude.
- The ZPN inverse could return a root past the first turning point.
- The pole longitude in
celestial-time
-
Breaking: Nothing is re-exported from the crate root or from the
scales,sidereal,transformsandscales::conversionsmodule roots. Import from the defining module, for examplecelestial_time::julian::JulianDate,celestial_time::scales::tt::TT,celestial_time::scales::conversions::tt_tdb::ToTDBandcelestial_time::sidereal::gmst::GMST. Theparsingmodule is private, soparse_iso8601andParsedDateTimeare gone. Parse withFromStron a scale type instead, for example"2000-01-01T12:00:00".parse::<TT>(). -
Breaking: Constructors and conversions that can fail now return
TimeResult. This covers:JulianDate::from_calendarand every*_from_calendarfunction.UTC::new,UTC::nowandUTC::to_iso8601.TT::centuries_since_j2000,get_tai_utc_offsetandcalendar_to_julian.from_hours,from_degreesandfrom_radiansonSiderealAngle,GMST,GAST,LMSTandLAST.hour_angle_to_target,GMST::to_lmst,GAST::to_last,LMST::to_gmstandLAST::to_gast.
These functions reject dates that do not exist, out-of-range times of day and non-finite values.
-
Breaking:
JulianDate:- The fields are private. Read them with
jd1()andjd2(). AddandFrom<f64>are removed. Useadd_daysandfrom_f64.Subreturns the difference in days as anf64.==compares the date value, soJulianDate::new(2451545.0, 0.5) == JulianDate::new(2451545.5, 0.0).Displayprints both parts, for exampleJD 2451545 + 0.5. Before, it printed the sum to nine decimals.
- The fields are private. Read them with
-
Breaking:
TimeError::InvalidDatecarries aStringmessage. -
Breaking: UTC is undefined before 1960-01-01.
utc_from_calendar,UTC::new,UTC::from_str,get_tai_utc_offsetand the UTC conversions returnTimeError::InvalidDatefor those dates. Before, they used TAI-UTC = 0. -
Breaking:
TT::centuries_since_j2000returnsTimeError::InvalidEpochmore than 20 centuries from J2000.0. Nutation, precession,GMSTandGASTuse it, so they fail for the same dates.earth_rotation_anglefails for a non-finite date or one more than 1e12 days from J2000.0. -
Breaking: These conversion items are removed:
- The traits
ToUT1,ToTCB,ToTCGFromTCBandToUTCViaTAI, with the direct TCG-TCB conversion. - The identity conversions such as
TT::to_tt(). ToTT for TDB. UseToTTFromTDB.- The free functions
utc_to_taiandtai_to_utc. Useto_tai()andto_utc().
- The traits
-
Breaking: These other items are removed:
TT::from_jdandfrom_julian_date_rawonTT,TAIandGPS. Usefrom_julian_date(JulianDate::new(jd1, jd2)).ObservatoryContextand the siderealj2000()constructors.LAST::from_lmst_and_equation_of_equinoxes.From<LMST> for GMSTandFrom<LAST> for GAST.scales::common::is_leap_yearandscales::common::next_calendar_day.- Every public constant in
celestial_time::constantsexceptUNIX_EPOCH_JD.
-
UTC::newhandles leap seconds the same wayutc_from_calendardoes. A day that ends in a leap second is 86,401 s long. AddUTC::to_unixas its inverse.UTC::from_straccepts a trailingZ, and the other scales returnParseErrorfor it. ISO 8601 parsing accepts expanded years such as+10000and a lowercasetseparator. -
Fix TT-to-TDB with a location. The diurnal terms read the TT day fraction counted from noon, so they ran 12 hours off. They now read the UT1 fraction from midnight.
to_tdb_with_location*andto_tt_with_location*match the ERFAeraDtdbchain bit-for-bit. TDB-to-TT evaluates the series once at TDB instead of three times. The UT1 offset parameter is renamedut1_minus_tt_seconds. -
Fix
UTC::to_iso8601. It truncated, so it could print60.000seconds outside a leap second. It now rounds to the millisecond and carries into the minute. It prints:60only during a leap second. FixUTC::now, which returned the Unix epoch when the system clock read before 1970. -
UTC-to-UT1 reads TAI-UTC at 0h on the UTC date, as
eraUtcut1does, which changes results before 1972.SiderealAngleDisplaynever shows24.000000h. Withserde,SiderealAnglewraps a stored angle into range and rejects non-finite values.
celestial-coords
-
Breaking: The crate root re-exports nothing, and
frames,eopandtransformsno longer re-export their types. Import each type from the module that defines it, for examplecelestial_coords::frames::icrs::ICRSPosition,celestial_coords::eop::record::EopParameters,celestial_coords::errors::CoordErrorandcelestial_coords::transforms::cartesian::CartesianFrame. ImportAngle,Location,Vector3andTTfromcelestial_coreandcelestial_time. -
Breaking: Conversions that depend on the Earth’s rotation take
&EopParametersin place of a delta-T in seconds or a second epoch. The new signatures areCIRSPosition::to_hour_angle(&observer, &eop),HourAnglePosition::to_cirs(&eop),TopocentricPosition::to_cirs(&eop),ITRSPosition::to_tirs(&eop)andTIRSPosition::to_itrs(&eop).TIRSPosition::from_cirs,from_itrsandcompute_delta_tare removed. UseCIRSPosition::to_tirs,ITRSPosition::to_tirsorastrom::earth::EarthRotationinstead. These calls return an error when the EOP record is more than one day from the position’s epoch. -
Breaking:
TopocentricPosition::atmospheric_refraction,with_refractionandwithout_refractiontake a&Refractionin place of four weather numbers.Refraction::new(pressure_hpa, temperature_c, relative_humidity, wavelength_um)?gives the closed-form constants.Refraction::from_weather(&weather)?gives ray-traced constants. Both return an error for non-finite input. -
Breaking: These functions now return
CoordResult, so callers add?:solar::compute_solar_orientationandsolar::sun_earth_distancelunar::compute_lunar_orientation,compute_optical_librationandcompute_sub_earth_pointHeliographicStonyhurst::disk_centerandSelenographicPosition::is_visible_from_earthEclipticPosition::mean_obliquity- the four diurnal parallax methods on
TopocentricPosition ITRSPosition::new,TIRSPosition::newand both types’from_position_vectoraberration::remove_aberrationandaberration::remove_light_deflection
NaN or infinite input returns an error where it used to produce NaN output.
-
Breaking: EOP API changes:
EopRecord::newno longer takeslod_sec. Add LOD with.with_lod(lod_sec)?.EopParameters::lodisOption<f64>.EopParameters::s_prime,compute_s_prime,compute_s_prime_jd,compute_era,corrected_cip_xandcorrected_cip_yare removed from the public API.EopRecordfields,EopRecord::with_flags,eop::parseandbundled::load_bundled_combinedare crate-private. UseEopProvider::from_finals_strorfrom_finals_fileto parse finals data.EopProvider::time_spanandEopInterpolator::time_spanreturn(f64, f64)in place of anOption.EopInterpolator::newandwith_max_gapreturnCoordResult, andEopInterpolator::extendis no longer public.EopSource::IersPrediction,EopSource::InterpolatedandEopQuality::LowPrecisionare removed.
-
Breaking:
CoordErrorconstructors are crate-private.EpochErrorandCoreErrorare tuple variants that wrap the source error, soCoreError(AstroError)replacesCoreError { message }.MissingObserverandExternalErrorare removed. File reads returnIo { context, source }.CoordErrorno longer implementsSerializeorDeserialize. -
Breaking: These items are removed:
- the
lighttimemodule andLightTimeCorrection ICRSPosition::position_uncertainty_arcsecsolar::compute_b0,compute_l0,compute_p,CARRINGTON_EPOCH_JDandCARRINGTON_SYNODIC_PERIOD. Read B0, L0 and P fromcompute_solar_orientation.HeliographicCarrington::carrington_rotation_number
solar::carrington_rotation_numberreturns a fractionalf64, where it used to return au32count.TopocentricPosition::parallactic_angle(ha, dec)is nowHourAnglePosition::parallactic_angle().set_radiuson the heliographic and selenographic types is crate-private. - the
-
Breaking:
HourAnglePosition::newfolds a declination past a pole back over the pole and adds 12 h to the hour angle, sodeclination()stays within ±90°. Callers that stored pier-flipped declinations must track the flip themselves. -
Add
astrom::Astrom. It computes the Earth’s position, velocity and GCRS-to-CIRS matrix once per epoch and converts positions between ICRS, GCRS and CIRS.Astrom::with_eopapplies the observed CIP offsets dX and dY.Astrom::for_siteuses the site’s position and velocity, which adds up to 0.32“ of diurnal aberration. Addastrom::earth::EarthRotationfor CIRS, TIRS, ITRS and hour angle. -
Add
proper_motion::CatalogStar::propagate. It propagates a star with parallax and radial velocity, following SOFA’spmsafe. Addaberration::apply_annual_aberrationandremove_annual_aberrationfor RA/Dec pairs. -
Add selectable refraction models: the
RefractionModeltrait,refraction::weather::Weather,ray_trace::RayTraceandclosed_form::ClosedForm.RayTraceuses Ciddor refractivity for optical wavelengths by default, or Hohenkerk and Sinclair, and Rueger refractivity above 100 µm.Refraction::from_modelselects a model.RefractionModel::refraction_atandobserved_zenith_distancegive the refraction at a zenith distance and its inverse. -
Fix the Earth-rotation chain:
- CIRS to TIRS rotated by minus the Earth rotation angle (ERA) and now rotates by plus the ERA.
- Hour angle subtracted the CIRS right ascension from apparent sidereal time, which is wrong by the equation of the origins, about 19’ in 2025. It now uses the ERA and applies polar motion, matching
eraApco13witheraAtioq.
-
Fix ICRS to GCRS. It applied aberration only and now also applies light deflection by the Sun, as ICRS to CIRS already did. ICRS to GCRS and ICRS to CIRS apply annual parallax when the position has a distance, matching
eraAtciq. ICRS, GCRS and CIRS conversions no longer reject epochs outside 1900 to 2100. -
Fix refraction near the horizon.
A tan z + B tan³ zhad no limit and diverged near the horizon.with_refractionevaluated it at the true place rather than the observed place. All three methods now use ERFA’s horizon limits. -
Fix four EOP bugs:
- UT1-UTC interpolation across a leap second used to jump by one second.
- CIP offsets beyond ±3.2767 mas were clipped.
EopProvider::bundled_with_updatekept the bundled rows on days the update file covered. It now uses the update file’s rows.- Bundled rows with no LOD are flagged
Predicted.
Duplicate MJDs and non-finite values return errors.
-
Fix solar and lunar orientation:
- B0, L0, P and the Carrington frame now follow Meeus chapter 29.
- Lunar libration and position angle follow Meeus chapter 53.
compute_sub_earth_pointincludes physical libration. It used to return the optical libration.
-
Fix five topocentric bugs:
- The parallactic angle formula dropped a cos(latitude) factor.
is_circumpolarandnever_riseswere wrong in the southern hemisphere.- Diurnal parallax ignored the observer’s height and the Earth’s flattening, and it now updates the distance. An object inside the Earth returns an error, where it used to return 90°.
EclipticPosition::to_icrsuses the position’s own epoch rather than the argument.air_mass_pickeringreturns infinity below -1.115°. It used to return negative values between -2° and -1.115°.
celestial-catalog
- Breaking: The catalog file format is now version 2, and
Catalog::openrejects version 1 files with a message to rebuild. Version 1 put stars at RA 270 to 360 in the equatorial belt (|Dec| <= 41.8 degrees) under the wrong HEALPix base pixel. The forge intermediate files changed format too, so rebuild with all four stages:ingest-gaia,ingest-hipparcos,mergeandbuild-index. - Breaking:
queryno longer re-exports types. Import fromquery::catalog::{Catalog, CatalogHeader, StarRecord}andquery::cone::{cone_search, ConeSearchParams, ConeSearchResult}.cone_search_at_epochis removed. SetConeSearchParams::epochand callcone_searchinstead. - Breaking: Library functions return
celestial_catalog::error::CatalogErrorin place ofanyhow::Error, andanyhowis now a dependency of theclifeature only.Catalog::openreturnsCatalogResult<Catalog>.cone_searchreturnsCatalogResult<Vec<ConeSearchResult>>. It rejects non-finite input, Dec outside [-90, 90], a negative radius and a non-finite epoch.ang2pix_nestreturnsCatalogResult<u64>and rejects an order above 29 or an invalid position. - Breaking:
cone_searchpropagates each star with full space motion, including parallax, usingcelestial_coords::proper_motion::CatalogStar::propagate. It starts from the epoch in the catalog header and readsConeSearchParams::epochas TT. It used to apply proper motion linearly from a fixed J2016.0. It skips records with a non-finite place or a motion that cannot be propagated. - Breaking: A Hipparcos record with no Gaia cross-match has the negated HIP number as its
source_id. It used to be0x4000_0000_0000_0000 | HIP. - Catalogs built by forge have different contents:
- A cross-matched star keeps the Gaia record when Gaia has a 5- or 6-parameter solution, and keeps the Hipparcos record otherwise. The new
FLAG_5_OR_6_PARAMmarks these Gaia solutions. - A Hipparcos star with no Gaia ID link is paired with a Gaia record within 2“ whose Hp - G is in [-1.0, +2.0].
- Gaia duplicated sources are kept and marked with the new
FLAG_DUPLICATED_SOURCE. FLAG_BP_RP_EXCESS_SUSPECTuses the corrected excess factor C* from Riello et al. 2021.- Hipparcos positions are propagated to J2016.0 with parallax, which moves them by up to 0.058“.
- A cross-matched star keeps the Gaia record when Gaia has a 5- or 6-parameter solution, and keeps the Hipparcos record otherwise. The new
- Fix cone search pixel selection. It descends the HEALPix NEST hierarchy and keeps every pixel that a point of the cone falls in. The old code sampled a grid of points and could miss pixels. A disc that covers more than 12 * 4^10 pixels returns an error.
Catalog::openchecks more of the file:- The header’s epoch must be within 20 centuries of J2000.
- The file length must match the header exactly.
- Every pixel table entry must point at its own run of records.
- Star records are read with
bytemuck, andStarRecordderivesbytemuck::Podandbytemuck::Zeroable.
- Add
query::quadwithtan_project_star,tan_deproject_star,neighbor_quads,relabelled_quads,discrete_hash_key,discrete_hash_key_neighbors,QuadandQuadStar, which celestial-solver uses to match quads. Each quad’s star labels and hash code are the same at any rotation of the field. - Add helpers for writing catalog files:
CatalogHeader::to_bytes,StarRecord::to_le_bytes,StarRecord::from_le_bytesandquery::catalog::pixel_entry_bytes.query::healpix::nside_and_npix,query::healpix::reduce_ra_degandquery::validate::check_epoch.celestial_catalog::VERSION.- A
test-supportfeature that exposesquery::test_support.
forgechanges:download-gaiaresumes from a manifest and connects with a 30 s timeout. It retries with backoff and writes each file through a temporary file.download-gaiaskips a local file whose MD5 matches ESA’s_MD5SUM.txt. This addsmd-5to theclifeature.download-gaiaandingest-gaiacheck that the Gaia files cover every level-8 HEALPix pixel exactly once.--allow-partial-skyturns that check into a warning.ingest-gaiarequires abp_rpcolumn and skips malformed rows.build-indexaccepts--healpix-orderup to 10. It reads the epoch and magnitude limit from the merged data and replaces the output file only after the new file opens.
query-catalog --dateconverts 00:00:00 UTC on the date to TT. It used to pass the UTC date as TT, which was 69.184 s off. Its help text now names the programquery-catalog.
celestial-pointing
- Breaking: The crate is rewritten, and the 0.1 API is gone:
PointingModel,solver::fit_model,terms::create_term,IndatFile, theparserandplotmodules, and thecelestial_pointing::Errorre-export. The new entry points areobservation::ObservationSet::read_indatandObservationSet::reduce,model::Model::newwithmodel::model_from_names,fit::fitwithFitOptionsandFitOutcome, and the frame types inframes. Code can also drive asession::Sessionthroughcommands::execute, the same commands the shell runs. - Breaking: The
pointingbinary builds only with theclifeature. Install it withcargo install celestial-pointing --features cli. - Breaking: Remove alt-azimuth support. INDAT files marked
:ALTAZor:GIMBALreturnError::Indat, and the alt-az termsIA,IE,CA,NPAE,ANandAWno longer exist. Harmonic terms with result codes S, A and E returnError::UnsupportedTerm. fit::fitfits the model as a nonlinear problem. Each Gauss-Newton step is solved by truncated SVD. Singular values belowFitOptions::fittoltimes the largest are dropped from the step and from the sigmas, so models with dependent terms still fit.FitOutcomereturns the coefficients with sigmas, the per-observation residuals, the sky RMS, the PSD and the singular values.- Terms are evaluated in chain order. Each term is evaluated at a working place that the earlier terms have moved. A term with
ModelTerm::parallelset uses the same place as the term before it.FLOPis applied as a vertical shift.Model::mount_to_skyapplies the model, andModel::sky_to_mountinverts it by Newton iteration. - Add the terms
FLOP,TX10,X2HCandDNP, alongsideIH,ID,CH,NP,MA,ME,TF,TX,FO,HCES,HCEC,DCES,DCECandDAF. Generic harmonic terms such asHDSH,HXCH2SDandHHSH%accept the angles H, D, A, Z, E and Q, whole multiples, and half-angle (%) multiples. - Apply refraction when reducing star places.
RunRefractionholds either fixedRefractionconstants or aRefractionModelKindthat computes them from the INDAT run record’s weather. The kinds areCiddor(ray trace, the default),HohenkerkSinclairandClosedForm. The shell sets refraction withREFRACT <A> <B>andREFMODEL [CIDDOR | HS | CLOSED]. - Reject stars on reading when they are at or below 10 degrees unrefracted elevation, or within 0.2 degrees of the zenith or a celestial pole. The INDAT option
ALLSKYkeeps every star. - Read and write INDAT Format 1 with
ObservationSet::from_indatandObservationSet::to_indat. Read and write OUTMOD withoutmod::parse_outmodandoutmod::format_outmod, including the&(parallel) and=(fixed) flags. INDAT Format 2, subsets and catalog-star records returnError::Indat. - Add
automodel::automodel, which the shell runs asFAUTO [<max harmonic> [<significance>]] [CROSS]. It starts from a basic model sized to the observation count. It then adds significantTF,TX10,DAFand harmonic sine/cosine pairs, removes weak terms, and masks outliers by leave-one-out residual. Aprogress::Progressimplementation receives each log line and can cancel the search.vetting(MVET) ranks the floating terms and removes weak ones.quality::leave_one_out_residualsandquality::jackknife_psd(LOO) report the leave-one-out residuals and the jackknife PSD. - Add
pointer::Pointerfor applying a fitted model at a site.Pointer::mount_forreturns the mount reading for an ICRS target, andPointer::sky_forreturns the ICRS direction for a mount reading. Both use EOP data when it is supplied.Observation::from_icrsbuilds an observation from an ICRS star and the raw encoder reading. - Add
pointing_run::PointingRun, which refits the model after each star is added. The basic terms grow fromIH IDtoIH ID NP CH ME MAas stars arrive. Addpolar_alignment::PolarAlignment::from_fit, which converts the fittedMEandMAinto polar axis adjustments with sigmas. - In a terminal, the
pointingbinary opens a full-screen UI with residual graphs, model and observation tabs, point masking, and a cancellableFAUTO.--plaingives a line editor, and a script path or stdin runs a script. The shell addsAPPEND,FLIST,LOO,G,INPRO/CALLprocedures andGC(SVG output). It dropsADJUST,APPLY,CHAIN,CLIST,CORRECT,GDEC,GHA,GHYST,GMAP,LST,OPTIMAL,OUTL,PARALLEL,PREDICT,RESETandSHOW. - Add a
serdefeature. Drop the dependencies onnalgebra,regex,rayon,bitflags,dirs,plottersandtextplots. Withoutcli, the library depends only on the celestial crates,libmandthiserror.
celestial-images
- Breaking: The crate root and the module files no longer re-export anything. Import each type from the module that defines it, for example
celestial_images::formats::image::Image,celestial_images::fits::io::reader::FitsFileorcelestial_images::xisf::reader::XisfFile.formats::unifiedis split intoformats::{image, astro_image, pixel_data, format, kind}. - Breaking: Removed
ImageWriter,TelescopeParams,formats::ImageInfo,FitsWriter,KeywordBuilder,FrameType,FitsImage,WcsInfo,HeaderParser,HeaderCardandHeader::get_keyword_value. Also removed: thericecompandfits::utilmodules,compress_tile,decompress_tile, the typedread_column_*table readers,XisfFile::header,XisfFile::read_image_data,XisfFile::fits_keywords,XisfWriter::set_fits_keywordandwcs_to_xisf_properties. Write files withImage::save,Image::save_fits_compressedorAstroImage. Set capture metadata with theirexposure,gain,filter,objectanddate_obssetters. Read values withHeader::get, table columns withget_column_values, and XISF pixels withread_image_data_typed. Thesimdfeature is removed. - Breaking:
PixelDatagainsI8,U32,I64andU64.TableValuegainsI8,U16,U32,U64,BitsandArray.XisfPropertyValuegainsBoolean,OtherandOtherArray, andCompressionAlgorithmgainsGzip2.ImageError,FitsError,XisfErrorandSerErrorhave new and removed variants. Update exhaustivematchexpressions. - Breaking:
Imagehas a new public field,xisf_properties.Keywordhas a new private field, so build keywords withKeyword::newor a typed constructor such asKeyword::realinstead of a struct literal. - Breaking:
Image::debayer,debayer_bilinear_u8anddebayer_bilinear_u16returnResult.Image::debayeraccepts every sample type, mirrors the edges and removesBAYERPAT,XBAYROFFandYBAYROFF. A non-mono image, or one smaller than 2x2, returnsInvalidDimensions. 0.1 left those images unchanged without an error. - Breaking:
Image::normalizeconverts integer pixels toF64. 0.1 kept the integer type, which rounded every value to 0 or 1. - Breaking:
AstroImagewrites uncompressed FITS by default. 0.1 wrote Rice-compressed tiles.compressed()takes aCompressionAlgorithminstead of abool.AstroImage::keywordreplaces an earlier card with the same name. 0.1 added a second card. - Breaking: Saving signed integer pixels to XISF returns an error. 0.1 wrapped negative values to large unsigned ones. Convert first with
PixelData::signed_to_offset_unsignedorPixelData::signed_to_float. XISF files that 0.1 wrote with LZ4 compression no longer open. 0.1 prefixed each LZ4 block with its length, and the XISF spec does not define that prefix. - Breaking: In SER,
SerHeader.byte_order: ByteOrderreplacesSerHeader.little_endian.SerHeader.file_idandSerReader::from_readerare removed.SerTimestampfields are private: useticks(),to_unix()orto_utc().SerHeader::frame_sizeandSerReader::iter_frames_rangereturnResult. A byte-order flag of 0 now reads as little-endian, which is how capture programs write it. 0.1 wrote 1 for little-endian, so 16-bit SER files from 0.1 now decode as big-endian.SerReader::read_frame_u16andSerReader::has_timestampsare new. - Add the
stretchmodule. ItsStretchtrait onImageprovides three methods:stf(an automatic midtones stretch set byStfParams),mad_normalizedandto_u8. Each returns a newImagewith the source’s keywords and XISF properties. - Fix FITS reading:
Image::openreads the first HDU that holds an image. This includesRICE_1,GZIP_1andGZIP_2tile-compressed images and quantized float images. 0.1 read only the primary HDU.Image::openappliesBSCALEandBZERO. The standard unsigned offsets load asU16,U32orU64. Other scaling loads asF64, andBLANKpixels in scaled data load as NaN. 0.1 applied no scaling and readBITPIX = 64as 32-bit.FitsFile::get_image_infoandFitsFile::read_hdu_with_datadecode compressed HDUs.- The header parser reads
CONTINUElong strings, doubled quotes andHIERARCHnames.FitsFile::get_header_valuereturns strings without the FITS quotes. Header::get_lastandImage::get_lastreturn the last card of a repeated keyword. Scaling and WCS cards use the last card.- A truncated file keeps the HDUs before the damage, and
FitsFile::scan_errorreports the problem.
- Fix FITS writing:
Image::savewritesI8,U16,U32andU64pixels with the standardBZERO. 0.1 castU16toi16without an offset, so values above 32767 read back negative.- Real values round-trip exactly, quotes in strings are escaped, long strings use
CONTINUE, and long keyword names useHIERARCH. Image::saveand compressed writes emit correctDATASUMandCHECKSUMcards.- Every
ImageandAstroImagesave writes a temporary file and then renames it, so a failed save leaves the target file unchanged. - Add
Image::save_fits_compressed.AstroImage::write_fitsacceptsi8,u16,u32andu64samples.
- Fix XISF reading and writing:
- Reading verifies SHA-1, SHA-256 and SHA-512 block checksums. It decodes byte-shuffled codecs such as
lz4+sh, and inline and embedded data blocks. UInt32images load asU32. 0.1 loaded them as wrappedI32.Image.xisf_propertiesandXisfFile::propertiesreturn an image’s properties. Property types the crate does not decode are written back unchanged.- A FITS WCS is saved as XISF astrometric solution properties, and those properties load back as FITS WCS keywords.
- Written files include the
Metadataelement that the spec requires. - Add
XisfFile::image_keywordsandXisfWriter::sha1_checksums.
- Reading verifies SHA-1, SHA-256 and SHA-512 block checksums. It decodes byte-shuffled codecs such as
- Fix FITS tables: column scaling,
TNULLnulls and variable-length arrays now read correctly. Read random-groups HDUs withRandomGroupsHdu::read_groups.Image::open_pngreads palette images and 1-, 2- and 4-bit images, drops the alpha channel, and limits memory use to a bound set by the file length.
celestial-ephemeris
- Breaking:
ElpMpp02Moon::geocentric_positionandgeocentric_statereturnVector3and(Vector3, Vector3)in ICRS, in AU and AU/day. They used to return[f64; 3]and[f64; 6]in km and km/day in the mean ecliptic of J2000.geocentric_position_icrsandgeocentric_state_icrsare removed. Multiply bycelestial_core::constants::AU_KMfor kilometres. - Breaking: The geocentric methods on the planets and
Vsop2013Suntake the Earth’s heliocentric place as a parameter:geocentric_position(&tdb, &earth_position)andgeocentric_state(&tdb, &earth_state). ComputeVsop2013Earth::new().heliocentric_state(&tdb)?once per epoch and pass it to each call. - Breaking: The crate root no longer re-exports
Vsop2013EarthandVsop2013Sun, andjplno longer re-exportsSpkFileandSpkSegment. Import fromearth,sunandjpl::spk. - Breaking:
SpkFile::compute_positionandcompute_statetake&TDBin place of a Julian datef64and returnVector3and(Vector3, Vector3)in km and km/s.SpkSegmentfields are private. Read them withbody(),center(),frame(),data_type(),start()andend(), where the last two returnTDB.SpkSegment::from_summary,contains_epoch,start_jd,end_jdandSpkFile::find_segmentare removed. - Breaking:
SpkErroris#[non_exhaustive]and no longer implementsCloneorPartialEq.Iowrapsstd::io::Error. TheSegmentNotFoundfieldepochis renamedjd. The new variants areInvalidEpoch,UnsupportedTypeandUnsupportedFrame.SpkErrorconverts intoAstroError. - SPK lookups chain through the solar system barycenter, so pairs a kernel doesn’t store directly, such as
MOONrelative toEARTH, return a result.SpkFile::openreads the whole kernel into memory and validates every segment. Only type 2 segments in the J2000 frame can be evaluated, and other segments return an error. Addbodies::MERCURYandbodies::VENUS. - Every theory returns an error for an epoch outside its published range, and for NaN or infinite epochs. VSOP2013 covers -4000 to +8000, its Pluto covers 0 to +4000, and ELP/MPP02 and
Vsop2013Earthcover -3000 to +3000. - Planet, Earth and Sun velocities come from the analytic series rates. They used to come from central differences over ±1 s.
- Regenerate the built-in series with more terms. VSOP2013 keeps 83,780 terms, up from 24,685, and ELP/MPP02 keeps 10,754 terms. Against DE432s over 1950 to 2050, geocentric directions are within 7 to 30 mas for Mercury through Saturn, 2.3 mas for the Sun and 38 mas for the Moon. Neptune is within 0.2“, Uranus 0.8“ and Pluto 3“.
ElpMpp02Moon::with_de405_fit()rotates to ICRS with the DE405 fit’s own frame constants. It used to use the lunar laser ranging fit’s obliquity.- Drop the
celestial-coords,memmap2andchronodependencies, and addthiserrorandwide. Theserdefeature only enablesserdein celestial-core and celestial-time. - In
vsop2013-genandelpmpp02-gen(featurecli),--thresholddefaults to each shipped table’s cut.vsop2013-genused to require it.elpmpp02-genused to default to 1e-5 while the shipped table used 1e-3. Generated tables record the command that produced them.
celestial-solver
- First release.
celestial-solverplate-solves an astronomical image. It takes acelestial_imagesImageand acelestial_catalogCatalog, and returns the image’s WCS. The WCS is a TAN projection, with SIP distortion when the fit selects it. A solve needs a position hint and a plate scale, because the solver does not search the whole sky. celestial_solver::solve::solve(&image, &catalog).run()returns aSolveResultor aSolveError. The solver reads three things from the FITS or XISF header:- the position hint, from the header WCS,
CRVAL1/2,RA/DECorOBJCTRA/OBJCTDEC - the epoch, from
MJD-OBSorDATE-OBS - the plate scale, from
FOCALLENandXPIXSZ
- the position hint, from the header WCS,
- Override header values with the builder setters
hint,epoch,focal_length_mm,pixel_size_umandplate_scale_arcsec. For PNG, TIFF or other images without a header,with_metadatasupplies all of these values. SolveResultholds the linear WCS (wcs), the SIP model (sip), the combinedfits_wcs, the matchedpairs, the detectedstarsandlog_odds.pixel_to_skyandsky_to_pixelapply the SIP distortion.- To store the solution,
to_fits_keywordsreturns the solution as FITS keywords.write_intoadds them to anImage, andsave_withwrites a new FITS or XISF file.to_xisf_propertiesbuilds XISF spline properties. - The solver rejects any match whose log-odds score (Lang et al. 2010) is below ln(10^9). The same inputs give the same solution on every run and with any thread count.
- The solver accepts every pixel type that
Imagereads, fromu8tof64, and treats NaN pixels as blank. Catalog stars are moved by proper motion to the image epoch.SolveParamstunes detection, matching, refinement and the highest SIP order, which defaults to 4. detect::find_bright_starsruns star detection on its own.annotate::Annotationdraws detections and a solve overlay onto an image.- The
image-solverbinary, built with theclifeature, solves one image and prints a report. With--outputit also writes the solved FITS or XISF file.