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_v6::{MutableKdTree, SquaredEuclidean};

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: MutableKdTree<f64, 2> = MutableKdTree::builder().build_from_entries(&[]).unwrap();
        for p in source_points {
            let point: [f64; 2] = [p.x, p.y];
            if kd_img_obj
                .query(&point)
                .within::<SquaredEuclidean<f64>>(IMAGE_POINT_MIN_SQ_SEP)
                .execute()
                .is_empty()
            {
                kd_img_obj.add(&point, points.len() as u32).expect("could not add point");
                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);
    }

    #[test]
    fn deduplicates_nearby_points_after_sorting_by_amplitude() {
        let query = Query::new(
            "test.jpg",
            100,
            100,
            vec![
                QueryPoint {
                    x: 5.0,
                    y: 5.0,
                    amplitude: 9.0,
                    radius: 1.0,
                },
                QueryPoint {
                    x: 20.0,
                    y: 0.0,
                    amplitude: 8.0,
                    radius: 1.0,
                },
                QueryPoint {
                    x: 0.0,
                    y: 0.0,
                    amplitude: 10.0,
                    radius: 1.0,
                },
            ],
        );

        assert_eq!(query.points.len(), 2);
        assert_eq!(query.points[0].amplitude, 10.0);
        assert_eq!(query.points[1].amplitude, 8.0);
    }
}