use alloc::collections::BTreeMap;
use crate::err;
use crate::error::Result;
mod eval;
mod load;
mod projection;
mod spline;
pub use projection::{Rotation, celestial_to_native, deproject, native_to_celestial, project};
pub use spline::{Spline, monomials, polynomial_terms, wendland};
pub const NAMESPACE: &str = "AstrometricSolution";
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Version {
pub major: u32,
pub minor: u32,
}
impl Version {
pub const SUPPORTED: Version = Version { major: 1, minor: 0 };
pub fn parse(text: &str) -> Result<Self> {
let (major, minor) = text.trim().split_once('.').ok_or_else(|| {
err!(BadAttribute, "an astrometric solution version must be major.minor, got {text:?}")
})?;
let number = |field: &str, what: &str| -> Result<u32> {
field.trim().parse::<u32>().map_err(|_| {
err!(BadAttribute, "the {what} version {field:?} is not an unsigned integer")
})
};
Ok(Version { major: number(major, "major")?, minor: number(minor, "minor")? })
}
pub fn is_supported(self) -> bool {
self.major == Self::SUPPORTED.major
}
}
impl core::fmt::Display for Version {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}.{}", self.major, self.minor)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ProjectionClass {
Zenithal,
Cylindrical,
PseudoCylindrical,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ProjectionSystem {
Gnomonic,
Stereographic,
ZenithalEqualArea,
Orthographic,
PlateCarree,
Mercator,
HammerAitoff,
}
impl ProjectionSystem {
pub fn parse(name: &str) -> Option<Self> {
Some(match name.trim() {
"Gnomonic" => ProjectionSystem::Gnomonic,
"Stereographic" => ProjectionSystem::Stereographic,
"ZenithalEqualArea" => ProjectionSystem::ZenithalEqualArea,
"Orthographic" => ProjectionSystem::Orthographic,
"PlateCarree" => ProjectionSystem::PlateCarree,
"Mercator" => ProjectionSystem::Mercator,
"HammerAitoff" => ProjectionSystem::HammerAitoff,
_ => return None,
})
}
pub fn name(self) -> &'static str {
match self {
ProjectionSystem::Gnomonic => "Gnomonic",
ProjectionSystem::Stereographic => "Stereographic",
ProjectionSystem::ZenithalEqualArea => "ZenithalEqualArea",
ProjectionSystem::Orthographic => "Orthographic",
ProjectionSystem::PlateCarree => "PlateCarree",
ProjectionSystem::Mercator => "Mercator",
ProjectionSystem::HammerAitoff => "HammerAitoff",
}
}
pub fn class(self) -> ProjectionClass {
match self {
ProjectionSystem::Gnomonic
| ProjectionSystem::Stereographic
| ProjectionSystem::ZenithalEqualArea
| ProjectionSystem::Orthographic => ProjectionClass::Zenithal,
ProjectionSystem::PlateCarree | ProjectionSystem::Mercator => {
ProjectionClass::Cylindrical
}
ProjectionSystem::HammerAitoff => ProjectionClass::PseudoCylindrical,
}
}
pub fn default_reference_native(self) -> [f64; 2] {
match self.class() {
ProjectionClass::Zenithal => [0.0, 90.0],
_ => [0.0, 0.0],
}
}
}
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub enum CelestialReferenceSystem {
#[default]
Icrs,
Gcrs,
Other(String),
}
impl CelestialReferenceSystem {
pub fn parse(name: &str) -> Self {
match name.trim() {
"ICRS" => CelestialReferenceSystem::Icrs,
"GCRS" => CelestialReferenceSystem::Gcrs,
other => CelestialReferenceSystem::Other(other.to_string()),
}
}
pub fn name(&self) -> &str {
match self {
CelestialReferenceSystem::Icrs => "ICRS",
CelestialReferenceSystem::Gcrs => "GCRS",
CelestialReferenceSystem::Other(name) => name,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BasisFunction {
ThinPlateSpline,
VariableOrder,
Gaussian,
Multiquadric,
InverseMultiquadric,
InverseQuadratic,
}
impl BasisFunction {
pub fn parse(name: &str) -> Option<Self> {
Some(match name.trim() {
"ThinPlateSpline" => BasisFunction::ThinPlateSpline,
"VariableOrder" => BasisFunction::VariableOrder,
"Gaussian" => BasisFunction::Gaussian,
"Multiquadric" => BasisFunction::Multiquadric,
"InverseMultiquadric" => BasisFunction::InverseMultiquadric,
"InverseQuadratic" => BasisFunction::InverseQuadratic,
_ => return None,
})
}
pub fn name(self) -> &'static str {
match self {
BasisFunction::ThinPlateSpline => "ThinPlateSpline",
BasisFunction::VariableOrder => "VariableOrder",
BasisFunction::Gaussian => "Gaussian",
BasisFunction::Multiquadric => "Multiquadric",
BasisFunction::InverseMultiquadric => "InverseMultiquadric",
BasisFunction::InverseQuadratic => "InverseQuadratic",
}
}
pub fn has_shape_parameter(self) -> bool {
matches!(
self,
BasisFunction::Gaussian
| BasisFunction::Multiquadric
| BasisFunction::InverseMultiquadric
| BasisFunction::InverseQuadratic
)
}
pub fn requires_polynomial(self) -> bool {
matches!(self, BasisFunction::ThinPlateSpline | BasisFunction::VariableOrder)
}
pub fn minimum_order(self) -> i32 {
match self {
BasisFunction::ThinPlateSpline => 2,
BasisFunction::VariableOrder => 3,
_ => 0,
}
}
pub fn eval(self, rho: f64, order: i32, epsilon: f64) -> f64 {
match self {
BasisFunction::ThinPlateSpline => {
if rho <= 0.0 {
0.0
} else {
rho * rho * rho.ln()
}
}
BasisFunction::VariableOrder => {
if rho <= 0.0 {
0.0
} else {
let r2 = rho * rho;
r2.powi(order - 1) * r2.ln()
}
}
BasisFunction::Gaussian => (-(epsilon * rho).powi(2)).exp(),
BasisFunction::Multiquadric => (1.0 + (epsilon * rho).powi(2)).sqrt(),
BasisFunction::InverseMultiquadric => 1.0 / (1.0 + (epsilon * rho).powi(2)).sqrt(),
BasisFunction::InverseQuadratic => 1.0 / (1.0 + (epsilon * rho).powi(2)),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum TermKind {
Global,
Local,
Fallback,
}
impl TermKind {
pub fn parse(name: &str) -> Option<Self> {
Some(match name.trim() {
"Global" => TermKind::Global,
"Local" => TermKind::Local,
"Fallback" => TermKind::Fallback,
_ => return None,
})
}
pub fn name(self) -> &'static str {
match self {
TermKind::Global => "Global",
TermKind::Local => "Local",
TermKind::Fallback => "Fallback",
}
}
pub fn parse_list(text: &str) -> Result<Vec<TermKind>> {
let mut out = Vec::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
let kind = TermKind::parse(line).ok_or_else(|| {
err!(Unsupported, "unknown astrometric distortion term kind {line:?}")
})?;
if !out.contains(&kind) {
out.push(kind);
}
}
if out.is_empty() {
return Err(err!(BadHeader, "a distortion model lists no term kinds"));
}
if out.contains(&TermKind::Fallback) && !out.contains(&TermKind::Local) {
return Err(err!(
BadHeader,
"a Fallback term may only exist together with Local terms"
));
}
Ok(out)
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Availability {
Complete,
UpTo { layer: u8, because: String },
None { because: String },
}
impl Availability {
pub fn usable_layer(&self) -> Option<u8> {
match self {
Availability::Complete => Some(4),
Availability::UpTo { layer, .. } => Some(*layer),
Availability::None { .. } => None,
}
}
pub fn is_usable(&self) -> bool {
self.usable_layer().is_some()
}
}
#[derive(Clone, Debug, Default)]
pub struct SolutionProperties {
properties: BTreeMap<String, String>,
}
impl SolutionProperties {
pub fn insert(&mut self, id: &str, value: String) {
if let Some(rest) = id.strip_prefix("AstrometricSolution:") {
self.properties.insert(rest.to_string(), value);
}
}
pub fn get(&self, key: &str) -> Option<&str> {
self.properties.get(key).map(String::as_str)
}
pub fn is_empty(&self) -> bool {
self.properties.is_empty()
}
pub fn keys(&self) -> impl Iterator<Item = &str> {
self.properties.keys().map(String::as_str)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Projection {
pub system: ProjectionSystem,
pub reference_celestial: [f64; 2],
pub reference_image: [f64; 2],
pub linear_transformation: [[f64; 2]; 2],
pub reference_native: Option<[f64; 2]>,
pub celestial_pole_native: Option<[f64; 2]>,
pub celestial_reference_system: CelestialReferenceSystem,
}
#[derive(Clone, PartialEq, Debug)]
pub struct ProjectiveTransformation {
pub image_to_projection: [[f64; 3]; 3],
pub projection_to_image: [[f64; 3]; 3],
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Direction {
ImageToProjection,
ProjectionToImage,
}
impl Direction {
pub fn name(self) -> &'static str {
match self {
Direction::ImageToProjection => "ImageToProjection",
Direction::ProjectionToImage => "ProjectionToImage",
}
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct SplinePair {
pub x: Spline,
pub y: Spline,
}
impl SplinePair {
pub fn eval(
&self,
point: [f64; 2],
direction: &DistortionDirection,
scratch: &mut Vec<f64>,
) -> [f64; 2] {
let basis = direction.basis_function;
let order = direction.order;
let polynomial = direction.polynomial;
[
self.x.eval(point, basis, order, polynomial, scratch),
self.y.eval(point, basis, order, polynomial, scratch),
]
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct LocalTerm {
pub center: [f64; 2],
pub radius: f64,
pub spline: SplinePair,
}
#[derive(Clone, PartialEq, Debug)]
pub struct FallbackTerm {
pub threshold: f64,
pub spline: SplinePair,
}
#[derive(Clone, PartialEq, Debug)]
pub struct DistortionDirection {
pub basis_function: BasisFunction,
pub order: i32,
pub polynomial: bool,
pub terms: Vec<TermKind>,
pub global: Option<SplinePair>,
pub local: Vec<LocalTerm>,
pub fallback: Option<FallbackTerm>,
}
impl DistortionDirection {
pub fn validate(&self) -> Result<()> {
if self.order < self.basis_function.minimum_order() {
return Err(err!(
BadHeader,
"the {} basis function requires an order of at least {}, got {}",
self.basis_function.name(),
self.basis_function.minimum_order(),
self.order
));
}
if self.basis_function.requires_polynomial() && !self.polynomial {
return Err(err!(
BadHeader,
"the {} basis function requires a polynomial part",
self.basis_function.name()
));
}
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct DistortionModel {
pub image_to_projection: DistortionDirection,
pub projection_to_image: DistortionDirection,
}
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct Provenance {
pub catalog: Option<String>,
pub creation_time: Option<String>,
pub creator_application: Option<String>,
pub creator_module: Option<String>,
pub creator_os: Option<String>,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Solution {
pub version: Version,
pub projection: Projection,
pub projective: Option<ProjectiveTransformation>,
pub distortion: Option<DistortionModel>,
pub provenance: Provenance,
pub availability: Availability,
}
impl Solution {
pub fn usable_layer(&self) -> u8 {
self.availability.usable_layer().unwrap_or(0)
}
}
pub fn read(reader: &crate::Reader, image: &crate::header::Element) -> Result<Option<Solution>> {
use crate::property::{Property, Shape};
let mut scalars: BTreeMap<String, String> = BTreeMap::new();
let mut blocks: BTreeMap<String, &crate::header::Element> = BTreeMap::new();
for element in image.children_named("Property") {
let Some(id) = element.attr("id") else { continue };
let Some(key) = id.strip_prefix("AstrometricSolution:") else { continue };
if element.data.location.is_some() {
blocks.insert(key.to_string(), element);
} else if let Some(value) = element.attr("value") {
scalars.insert(key.to_string(), value.to_string());
} else if let Some(text) = element.data.text.as_deref() {
scalars.insert(key.to_string(), text.trim().to_string());
}
}
if scalars.is_empty() && blocks.is_empty() {
return Ok(None);
}
let numbers = |key: &str| -> Result<Option<Vec<f64>>> {
let Some(element) = blocks.get(key) else { return Ok(None) };
let property = Property::parse(element)?;
if !matches!(property.kind.shape, Shape::Vector | Shape::Matrix) {
return Err(err!(
BadHeader,
"AstrometricSolution:{key} must be a vector or matrix property"
));
}
let bytes = reader.block(&element.data)?;
let expected = property.data_size().unwrap_or(0);
if bytes.len() as u64 != expected {
return Err(err!(
Truncated,
"AstrometricSolution:{key} declares {expected} bytes but its block holds {}",
bytes.len()
));
}
let (chunks, _) = bytes.as_chunks::<8>();
let big = element.data.byte_order == crate::block::ByteOrder::Big;
Ok(Some(
chunks
.iter()
.map(|c| if big { f64::from_be_bytes(*c) } else { f64::from_le_bytes(*c) })
.collect(),
))
};
let required_numbers = |key: &str, n: usize| -> Result<Vec<f64>> {
let values = numbers(key)?.ok_or_else(|| {
err!(BadHeader, "an astrometric solution has no AstrometricSolution:{key}")
})?;
if values.len() != n {
return Err(err!(
BadHeader,
"AstrometricSolution:{key} needs {n} values, got {}",
values.len()
));
}
Ok(values)
};
let version_text = scalars.get("Version").ok_or_else(|| {
err!(BadHeader, "an astrometric solution has no AstrometricSolution:Version")
})?;
let version = Version::parse(version_text)?;
if !version.is_supported() {
return Err(err!(
Unsupported,
"astrometric solution revision {version} is not supported by this decoder, \
which implements {}; its properties are preserved but not interpreted",
Version::SUPPORTED
));
}
let system_text = scalars.get("ProjectionSystem").ok_or_else(|| {
err!(BadHeader, "an astrometric solution has no AstrometricSolution:ProjectionSystem")
})?;
let Some(system) = ProjectionSystem::parse(system_text) else {
return Err(err!(
Unsupported,
"unknown astrometric projection system {system_text:?}, \
which makes the whole solution unavailable"
));
};
let pair = |v: Vec<f64>| -> [f64; 2] { [v[0], v[1]] };
let linear = required_numbers("LinearTransformationMatrix", 4)?;
let projection = Projection {
system,
reference_celestial: pair(required_numbers("ReferenceCelestialCoordinates", 2)?),
reference_image: pair(required_numbers("ReferenceImageCoordinates", 2)?),
linear_transformation: [[linear[0], linear[1]], [linear[2], linear[3]]],
reference_native: numbers("ReferenceNativeCoordinates")?.map(pair),
celestial_pole_native: numbers("CelestialPoleNativeCoordinates")?.map(pair),
celestial_reference_system: scalars
.get("CelestialReferenceSystem")
.map(|s| CelestialReferenceSystem::parse(s))
.unwrap_or_default(),
};
let to_3x3 = |v: Vec<f64>| -> [[f64; 3]; 3] {
[[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]
};
let forward = numbers("ProjectiveTransformation:ImageToProjection")?;
let inverse = numbers("ProjectiveTransformation:ProjectionToImage")?;
let projective = match (forward, inverse) {
(Some(f), Some(i)) if f.len() == 9 && i.len() == 9 => Some(ProjectiveTransformation {
image_to_projection: to_3x3(f),
projection_to_image: to_3x3(i),
}),
(None, None) => None,
_ => {
return Err(err!(
BadHeader,
"an astrometric solution has only one direction of its projective \
transformation, or one of the wrong size; both are required together"
));
}
};
let mut availability = Availability::Complete;
let mut distortion = None;
let has_distortion = scalars.keys().any(|k| k.starts_with("DistortionModel:"));
if has_distortion {
let fetch = load::Blocks { reader, elements: blocks.clone(), scalars: &scalars };
match read_distortion(&scalars).and_then(|mut model| {
load::load(&mut model.image_to_projection, &fetch, "ImageToProjection")?;
load::load(&mut model.projection_to_image, &fetch, "ProjectionToImage")?;
Ok(model)
}) {
Ok(model) => {
if projective.is_none() {
return Err(err!(
BadHeader,
"an astrometric solution has a distortion model but no projective \
transformation, which must be present whenever the third layer is"
));
}
distortion = Some(model);
}
Err(e) => {
availability = Availability::UpTo {
layer: if projective.is_some() { 2 } else { 1 },
because: e.message().to_string(),
};
}
}
}
let provenance = Provenance {
catalog: scalars.get("Catalog").cloned(),
creation_time: scalars.get("CreationTime").cloned(),
creator_application: scalars.get("CreatorApplication").cloned(),
creator_module: scalars.get("CreatorModule").cloned(),
creator_os: scalars.get("CreatorOS").cloned(),
};
Ok(Some(Solution { version, projection, projective, distortion, provenance, availability }))
}
fn read_distortion(scalars: &BTreeMap<String, String>) -> Result<DistortionModel> {
let direction = |which: &str| -> Result<DistortionDirection> {
let key = |leaf: &str| format!("DistortionModel:{which}:{leaf}");
let text = |leaf: &str| scalars.get(&key(leaf)).map(String::as_str);
let basis_text = text("BasisFunction")
.ok_or_else(|| err!(BadHeader, "a distortion model direction has no BasisFunction"))?;
let basis_function = BasisFunction::parse(basis_text).ok_or_else(|| {
err!(
Unsupported,
"unknown astrometric basis function {basis_text:?}, \
which makes the distortion model unavailable"
)
})?;
let order_text =
text("Order").ok_or_else(|| err!(BadHeader, "a distortion model has no Order"))?;
let order = order_text.trim().parse::<i32>().map_err(|_| {
err!(BadAttribute, "a distortion model Order {order_text:?} is not an integer")
})?;
let polynomial = match text("Polynomial") {
None => true,
Some(value) => match value.trim() {
"true" | "1" => true,
"false" | "0" => false,
other => {
return Err(err!(BadAttribute, "Polynomial must be a Boolean, got {other:?}"));
}
},
};
let terms_text =
text("Terms").ok_or_else(|| err!(BadHeader, "a distortion model has no Terms"))?;
let terms = TermKind::parse_list(terms_text)?;
let direction = DistortionDirection {
basis_function,
order,
polynomial,
terms,
global: None,
local: Vec::new(),
fallback: None,
};
direction.validate()?;
Ok(direction)
};
Ok(DistortionModel {
image_to_projection: direction("ImageToProjection")?,
projection_to_image: direction("ProjectionToImage")?,
})
}