solvastro 0.1.1

A Rust blind plate solver
Documentation
use itertools::Itertools;
use log::*;
use nalgebra::Vector2;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::error::Error;
use std::fs::File;

use kiddo::distance::squared_euclidean;
use kiddo::KdTree;

const IMAGE_POINT_MIN_SQ_SEP: f64 = 144f64; // min 12 pixels between image objects for verification

#[derive(Serialize, Deserialize, Debug)]
pub struct Query {
    pub filename: String,
    pub img_w: u32,
    pub img_h: u32,

    pub points: Vec<QueryPoint>,
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct QueryPoint {
    pub x: f64,
    pub y: f64,
    pub amplitude: f64,
    pub radius: f64,
}

impl PartialOrd for QueryPoint {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.amplitude.partial_cmp(&other.amplitude)
    }
}

impl PartialEq for QueryPoint {
    fn eq(&self, other: &Self) -> bool {
        self.amplitude == other.amplitude
    }
}

impl Query {
    pub fn new(
        filename: &str,
        img_w: u32,
        img_h: u32,
        mut source_points: Vec<QueryPoint>,
    ) -> Query {
        // sort points by biggest amplitude first
        source_points.sort_unstable_by(|&a, &b| b.partial_cmp(&a).unwrap());

        // deduplicate stars
        let mut points: Vec<QueryPoint> = vec![];
        let mut kd_img_obj: KdTree<f64, QueryPoint, 2> = KdTree::new();
        for p in source_points {
            let point: [f64; 2] = [p.x, p.y];
            if kd_img_obj
                .within(&point, IMAGE_POINT_MIN_SQ_SEP, &squared_euclidean)
                .expect("query within kd_img_obj failed")
                .is_empty()
            {
                kd_img_obj.add(&point, p).unwrap();
                points.push(p);
            } else {
                debug!("Discarding image point #{:?}, deduplication", &p);
            }
        }

        Query {
            filename: filename.to_owned(),
            img_w,
            img_h,
            points,
        }
    }

    pub fn get_img_centre(&self) -> Vector2<f64> {
        Vector2::new(self.img_w as f64 / 2f64, self.img_h as f64 / 2f64)
    }

    pub fn get_img_corner(&self) -> Vector2<f64> {
        Vector2::new(0f64, 0f64)
    }

    pub fn point_indices_by_magnitude(&self) -> Vec<usize> {
        self.points
            .iter()
            .enumerate()
            .sorted_by(|(_, &a), (_, &b)| b.amplitude.partial_cmp(&a.amplitude).unwrap())
            .map(|(pos, _)| pos)
            .collect()
    }

    // TODO: can't work out how to extract this into a trait with a default implementation,
    //       shared with VerifiedSolution
    pub fn save(&self, filepath: &str) -> Result<(), Box<dyn Error>> {
        let file = File::create(filepath)?;
        serde_json::to_writer(file, &self)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_img_centre() {
        let query = Query {
            filename: "test.jpg".parse().unwrap(),
            img_w: 4000,
            img_h: 3000,
            points: vec![],
        };

        let result = query.get_img_centre();

        assert_eq!(result.x, 2000f64);
        assert_eq!(result.y, 1500f64);
    }

    #[test]
    fn test_get_img_corner() {
        let query = Query {
            filename: "test.jpg".parse().unwrap(),
            img_w: 4000,
            img_h: 3000,
            points: vec![],
        };

        let result = query.get_img_corner();

        assert_eq!(result.x, 0f64);
        assert_eq!(result.y, 0f64);
    }
}