solvastro 0.1.1

A Rust blind plate solver
Documentation
use super::star::Star;
use crate::coords::{get_midpoint, tan_project, CoordCartesian, CoordUnitSphere};
use serde::{Deserialize, Serialize};
use std::error::Error;

pub type QuadCode = [f64; 4];

#[allow(dead_code)]
const QUAD_FP_OFFSETS: [f64; 4] = [0.21f64, 0.21f64, 0.21f64, 0.21f64];
#[allow(dead_code)]
const QUAD_FP_MULTIPLIERS: [f64; 4] = [0.666f64, 0.666f64, 1.5f64, 0.666f64];

#[derive(
    rkyv_08::Archive,
    rkyv_08::Serialize,
    rkyv_08::Deserialize,
    Serialize,
    Deserialize,
    PartialEq,
    Debug,
    Copy,
    Clone,
)]
#[rkyv(crate=rkyv_08, derive(Debug))]
pub struct Quad {
    pub a: usize,
    pub b: usize,
    pub c: usize,
    pub d: usize,
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Copy, Clone)]
pub struct PotentialQuad {
    a_idx: usize,
    b_idx: usize,

    midpoint: CoordUnitSphere,
    a: CoordCartesian,
    b: CoordCartesian,

    inv_scale: f64,
    cos_theta: f64,
    sin_theta: f64,
}

impl Quad {
    pub fn contains(&self, idx: usize) -> bool {
        idx == self.a || idx == self.b || idx == self.c || idx == self.d
    }

    pub fn calc_code(&self, stars: &[Star]) -> Result<QuadCode, Box<dyn Error>> {
        // based on https://github.com/dstndstn/astrometry.net/blob/555b6ba637d19a8c35b7402fbc85499fb5db1945/blind/quad-utils.c
        // and https://arxiv.org/pdf/0910.2233.pdf (Lang et al 2009)
        /*
           We label the most widely-separated pair of stars “A” and “B”. These two stars
           define a local coordinate system. The remaining two stars are called “C” and “D”, and their
           positions in this local coordinate system are (xC, yC) and (xD, yD). The geometric hash code
           is simply the 4-vector (xC, yC, xD, yD). We require stars C and D to be within the circle
           that has stars A and B on its diameter. This hash code has some symmetries: swapping A
           and B converts the code to (1−xC, 1−yC, 1−xD, 1−yD) while swapping C and D converts
           (xC, yC, xD, yD) into (xD, yD, xC, yC). In practice, we break this symmetry by demanding
           that xC ≤ xD and that xC + xD ≤ 1; we consider only the permutation (or relabelling) of
           stars that satisfies these conditions (within noise tolerance).
        */

        let s_a: &CoordUnitSphere = &stars[self.a].spherical();
        let s_b: &CoordUnitSphere = &stars[self.b].spherical();
        let s_c: &CoordUnitSphere = &stars[self.c].spherical();
        let s_d: &CoordUnitSphere = &stars[self.d].spherical();

        let mid_ab = get_midpoint(s_a, s_b);

        let a = tan_project(s_a, &mid_ab).expect("A was on wrong side of the sky");
        let b = tan_project(s_b, &mid_ab).expect("B was on wrong side of the sky");
        let c = tan_project(s_c, &mid_ab).expect("C was on wrong side of the sky");
        let d = tan_project(s_d, &mid_ab).expect("D was on wrong side of the sky");

        // translate to place origin at a
        let ab = b - a;
        let ac = c - a;
        let ad = d - a;

        // rescale so that len AB = 1?
        // (nb len AB = sqrt 2 in fig 1 of Lang 2009?)
        let inv_scale: f64 = 1f64 / ab.norm_squared();

        // not sure how this rotation works, it does not match any trig id that I know? 😕
        //
        // a 0 degree rotation would be sin_theta = 0, cos_theta = 1.
        // plugging that into the below, we get:
        //     1 = y + x
        //     0 = y - x
        // the important part of the example above is that y = x to get 0 rotation.
        // this is the case when AB are aligned as per Lang 09 figure 1 already.
        // what y and x are in this case doesn't matter, as the scale factor will scale
        // them to 1, 1.
        //
        // what about a 90 degree rotation? that would be sin_theta = 1, cos_theta = 0
        // which gives us:
        // a    0 = y + x
        // b    1 = y - x
        //
        // a implies that y = -x, so B lies on the diagonal in the \ direction, 90deg
        // from / in the original.
        // Maybe this does work after all! And all done using no trig funcs or sqrts,
        // 1 divide, 12 mults, and a sprinkle of adds/subs. nice

        // create factors that combine the required rotation and scaling
        let cos_theta: f64 = (ab.y + ab.x) * inv_scale;
        let sin_theta: f64 = (ab.y - ab.x) * inv_scale;

        // rotate-and-scale
        let mut code = [
            ac.x * cos_theta + ac.y * sin_theta,
            -ac.x * sin_theta + ac.y * cos_theta,
            ad.x * cos_theta + ad.y * sin_theta,
            -ad.x * sin_theta + ad.y * cos_theta,
        ];

        // handle parity flipping
        let mut rodeos = 0;
        while rodeos <= 2 && (code[2] > code[0] || code[0] + code[2] > 1f64) {
            rodeos += 1;
            if code[2] > code[0] {
                code = [code[2], code[3], code[0], code[1]];
            }

            if code[0] + code[2] > 1f64 {
                code = [
                    1f64 - code[0],
                    1f64 - code[1],
                    1f64 - code[2],
                    1f64 - code[3],
                ];
            }
        }
        assert!(code[2] <= code[0] && code[0] + code[2] <= 1f64);

        Ok(code)
    }
}

