solvastro 0.1.1

A Rust blind plate solver
Documentation
use crate::dynamic_index::star_index::{BestNeighbour, NearestNeighbour};
use crate::structs_f64::{quad::Quad, star::Star};
use az::Az;
use std::fmt::Debug;
use std::fs::File;
use std::io::Write;
use std::num::NonZero;

pub(crate) use crate::dynamic_index::kdtree_trait::{
    load_kd_tree, save_kd_tree, DistanceMetric, KdTree,
};
pub use crate::dynamic_index::kdtree_trait::{
    FloatType, KdTreeDescriptor, KiddoV6ItemLeafMode, KiddoV6LeafStrategy, KiddoV6StemStrategy,
};
use crate::structs_f64::quad::ArchivedQuad;
use crate::structs_f64::star::ArchivedStar;
use memmap::Mmap;
use rkyv_08::vec::ArchivedVec;
use rkyv_08::{
    access_unchecked, rancor::Error as RkyvError, to_bytes, Archive, Deserialize, Serialize,
};

pub(crate) type SIDX = u32; // type used to index stars in the star kd-tree
pub(crate) type QIDX = u32; // type used to index quads in the quad kd-tree

#[derive(Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[rkyv(crate=rkyv_08)]
struct RawStarIndexDescriptorVersion(u32);

impl Debug for RawStarIndexDescriptorVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let version: StarIndexDescriptorVersion = self.clone().try_into().unwrap();
        write!(f, "{:?}", version)
    }
}

impl From<StarIndexDescriptorVersion> for RawStarIndexDescriptorVersion {
    fn from(version: StarIndexDescriptorVersion) -> Self {
        RawStarIndexDescriptorVersion(version as u32)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(u32)]
pub enum StarIndexDescriptorVersion {
    V1 = 0x53494458, // "SIDX" in ASCII
}

impl TryFrom<RawStarIndexDescriptorVersion> for StarIndexDescriptorVersion {
    type Error = anyhow::Error;
    fn try_from(value: RawStarIndexDescriptorVersion) -> Result<Self, Self::Error> {
        match value.0 {
            0x53494458 => Ok(StarIndexDescriptorVersion::V1),
            _ => Err(anyhow::anyhow!("Unknown descriptor version")),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
#[rkyv(crate=rkyv_08)]
pub struct StarIndexDescriptor {
    descriptor_version: RawStarIndexDescriptorVersion,
    pub star_float_type: FloatType,
    pub star_kd_tree_type: KdTreeDescriptor,
    pub quad_kd_tree_type: KdTreeDescriptor,
}

impl StarIndexDescriptor {
    pub fn new(
        star_float_type: FloatType,
        star_kd_tree_type: KdTreeDescriptor,
        quad_kd_tree_type: KdTreeDescriptor,
    ) -> Self {
        StarIndexDescriptor {
            descriptor_version: RawStarIndexDescriptorVersion::from(StarIndexDescriptorVersion::V1),
            star_float_type,
            star_kd_tree_type,
            quad_kd_tree_type,
        }
    }
}

#[derive(Debug, Archive, Serialize, Deserialize)]
#[rkyv(crate=rkyv_08)]
struct RawStarIndexContainer {
    descriptor: StarIndexDescriptor,
    vec_stars: Vec<Star>,
    vec_quads: Vec<Quad>,
    kd_stars_raw: Vec<u8>,
    kd_codes_raw: Vec<u8>,
}

pub struct WriteableStarIndexContainer {
    pub descriptor: StarIndexDescriptor,
    pub vec_stars: Vec<Star>,
    pub vec_quads: Vec<Quad>,
    pub kd_stars: Box<dyn KdTree<3>>,
    pub kd_codes: Box<dyn KdTree<4>>,
}

pub struct ReadableStarIndexContainer<'a> {
    pub descriptor: StarIndexDescriptor,
    vec_stars: &'a ArchivedVec<ArchivedStar>,
    vec_quads: &'a ArchivedVec<ArchivedQuad>,
    kd_stars: Box<dyn KdTree<3> + 'a>,
    kd_codes: Box<dyn KdTree<4> + 'a>,
}

impl Debug for WriteableStarIndexContainer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "StarIndexContainer {{ descriptor: {:?}, stars: {}, quads: {} }}",
            self.descriptor,
            self.vec_stars.len(),
            self.vec_quads.len()
        )
    }
}

