solvastro 0.1.1

A Rust blind plate solver
Documentation
// https://github.com/dstndstn/astrometry.net/blob/555b6ba637d19a8c35b7402fbc85499fb5db1945/include/astrometry/sip.h#L16-L50
use crate::coords::CoordCelestial;
use log::*;
use nalgebra::{Matrix2, Matrix3, Vector2, Vector3};
use polynomial::Polynomial;
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::fs::File;
use std::path::Path;

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct WcsTan {
    // fiducial point in pixel space
    pub crpix: Vector2<f64>,

    // fiducial point in world space
    pub crval: CoordCelestial,

    // Matrix for the linear transformation of relative pixel coordinates
    // (u,v) onto "intermediate world coordinates", which are in degrees
    // (x,y). The x,y coordinates are on the tangent plane.
    //
    //   u = pixel_x - crpix0
    //   v = pixel_y - crpix1
    //
    //   x  = [cd00 cd01] * u
    //   y    [cd10 cd11]   v
    //
    // where x,y are in intermediate world coordinates (i.e. x points
    // along negative ra and y points to positive dec) and u,v are in pixel
    // coordinates.
    pub cd: Matrix2<f64>,
    pub cd_inv: Matrix2<f64>,

    // spherical rotation matrices
    pub mtx_w2i: Matrix3<f64>,
    pub mtx_i2w: Matrix3<f64>,

    // SIP parameters
    sip_params: Option<(Vec<f64>, Vec<f64>)>,

    // cached polynomials
    #[serde(skip_serializing, skip_deserializing)]
    sip_polynomial: Option<(Polynomial<f64>, Polynomial<f64>)>,
}

impl WcsTan {
    pub fn new(crpix: Vector2<f64>, crval: CoordCelestial, cd: Matrix2<f64>) -> WcsTan {
        let mtx_w2i = WcsTan::create_world_to_iwc_matrix(crval);
        let mtx_i2w = mtx_w2i.transpose();
        let cd_inv: Matrix2<f64> = cd.try_inverse().unwrap();

        WcsTan {
            crpix,
            crval,
            cd,
            cd_inv,
            mtx_w2i,
            mtx_i2w,

            sip_params: None,
            sip_polynomial: None,
        }
    }

    fn setup_polynomial(&mut self) {
        if let Some(sip_params) = &self.sip_params {
            self.sip_polynomial = Some((
                Polynomial::new(sip_params.0.clone()),
                Polynomial::new(sip_params.1.clone()),
            ))
        }
    }

    pub fn with_updated_sip(&self, new_sip_params: (Vec<f64>, Vec<f64>)) -> WcsTan {
        let updated_sip_params = if let Some((x_params, y_params)) = &self.sip_params {
            (
                new_sip_params
                    .0
                    .iter()
                    .zip(x_params.iter())
                    .map(|(a, b)| a + b)
                    .collect(),
                new_sip_params
                    .1
                    .iter()
                    .zip(y_params.iter())
                    .map(|(a, b)| a + b)
                    .collect(),
            )
        } else {
            new_sip_params
        };

        debug!("SIP params updated to {:?}", &updated_sip_params);

        let updated_sip_polynomial = (
            Polynomial::new(updated_sip_params.0.clone()),
            Polynomial::new(updated_sip_params.1.clone()),
        );

        WcsTan {
            crpix: self.crpix,
            crval: self.crval,
            cd: self.cd,
            cd_inv: self.cd_inv,
            mtx_w2i: self.mtx_w2i,
            mtx_i2w: self.mtx_i2w,

            sip_params: Some(updated_sip_params),
            sip_polynomial: Some(updated_sip_polynomial),
        }
    }

    pub fn with_blank_sip(&self) -> WcsTan {
        WcsTan {
            crpix: self.crpix,
            crval: self.crval,
            cd: self.cd,
            cd_inv: self.cd_inv,
            mtx_w2i: self.mtx_w2i,
            mtx_i2w: self.mtx_i2w,

            sip_params: None,
            sip_polynomial: None,
        }
    }

