solvastro 0.1.1

A Rust blind plate solver
Documentation
use crate::dynamic_index::star_index_container::{ReadableStarIndexContainer, SIDX};
use log::{debug, info};
use nalgebra::{Vector2, Vector3};
use polyfit_rs::polyfit_rs::polyfit;
// use crate::optimize_wcs_allparams_hagerzhang;
use super::solution::Solution;
use super::verified_solution::{ItemMatchResult::Match, VerifiedSolution};
use super::verifier::verify_item;
use crate::optimize_wcs_cdparams_neldermead;
use crate::settings::{TunerConfig, TunerSipMode, TunerWcsMode};
use crate::structs_f64::query::Query;

const STRONG_MATCH_THRESHOLD: f64 = 4.0f64;
const TERMINATION_THRESHOLD: f64 = 0.5f64;

// TODO: investigate trying to improve the solution by finding four matched stars that cover a large
//       area of the image and generating a synthetic quad match from them. Perhaps dont need the biggest
//       quad, but one whose centroid is close to the image centre and whose aspect ratio is closest to 1:1.
//       You could try and find the 4 stars closest to
//       [ (img_w/4, img_h/4), (3*img_w/4, img_h/4), (img_w/4, 3*img_h/4), (3*img_w/4, 3*img_h/4) ]
//       in order to get a most universal quad

pub fn tune_until_best(
    v_solution: VerifiedSolution,
    query: &Query,
    index: &ReadableStarIndexContainer,
    config: &TunerConfig,
    cat_star_query_log: &mut Vec<(Vector3<f64>, f32, usize)>,
) -> VerifiedSolution {
    let mut iteration: usize = 0;
    let mut old_logodds = v_solution.logodds;
    let mut old_v_solution = v_solution;

    loop {
        iteration += 1;
        let new_v_solution = tune_and_fit_once(
            old_v_solution.clone(),
            query,
            index,
            &config,
            cat_star_query_log,
        );
        let new_logodds = new_v_solution.logodds;

        info!(
            "tune {:}: Logodds updated to {:} (delta: {:})",
            iteration,
            new_logodds,
            new_logodds - old_logodds
        );
        if new_logodds < old_logodds {
            info!("Fuck, made it worse. Giving up and keeping the old one.");
            if config.sip_mode == TunerSipMode::Off {
                return old_v_solution;
            }
            return fit_sip_once(&query, &index, &old_v_solution, cat_star_query_log);
        } else if new_logodds - old_logodds < TERMINATION_THRESHOLD {
            info!("Just a tiny bit better. Stopping now.");

            if config.sip_mode == TunerSipMode::Off {
                return new_v_solution;
            }
            return fit_sip_once(&query, &index, &new_v_solution, cat_star_query_log);
        } else {
            info!("Let's give it another bam on the spice weasel.");
            old_logodds = new_logodds;
            old_v_solution = new_v_solution;
        }
    }
}

pub fn tune_and_fit_once(
    v_solution: VerifiedSolution,
    query: &Query,
    index: &ReadableStarIndexContainer,
    config: &TunerConfig,
    cat_star_query_log: &mut Vec<(Vector3<f64>, f32, usize)>,
) -> VerifiedSolution {
    debug!("Tuning WCS...");
    let tuned_solution = tune_wcs(v_solution, &query, &index, &config.wcs_mode);

    let tuned_v_solution = verify_item(tuned_solution, &query, &index, cat_star_query_log);
    info!("tuned up to logodds {:}", tuned_v_solution.logodds);
    debug!(
        "Tuned Solution WCS: {:?}",
        &tuned_v_solution.solution.as_ref().unwrap().wcs
    );

    if config.sip_mode != TunerSipMode::Every {
        return tuned_v_solution;
    }

    fit_sip_once(&query, &index, &tuned_v_solution, cat_star_query_log)
}

