use super::{ProjectionClass, ProjectionSystem};
const R: f64 = 180.0 / core::f64::consts::PI;
fn arg(x: f64, y: f64) -> f64 {
y.atan2(x).to_degrees()
}
fn reduce(mut angle: f64) -> f64 {
while angle > 180.0 {
angle -= 360.0;
}
while angle <= -180.0 {
angle += 360.0;
}
angle
}
pub fn reduce_ra(mut angle: f64) -> f64 {
angle %= 360.0;
if angle < 0.0 {
angle += 360.0;
}
angle
}
fn sin_d(degrees: f64) -> f64 {
degrees.to_radians().sin()
}
fn cos_d(degrees: f64) -> f64 {
degrees.to_radians().cos()
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Rotation {
pub pole: [f64; 2],
pub phi_p: f64,
}
impl Rotation {
pub fn new(
reference_celestial: [f64; 2],
reference_native: [f64; 2],
celestial_pole_native: Option<[f64; 2]>,
) -> Option<Self> {
let [alpha0, delta0] = reference_celestial;
let [phi0, theta0] = reference_native;
let (phi_p, theta_p) = match celestial_pole_native {
Some([phi_p, theta_p]) => (phi_p, theta_p),
None => (reduce(if delta0 >= theta0 { phi0 } else { phi0 + 180.0 }), 90.0),
};
if (theta0 - 90.0).abs() < f64::EPSILON {
return Some(Rotation { pole: [alpha0, delta0], phi_p });
}
let z =
(cos_d(theta0).powi(2) * cos_d(phi_p - phi0).powi(2) + sin_d(theta0).powi(2)).sqrt();
let delta_p = if z == 0.0 {
if delta0 != 0.0 {
return None;
}
theta_p.clamp(-90.0, 90.0)
} else {
let ratio = sin_d(delta0) / z;
if ratio.abs() > 1.0 {
return None;
}
let base = arg(cos_d(theta0) * cos_d(phi_p - phi0), sin_d(theta0));
let offset = ratio.acos().to_degrees();
let candidates = [reduce(base + offset), reduce(base - offset)];
let in_range: Vec<f64> =
candidates.iter().copied().filter(|d| (-90.0..=90.0).contains(d)).collect();
match in_range.len() {
0 => return None,
_ => *in_range
.iter()
.min_by(|a, b| (*a - theta_p).abs().total_cmp(&(*b - theta_p).abs()))
.expect("non-empty"),
}
};
let alpha_p = if (cos_d(delta_p) * cos_d(delta0)).abs() < 1e-12 {
if cos_d(delta0).abs() < 1e-12 {
alpha0
} else if delta_p > 0.0 {
alpha0 + phi_p - phi0 - 180.0
} else {
alpha0 - phi_p + phi0
}
} else {
alpha0
- arg(
(sin_d(theta0) - sin_d(delta_p) * sin_d(delta0))
/ (cos_d(delta_p) * cos_d(delta0)),
sin_d(phi_p - phi0) * cos_d(theta0) / cos_d(delta0),
)
};
let alpha_p = if alpha0 >= 0.0 {
reduce_ra(alpha_p)
} else {
let reduced = reduce_ra(alpha_p);
if reduced > 0.0 { reduced - 360.0 } else { reduced }
};
Some(Rotation { pole: [alpha_p, delta_p], phi_p })
}
}
fn robust_latitude(sine: f64, a: f64, b: f64) -> f64 {
sine.atan2(a.hypot(b)).to_degrees()
}
pub fn native_to_celestial(native: [f64; 2], rotation: Rotation) -> [f64; 2] {
let [phi, theta] = native;
let [alpha_p, delta_p] = rotation.pole;
let phi_p = rotation.phi_p;
if cos_d(delta_p).abs() < 1e-12 {
return if delta_p > 0.0 {
[reduce_ra(phi + alpha_p - phi_p + 180.0), theta]
} else {
[reduce_ra(alpha_p + phi_p - phi), -theta]
};
}
let d_phi = phi - phi_p;
let a = sin_d(theta) * cos_d(delta_p) - cos_d(theta) * sin_d(delta_p) * cos_d(d_phi);
let b = -cos_d(theta) * sin_d(d_phi);
let alpha = alpha_p + arg(a, b);
let delta = robust_latitude(
sin_d(theta) * sin_d(delta_p) + cos_d(theta) * cos_d(delta_p) * cos_d(d_phi),
a,
b,
);
[reduce_ra(alpha), delta]
}
pub fn celestial_to_native(celestial: [f64; 2], rotation: Rotation) -> [f64; 2] {
let [alpha, delta] = celestial;
let [alpha_p, delta_p] = rotation.pole;
let phi_p = rotation.phi_p;
if cos_d(delta_p).abs() < 1e-12 {
return if delta_p > 0.0 {
[reduce(alpha - alpha_p + phi_p - 180.0), delta]
} else {
[reduce(alpha_p + phi_p - alpha), -delta]
};
}
let d_alpha = alpha - alpha_p;
let a = sin_d(delta) * cos_d(delta_p) - cos_d(delta) * sin_d(delta_p) * cos_d(d_alpha);
let b = -cos_d(delta) * sin_d(d_alpha);
let phi = phi_p + arg(a, b);
let theta = robust_latitude(
sin_d(delta) * sin_d(delta_p) + cos_d(delta) * cos_d(delta_p) * cos_d(d_alpha),
a,
b,
);
[reduce(phi), theta]
}
pub fn project(native: [f64; 2], system: ProjectionSystem) -> Option<[f64; 2]> {
let [phi, theta] = native;
match system.class() {
ProjectionClass::Zenithal => {
let r_theta = zenithal_radius(theta, system)?;
Some([r_theta * sin_d(phi), -r_theta * cos_d(phi)])
}
ProjectionClass::Cylindrical => match system {
ProjectionSystem::PlateCarree => Some([phi, theta]),
ProjectionSystem::Mercator => {
if theta.abs() >= 90.0 {
return None;
}
Some([phi, R * ((90.0 + theta) / 2.0).to_radians().tan().ln()])
}
_ => None,
},
ProjectionClass::PseudoCylindrical => {
let denominator = 1.0 + cos_d(theta) * cos_d(phi / 2.0);
if denominator <= 0.0 {
return None;
}
let gamma = R * (2.0 / denominator).sqrt();
Some([2.0 * gamma * cos_d(theta) * sin_d(phi / 2.0), gamma * sin_d(theta)])
}
}
}
pub fn deproject(plane: [f64; 2], system: ProjectionSystem) -> Option<[f64; 2]> {
let [u, v] = plane;
match system.class() {
ProjectionClass::Zenithal => {
let phi = arg(-v, u);
let r_theta = u.hypot(v);
Some([phi, zenithal_latitude(r_theta, system)?])
}
ProjectionClass::Cylindrical => match system {
ProjectionSystem::PlateCarree => Some([u, v]),
ProjectionSystem::Mercator => Some([u, 2.0 * (v / R).exp().atan().to_degrees() - 90.0]),
_ => None,
},
ProjectionClass::PseudoCylindrical => {
let inside = 1.0 - (u / (4.0 * R)).powi(2) - (v / (2.0 * R)).powi(2);
if inside < 0.0 {
return None;
}
let z = inside.sqrt();
if z < core::f64::consts::FRAC_1_SQRT_2 {
return None;
}
let phi = 2.0 * arg(2.0 * z * z - 1.0, z * u / (2.0 * R));
let theta = (v * z / R).clamp(-1.0, 1.0).asin().to_degrees();
Some([phi, theta])
}
}
}
fn zenithal_radius(theta: f64, system: ProjectionSystem) -> Option<f64> {
Some(match system {
ProjectionSystem::Gnomonic => {
if theta <= 0.0 {
return None;
}
R / theta.to_radians().tan()
}
ProjectionSystem::Stereographic => {
if theta <= -90.0 {
return None;
}
2.0 * R * ((90.0 - theta) / 2.0).to_radians().tan()
}
ProjectionSystem::ZenithalEqualArea => 2.0 * R * sin_d((90.0 - theta) / 2.0),
ProjectionSystem::Orthographic => {
if theta < 0.0 {
return None;
}
R * cos_d(theta)
}
_ => return None,
})
}
fn zenithal_latitude(r_theta: f64, system: ProjectionSystem) -> Option<f64> {
Some(match system {
ProjectionSystem::Gnomonic => {
if r_theta == 0.0 {
90.0
} else {
(R / r_theta).atan().to_degrees()
}
}
ProjectionSystem::Stereographic => 90.0 - 2.0 * (r_theta / (2.0 * R)).atan().to_degrees(),
ProjectionSystem::ZenithalEqualArea => {
let s = r_theta / (2.0 * R);
if s > 1.0 {
return None;
}
90.0 - 2.0 * s.asin().to_degrees()
}
ProjectionSystem::Orthographic => {
let c = r_theta / R;
if c > 1.0 {
return None;
}
c.acos().to_degrees()
}
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn arg_follows_the_specifications_argument_order() {
assert!((arg(1.0, 0.0) - 0.0).abs() < 1e-12);
assert!((arg(0.0, 1.0) - 90.0).abs() < 1e-12);
assert!((arg(-1.0, 0.0) - 180.0).abs() < 1e-12, "the range is (-180, 180]");
assert!((arg(0.0, -1.0) + 90.0).abs() < 1e-12);
}
#[test]
fn every_projection_round_trips() {
for system in [
ProjectionSystem::Gnomonic,
ProjectionSystem::Stereographic,
ProjectionSystem::ZenithalEqualArea,
ProjectionSystem::Orthographic,
ProjectionSystem::PlateCarree,
ProjectionSystem::Mercator,
ProjectionSystem::HammerAitoff,
] {
for &phi in &[-170.0, -90.0, -30.0, 0.0, 45.0, 120.0, 179.0] {
for &theta in &[-80.0, -40.0, 0.0, 15.0, 60.0, 89.0] {
if system == ProjectionSystem::Orthographic && theta == 0.0 {
continue;
}
let Some(plane) = project([phi, theta], system) else { continue };
let Some([phi2, theta2]) = deproject(plane, system) else {
panic!("{} could not deproject {plane:?}", system.name())
};
assert!(
(theta - theta2).abs() < 1e-9,
"{}: latitude {theta} came back {theta2}",
system.name()
);
if theta.abs() < 89.9 {
assert!(
(reduce(phi - phi2)).abs() < 1e-9,
"{}: longitude {phi} came back {phi2}",
system.name()
);
}
}
}
}
}
#[cfg_attr(miri, ignore)]
#[test]
fn the_orthographic_limb_is_singular_but_bounded() {
let system = ProjectionSystem::Orthographic;
let plane = project([30.0, 0.0], system).expect("the limb is in domain");
let [_, theta] = deproject(plane, system).expect("and deprojects");
assert!(theta.abs() < 1e-5, "the limb came back at {theta}, further out than expected");
let plane = project([30.0, 1.0], system).expect("in domain");
let [_, theta] = deproject(plane, system).expect("deprojects");
assert!((theta - 1.0).abs() < 1e-9, "one degree in came back {theta}");
}
#[test]
fn zenithal_projections_put_the_native_pole_at_the_origin() {
for system in [
ProjectionSystem::Gnomonic,
ProjectionSystem::Stereographic,
ProjectionSystem::ZenithalEqualArea,
ProjectionSystem::Orthographic,
] {
let [u, v] = project([0.0, 90.0], system).expect("the pole is always in domain");
assert!(u.abs() < 1e-9 && v.abs() < 1e-9, "{}: pole at ({u}, {v})", system.name());
}
}
#[test]
fn the_gnomonic_domain_is_the_visible_hemisphere() {
assert!(project([0.0, 45.0], ProjectionSystem::Gnomonic).is_some());
assert!(project([0.0, 0.0], ProjectionSystem::Gnomonic).is_none());
assert!(project([0.0, -10.0], ProjectionSystem::Gnomonic).is_none());
}
#[test]
fn plate_carree_is_the_identity() {
assert_eq!(project([42.0, -17.0], ProjectionSystem::PlateCarree), Some([42.0, -17.0]));
}
#[test]
fn the_reference_point_maps_to_itself() {
let reference = [10.684, 41.269];
let rotation = Rotation::new(reference, [0.0, 90.0], None).expect("valid parameters");
assert_eq!(rotation.pole, reference);
let [alpha, delta] = native_to_celestial([0.0, 90.0], rotation);
assert!((alpha - reference[0]).abs() < 1e-9, "alpha {alpha}");
assert!((delta - reference[1]).abs() < 1e-9, "delta {delta}");
}
#[test]
fn the_spherical_rotation_round_trips() {
let rotation =
Rotation::new([83.822, -5.391], [0.0, 90.0], None).expect("valid parameters");
for &phi in &[-150.0, -60.0, 0.0, 30.0, 170.0] {
for &theta in &[-45.0, 0.0, 20.0, 75.0, 89.0] {
let celestial = native_to_celestial([phi, theta], rotation);
let [phi2, theta2] = celestial_to_native(celestial, rotation);
assert!((theta - theta2).abs() < 1e-9, "theta {theta} -> {theta2}");
if theta.abs() < 89.9 {
assert!(reduce(phi - phi2).abs() < 1e-9, "phi {phi} -> {phi2}");
}
}
}
}
}