impl PotentialQuad {
    pub fn new(a_idx: usize, b_idx: usize, stars: &[Star]) -> PotentialQuad {
        let s_a: &CoordUnitSphere = &stars[a_idx].spherical();
        let s_b: &CoordUnitSphere = &stars[b_idx].spherical();

        let midpoint: CoordUnitSphere = get_midpoint(s_a, s_b);

        let a = tan_project(s_a, &midpoint).expect("A on wrong side of sky to midpoint");
        let b = tan_project(s_b, &midpoint).expect("B on wrong side of sky to midpoint");

        let ab = b - a;
        let inv_scale: f64 = 1f64 / ab.norm_squared();

        let cos_theta: f64 = (ab.y + ab.x) * inv_scale;
        let sin_theta: f64 = (ab.y - ab.x) * inv_scale;

        PotentialQuad {
            a_idx,
            b_idx,
            midpoint,
            a,
            b,
            inv_scale,
            cos_theta,
            sin_theta,
        }
    }

    pub fn to_quad(&self, c: usize, d: usize) -> Quad {
        Quad {
            a: self.a_idx,
            b: self.b_idx,
            c,
            d,
        }
    }

    pub fn can_contain(&self, d_idx: usize, stars: &[Star]) -> bool {
        // see https://github.com/dstndstn/astrometry.net/blob/f5d4764f33543d008e7635009a8e49f7868e9344/solver/quad-builder.c#L62-L102

        let s_d: &CoordUnitSphere = &stars[d_idx].spherical();
        let r_d = tan_project(s_d, &self.midpoint);
        if r_d.is_none() {
            return false;
        }
        let d = r_d.unwrap();

        let ad = d - self.a;

        let x: f64 = ad.x * self.cos_theta + ad.y * self.sin_theta;
        let y: f64 = ad.x * -self.sin_theta + ad.y * self.cos_theta;

        // make sure it's in the circle centered at (0.5, 0.5)...
        // (x-1/2)^2 + (y-1/2)^2   <=   r^2
        // x^2-x+1/4 + y^2-y+1/4   <=   (1/sqrt(2))^2
        // x^2-x + y^2-y + 1/2     <=   1/2
        // x^2-x + y^2-y           <=   0
        let r: f64 = (x * x - x) + (y * y - y);

        r.is_sign_negative()
    }
}