fn fit_sip_once(
    query: &&Query,
    index: &&ReadableStarIndexContainer,
    tuned_v_solution: &VerifiedSolution,
    cat_star_query_log: &mut Vec<(Vector3<f64>, f32, usize)>,
) -> VerifiedSolution {
    info!("Fitting SIP params...");
    let sip_params = fit_sip_coefficients(&tuned_v_solution);
    debug!("SIP params: ({:?}, {:?})", &sip_params.0, &sip_params.1);

    let sip_wcs = tuned_v_solution
        .solution
        .as_ref()
        .unwrap()
        .wcs
        .with_updated_sip(sip_params);
    let tuned_sol_fitted_sip = tuned_v_solution
        .solution
        .as_ref()
        .unwrap()
        .with_wcs(sip_wcs);

    let sip_v_sol = verify_item(tuned_sol_fitted_sip, &query, &index, cat_star_query_log);

    if sip_v_sol.logodds < tuned_v_solution.logodds {
        info!(
            "SIP made it worse! Keeping original. This should not happen, but whaddaya know. ({:?} -> {:?})",
            tuned_v_solution.logodds, sip_v_sol.logodds
        );
        return tuned_v_solution.clone();
    }

    sip_v_sol
}

pub fn tune_wcs(
    v_solution: VerifiedSolution,
    _query: &Query,
    index: &ReadableStarIndexContainer,
    wcs_tune_mode: &TunerWcsMode,
) -> Solution {
    let solution = &v_solution.solution.unwrap();

    let mut matched_query_positions: Vec<Vector2<f64>> = vec![];
    let mut matched_index_positions: Vec<Vector3<f64>> = vec![];
    for match_item in &v_solution.matches {
        if let Match {
            field_x,
            field_y,
            star_idx,
            logodds,
            ..
        } = match_item
        {
            if *logodds >= STRONG_MATCH_THRESHOLD {
                let star = index.get_star(*star_idx as SIDX);
                matched_query_positions.push(Vector2::new(*field_x, *field_y));
                matched_index_positions.push(star.spherical());
            }
        }
    }

    info!(
        "optimizing WCS with {:} strong matches",
        matched_index_positions.len()
    );

    let optimized_wcs = match wcs_tune_mode {
        // TunerWcsMode::HagerZhang => optimize_wcs_allparams_hagerzhang::optimize_wcs(
        //     &solution.wcs,
        //     &matched_index_positions,
        //     &matched_query_positions,
        // ),
        TunerWcsMode::NelderMead => optimize_wcs_cdparams_neldermead::optimize_wcs(
            &solution.wcs,
            &matched_index_positions,
            &matched_query_positions,
        ),
    };

    Solution {
        query_quad: solution.query_quad,
        cat_quad_idx: solution.cat_quad_idx,
        cat_quad_identifiers: solution.cat_quad_identifiers.clone(),
        code_error: solution.code_error,
        wcs: optimized_wcs,
    }
}

pub fn fit_sip_coefficients(verified_solution: &VerifiedSolution) -> (Vec<f64>, Vec<f64>) {
    let crpix_x = &verified_solution.solution.as_ref().unwrap().wcs.crpix.x;
    let crpix_y = &verified_solution.solution.as_ref().unwrap().wcs.crpix.y;
    let mut crp_dist_x: Vec<f64> = vec![];
    let mut residual_x: Vec<f64> = vec![];
    let mut crp_dist_y: Vec<f64> = vec![];
    let mut residual_y: Vec<f64> = vec![];

    for match_item in &verified_solution.matches {
        if let Match {
            field_x,
            field_y,
            index_x,
            index_y,
            ..
        } = match_item
        {
            let crpix_dist_x = crpix_x - field_x;
            let crpix_dist_y = crpix_y - field_y;
            let resid_x = index_x - field_x;
            let resid_y = index_y - field_y;

            crp_dist_x.push(crpix_dist_x);
            residual_x.push(resid_x);
            crp_dist_y.push(crpix_dist_y);
            residual_y.push(resid_y);
        }
    }

    debug!("crp_dist_x: {:?}", &crp_dist_x);
    debug!("residual_x: {:?}", &residual_x);
    debug!("crp_dist_y: {:?}", &crp_dist_y);
    debug!("residual_y: {:?}", &residual_y);

    let x_fit = polyfit(&crp_dist_x, &residual_x, 3).unwrap();
    let y_fit = polyfit(&crp_dist_y, &residual_y, 3).unwrap();

    debug!("x_fit: {:?}", &x_fit);
    debug!("y_fit: {:?}", &y_fit);
    (x_fit, y_fit)
}