    pub fn create_world_to_iwc_matrix(crval: CoordCelestial) -> Matrix3<f64> {
        let (sin_ra_p, cos_ra_p) = crval.ra.sin_cos();
        let (sin_dec_p, cos_dec_p) = crval.dec.sin_cos();

        Matrix3::new(
            cos_ra_p * sin_dec_p,
            sin_ra_p * sin_dec_p,
            -cos_dec_p,
            -sin_ra_p,
            cos_ra_p,
            0f64,
            cos_ra_p * cos_dec_p,
            sin_ra_p * cos_dec_p,
            sin_dec_p,
        )
    }

    pub fn world_2_iwc(&self, world: &Vector3<f64>) -> Vector3<f64> {
        self.mtx_w2i * world
    }

    pub fn iwc_2_world(&self, iwc: &Vector3<f64>) -> Vector3<f64> {
        self.mtx_i2w * iwc
    }

    // TODO: consider tan_project as it may be faster and we spend about 8%
    //       of cpu time in here
    pub fn iwc_2_proj_plane(iwc: &Vector3<f64>) -> Option<Vector2<f64>> {
        if iwc.z <= 0f64 {
            return None;
        }

        let w = (1f64 - iwc.z * iwc.z).sqrt();
        // getting rid of the to_degrees here gives us similar results to tan_project
        let rt = (w / iwc.z).to_degrees();

        let phi_mtx = iwc.y.atan2(iwc.x);

        Some(Vector2::new(rt * phi_mtx.sin(), -rt * phi_mtx.cos()))
    }

    pub fn proj_plane_2_iwc(&self, proj: &Vector2<f64>) -> Vector3<f64> {
        let radius = proj.magnitude();

        let phi = proj.x.atan2(-proj.y);

        let theta = (1f64 / radius.to_radians()).atan();

        (CoordCelestial {
            ra: phi,
            dec: theta,
        })
        .into()
    }

    pub fn proj_plane_2_pix(&self, proj: &Vector2<f64>) -> Vector2<f64> {
        let pix_coords: Vector2<f64> = self.cd_inv * proj;

        if let Some((p0, p1)) = &self.sip_polynomial {
            pix_coords + self.crpix + Vector2::new(p0.eval(pix_coords.x), p1.eval(pix_coords.y))
        } else {
            pix_coords + self.crpix
        }
    }

    pub fn proj_plane_2_pix_no_sip(&self, proj: &Vector2<f64>) -> Vector2<f64> {
        (self.cd_inv * proj) + self.crpix
    }

    pub fn pix_2_proj_plane(&self, pix: &Vector2<f64>) -> Vector2<f64> {
        // TODO: this SIP inversion is wrong. need an inverse polynomial
        /*
        if let Some((p0, p1)) = &self.sip_polynomial {
            self.cd * (pix - self.crpix - Vector2::new(p0.eval(pix.x), p1.eval(pix.y)))
        } else {
            self.cd * (pix - self.crpix)
        }*/

        self.cd * (pix - self.crpix)
    }

    pub fn world_2_pix(&self, world: &Vector3<f64>) -> Option<Vector2<f64>> {
        let iwc = self.world_2_iwc(&world);
        let proj_plane = WcsTan::iwc_2_proj_plane(&iwc);
        proj_plane.map(|pp| self.proj_plane_2_pix(&pp))
    }

    pub fn world_2_pix_no_sip(&self, world: &Vector3<f64>) -> Option<Vector2<f64>> {
        let iwc = self.world_2_iwc(&world);
        let proj_plane = WcsTan::iwc_2_proj_plane(&iwc);
        proj_plane.map(|pp| self.proj_plane_2_pix_no_sip(&pp))
    }

    pub fn pix_2_world(&self, pix: &Vector2<f64>) -> Vector3<f64> {
        let proj_plane = self.pix_2_proj_plane(pix);
        let iwc = self.proj_plane_2_iwc(&proj_plane);
        self.iwc_2_world(&iwc)
    }

    pub fn write_to_file(&self, filename: &str) -> Result<(), Box<dyn Error>> {
        let file = File::create(filename)?;
        serde_json::to_writer(file, &self)?;
        Ok(())
    }

    pub fn read_from_file(filename: &Path) -> Result<WcsTan, Box<dyn Error>> {
        let file = File::open(filename)?;
        let mut wcs: WcsTan = serde_json::from_reader(file)?;
        wcs.setup_polynomial();
        Ok(wcs)
    }
}