solvastro 0.1.1

A Rust blind plate solver
Documentation
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use tinyset::Set64;

use super::solution::Solution;
use super::verified_solution::VerifiedSolutionState::InProgress;

const THRESHOLD_BAIL_CHECK_START_INDEX: usize = 15;

#[derive(Debug, Serialize, Clone, Deserialize)]
pub struct VerifiedSolution {
    pub solution: Option<Solution>,

    #[serde(skip)]
    threshold_bail: f64,
    #[serde(skip)]
    threshold_stop: f64,

    #[serde(skip)]
    state: VerifiedSolutionState,
    pub matches: Vec<ItemMatchResult>,

    // technically these can be derived.
    //#[serde(skip_serializing)]
    pub logodds: f64,
    //#[serde(skip_serializing)]
    best_idx: usize,
    //#[serde(skip_serializing)]
    pub best_logodds: f64,
    // worst_logodds: f64, // don't need

    // internal use
    #[serde(skip)]
    pub matched_cat_indices: Set64<usize>,

    // internal use. Map matched cat indices to (logodds, query item index)
    #[serde(skip)]
    matched_cat_map: HashMap<usize, (f64, usize)>,
}

impl VerifiedSolution {
    pub fn new(threshold_bail: f64, threshold_stop: f64, capacity: usize) -> VerifiedSolution {
        VerifiedSolution {
            solution: None,
            threshold_bail,
            threshold_stop,
            state: InProgress,
            matches: Vec::with_capacity(capacity),
            logodds: 0f64,
            best_idx: 0,
            best_logodds: f64::NEG_INFINITY,
            matched_cat_indices: Set64::with_capacity(capacity),
            matched_cat_map: HashMap::with_capacity(capacity),
        }
    }

    pub fn take_sol(self, solution: Solution) -> VerifiedSolution {
        VerifiedSolution {
            solution: Some(solution),
            ..self
        }
    }

    pub fn already_matched(&self, idx: usize) -> bool {
        self.matched_cat_indices.contains(idx)
    }

    pub fn get_existing_logodds(&self, index: usize) -> Option<f64> {
        self.matched_cat_map
            .get(&index)
            .map(|&(logodds, _)| logodds)
    }

    pub fn add_distractor(&mut self) {
        self.matches.push(ItemMatchResult::Distractor);

        if self.matches.len() >= THRESHOLD_BAIL_CHECK_START_INDEX
            && self.logodds < self.threshold_bail
        {
            self.state = VerifiedSolutionState::Bailed;
        }
    }

    pub fn add_conflict(&mut self) {
        self.matches.push(ItemMatchResult::Conflict);

        if self.matches.len() >= THRESHOLD_BAIL_CHECK_START_INDEX
            && self.logodds < self.threshold_bail
        {
            self.state = VerifiedSolutionState::Bailed;
        }
    }

    pub fn replace_match(
        &mut self,
        field: usize,
        index: usize,
        logodds: f64,
        field_x: f64,
        field_y: f64,
        index_x: f64,
        index_y: f64,
        index_name: &str,
    ) -> f64 {
        let index_to_replace = self
            .matches
            .iter()
            .position(|m| {
                if let ItemMatchResult::Match { star_idx, .. } = m {
                    index == *star_idx
                } else {
                    false
                }
            })
            .unwrap();

        self.matches[index_to_replace] = ItemMatchResult::Conflict;

        self.add_match(
            field, index, logodds, field_x, field_y, index_x, index_y, index_name,
        )
    }

    pub fn add_match(
        &mut self,
        field: usize,
        index: usize,
        logodds: f64,
        field_x: f64,
        field_y: f64,
        index_x: f64,
        index_y: f64,
        index_name: &str,
    ) -> f64 {
        self.matches.push(ItemMatchResult::Match {
            field,
            star_idx: index,
            logodds,
            field_x,
            field_y,
            index_x,
            index_y,
            index_name: index_name.to_string(),
        });
        self.matched_cat_indices.insert(index);
        self.matched_cat_map.insert(index, (logodds, field));

        self.logodds += logodds;

        if self.logodds > self.best_logodds {
            self.best_logodds = self.logodds;
            self.best_idx = self.matches.len();
        }

        if self.logodds > self.threshold_stop {
            self.state = VerifiedSolutionState::Stopped;
        }

        self.logodds
    }

    pub fn should_stop(&self) -> bool {
        self.state == VerifiedSolutionState::Bailed || self.state == VerifiedSolutionState::Stopped
    }

    // 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(())
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub enum ItemMatchResult {
    #[allow(dead_code)]
    Filtered, // should be used for quad stars

    Distractor,
    Conflict,
    Match {
        field: usize,
        star_idx: usize,
        logodds: f64,
        field_x: f64,
        field_y: f64,
        index_x: f64,
        index_y: f64,
        index_name: String,
    },
}

impl ItemMatchResult {
    pub fn is_match(&self) -> bool {
        !matches!(
            *self,
            ItemMatchResult::Filtered | ItemMatchResult::Distractor | ItemMatchResult::Conflict
        )
    }
}

#[derive(Debug, Deserialize, PartialEq, Serialize, Clone)]
pub enum VerifiedSolutionState {
    InProgress,
    Bailed,
    Stopped,
}

impl Default for VerifiedSolutionState {
    fn default() -> Self {
        VerifiedSolutionState::Stopped
    }
}