impl Debug for ReadableStarIndexContainer<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "StarIndexContainer {{ descriptor: {:?}, stars: {}, quads: {} }}",
            self.descriptor,
            self.vec_stars.len(),
            self.vec_quads.len()
        )
    }
}

impl WriteableStarIndexContainer {
    pub fn save(self, filename: &str) -> anyhow::Result<()> {
        let WriteableStarIndexContainer {
            descriptor,
            vec_stars,
            vec_quads,
            kd_stars,
            kd_codes,
        } = self;

        let kd_stars_raw = save_kd_tree(&*kd_stars, &descriptor.star_kd_tree_type)?;
        let kd_codes_raw = save_kd_tree(&*kd_codes, &descriptor.quad_kd_tree_type)?;

        let raw_star_index_container = RawStarIndexContainer {
            descriptor,
            vec_stars,
            vec_quads,
            kd_stars_raw,
            kd_codes_raw,
        };

        let mut file = File::create(filename)?;
        let buf = to_bytes::<RkyvError>(&raw_star_index_container)?;
        file.write(&buf)?;

        Ok(())
    }
}
impl ReadableStarIndexContainer<'_> {
    pub fn load(buf: &Mmap) -> anyhow::Result<ReadableStarIndexContainer<'_>> {
        let ArchivedRawStarIndexContainer {
            descriptor,
            vec_stars,
            vec_quads,
            kd_stars_raw,
            kd_codes_raw,
        } = unsafe { access_unchecked::<ArchivedRawStarIndexContainer>(&buf) };

        let descriptor = rkyv_08::deserialize::<StarIndexDescriptor, RkyvError>(descriptor)?;

        let version: StarIndexDescriptorVersion =
            descriptor.descriptor_version.clone().try_into()?;
        println!("Loaded index version: {:?}", version);

        let kd_stars = load_kd_tree::<f32, 3>(kd_stars_raw, &descriptor.star_kd_tree_type)?;

        let kd_codes = load_kd_tree::<f32, 4>(kd_codes_raw, &descriptor.quad_kd_tree_type)?;

        let result = ReadableStarIndexContainer {
            descriptor: descriptor.clone(),
            vec_stars,
            vec_quads,
            kd_stars,
            kd_codes,
        };

        Ok(result)
    }
}

impl ReadableStarIndexContainer<'_> {
    pub fn best_n_stars_within(
        &self,
        query: &[f64; 3],
        radius: f64,
        max_qty: NonZero<usize>,
    ) -> Box<dyn Iterator<Item = BestNeighbour<f64, u32>>> {
        self.kd_stars.best_n_within_radius(
            query,
            radius.az::<f64>(),
            max_qty,
            DistanceMetric::SquaredEuclidean,
        )
    }

    pub fn best_n_stars_within_with_metric(
        &self,
        query: &[f64; 3],
        radius: f64,
        max_qty: NonZero<usize>,
        metric: DistanceMetric,
    ) -> Box<dyn Iterator<Item = BestNeighbour<f64, u32>>> {
        self.kd_stars
            .best_n_within_radius(query, radius.az::<f64>(), max_qty, metric)
    }

    pub fn get_star(&self, index: SIDX) -> &ArchivedStar {
        self.vec_stars.get(index as usize).unwrap()
    }

    pub fn get_quad(&self, index: QIDX) -> Quad {
        let archived_quad = self.vec_quads.get(index as usize).unwrap();
        rkyv_08::deserialize::<Quad, RkyvError>(archived_quad).unwrap()
    }

    #[allow(unused)]
    fn stars_within_radius(
        &self,
        query: &[f64; 3],
        radius: f64,
    ) -> Vec<NearestNeighbour<f64, SIDX>> {
        self.kd_stars
            .within_radius(query, radius.az::<f64>(), DistanceMetric::SquaredEuclidean)
    }

    pub fn quad_codes_within_radius(
        &self,
        query: &[f64; 4],
        radius: f64,
    ) -> Vec<NearestNeighbour<f64, SIDX>> {
        self.kd_codes
            .within_radius(query, radius.az::<f64>(), DistanceMetric::Manhattan)
    }
}