twitcher 0.7.2

Find template switch mutations in genomic data
use anyhow::Context as _;
use clap::ValueEnum;
use compact_genome::implementation::alphabets::dna_alphabet_or_n::DnaAlphabetOrN;
use lib_tsalign::a_star_aligner::configurable_a_star_align::MinLengthStrategySelector;
use lib_tsalign::a_star_aligner::template_switch_distance::TSMUncertaintyRangeExtensionMode;
use lib_tsalign::config::TemplateSwitchConfig;
use lib_tsalign::costs::U64Cost;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::str::FromStr;
use std::{fs::File, io::BufReader, time::Duration};
use tokio::sync::Semaphore;

use bytesize::ByteSize;

use crate::common::aligner::db::CliDatabaseArgs;
use crate::common::aligner::{AlignerSelector, fpa::FourPointAligner};

#[derive(clap::Args, Debug)]
#[command(next_help_heading = "Alignment")]
pub struct CliAlignmentArgs {
    /// Number of threads to use for the alignments. Defaults to the number of available cores.
    #[arg(long = "threads", value_name = "NUM")]
    pub num_threads: Option<usize>,

    /// Set an overall memory limit, for example 4gb or 500mb. It is split evenly across the threads.
    /// Defaults to the memory currently available on the machine, so results may differ between machines and runs unless it is set explicitly.
    #[arg(short, long, global = true, value_name = "EXPR", value_parser = ByteSize::from_str)]
    pub memory_limit: Option<ByteSize>,

    /// Set a timeout for each individual run of the aligner, as a number with a unit: `ms`, `s`, `m` or `h` (e.g. `30s`).
    /// If an alignment takes longer than that, it will fail and no template switch is found. Unlimited by default.
    #[arg(long = "aligner-timeout", value_name = "EXPR", value_parser = parse_duration)]
    pub aligner_timeout: Option<Duration>,

    /// How much padding should be considered in the alignment around a mutation cluster. This is the window to where a template switch may "jump" (e.g. 100 for +- 100 bps before and after a mutation cluster)
    #[arg(short, long, default_value_t = 200, value_name = "BASES")]
    pub padding: usize,

    /// How many extra bases to add on each side of the cluster when setting the alignment range.
    /// The alignment range marks the region of interest within the padded sequences; extending it
    /// gives the aligner slightly more context to anchor template switch boundaries.
    #[arg(long = "range-extension", default_value_t = 5, value_name = "BASES")]
    pub range_extension: usize,

    /// A config file for the costs (in custom .tsa format), this is used by the aligner.
    #[arg(short, long, value_name = "FILE")]
    pub costs: Option<String>,

    /// Force the aligner to NOT align with template switches, so no template switch is ever reported. Useful for performance benchmarks, useless otherwise.
    #[arg(long)]
    pub no_ts: bool,

    /// Use the Four-Point-Aligner, based on dynamic programming. While it has limited capabilities, it is generally faster.
    /// It cannot, however, find alignments that have indels in the inner part of the template switch or that have more than one template switch.
    /// A best effort is made to keep the costs consistent with the `--costs` argument, with some exceptions. The most notable one is that since
    /// this aligner is not gap-affine, there is no gap open cost. Only the cost for extending a gap is taken into account.
    #[arg(long = "fpa")]
    pub use_fpa: bool,

    /// Ignored with --fpa and --no-ts:  Select a strategy to determine lower bounds on the length of a template switch. This is an implementation detail and not part of the cost function.
    /// To enforce a minimum (or maximum) length of the inner part of a template switch, use the cost file.
    #[arg(long, value_name = "ML_STRATEGY", default_value_t)]
    pub min_length_strategy: MLSSelector,

    /// Ignored with --fpa and --no-ts: Select how to compute the uncertainty ranges around template switches. See the aligner repo for details.
    #[arg(long, value_name = "UR_MODE", default_value_t)]
    pub uncertainty_range_mode: URMSelector,

    /// Ignored with --fpa and --no-ts: Allow multiple template switches in the same solution to have different descendants. By default, all template switches in the solution must have the same descendant, but it can be either of the sequences (ref / alt).
    #[arg(long)]
    pub allow_mixed_descendants: bool,

    /// If specified, write the region of every failed alignment to this file, one per line,
    /// in samtools region format (chr:start-end, 1-based inclusive). The file can be passed
    /// directly to samtools/bcftools via -R or -T to retry or inspect failed regions.
    #[arg(long = "output-failed-alignments", value_name = "FILE")]
    pub failed_alignments_output: Option<String>,

    /// If specified, write one CSV row per alignment to this file, covering runtime, peak memory,
    /// where the result came from (a fresh computation, the in-memory cache or the database) and
    /// the statistics reported by the aligner. Clusters that map to the same alignment yield one
    /// row each; filter on `source == computed` to see only the alignments that were actually run.
    #[arg(long = "output-alignment-stats", value_name = "FILE")]
    pub alignment_stats_output: Option<String>,

    #[clap(flatten)]
    pub database: CliDatabaseArgs,
}

fn parse_duration(s: &str) -> anyhow::Result<Duration> {
    if s.is_empty() {
        anyhow::bail!("empty duration string");
    }

    let ix = s
        .find(|c: char| !c.is_ascii_digit() && c != '.')
        .ok_or_else(|| anyhow::anyhow!("no unit detected"))?;
    let (number, unit) = s.split_at_checked(ix).context("non-utf8 duration string")?;
    let value: u64 = number.trim().parse()?;

    let dur = match unit.trim() {
        "ms" => Duration::from_millis(value),
        "s" => Duration::from_secs(value),
        "m" => Duration::from_mins(value),
        "h" => Duration::from_hours(value),
        // This only works on Rust 1.91.0 and up
        // "m" => Duration::from_mins(value),
        // "h" => Duration::from_hours(value),
        _ => anyhow::bail!("unknown duration unit: {unit}"),
    };

    Ok(dur)
}

impl Default for CliAlignmentArgs {
    fn default() -> Self {
        Self {
            num_threads: None,
            memory_limit: None,
            aligner_timeout: None,
            padding: 200,
            range_extension: 5,
            costs: None,
            no_ts: false,
            use_fpa: false,
            min_length_strategy: MLSSelector::default(),
            uncertainty_range_mode: URMSelector::default(),
            allow_mixed_descendants: false,
            failed_alignments_output: None,
            alignment_stats_output: None,
            database: CliDatabaseArgs::default(),
        }
    }
}

fn default_costs() -> anyhow::Result<TemplateSwitchConfig<DnaAlphabetOrN, U64Cost>> {
    let costs = include_bytes!("../../../default_costs.tsa");
    TemplateSwitchConfig::read_plain(&costs[..]).context("unable to parse the default cost file")
}

impl CliAlignmentArgs {
    pub(super) fn init_aligner(
        &self,
    ) -> anyhow::Result<(
        AlignerSelector,
        TemplateSwitchConfig<DnaAlphabetOrN, U64Cost>,
    )> {
        let costs = if let Some(cost_path) = &self.costs {
            tracing::info!("Loading costs from {cost_path}");
            let file = BufReader::new(File::open(cost_path)?);
            TemplateSwitchConfig::read_plain(file)?
        } else {
            tracing::info!("Using default costs");
            default_costs()?
        };

        crate::common::settings_warnings::warn_about_alignment_settings(self, &costs);

        if self.use_fpa {
            let aligner = FourPointAligner::new(costs.clone(), self.no_ts);
            Ok((AlignerSelector::Fpa(aligner), costs))
        } else {
            let aligner = AlignerSelector::AStar {
                costs: costs.clone(),
                min_length_strategy: self.min_length_strategy,
                uncertainty_range_mode: self.uncertainty_range_mode,
                allow_mixed_descendants: self.allow_mixed_descendants,
                no_ts: self.no_ts,
            };
            Ok((aligner, costs))
        }
    }

    pub fn init_semaphore(&self) -> anyhow::Result<(Semaphore, usize)> {
        let n = if let Some(num) = self.num_threads {
            num.try_into()?
        } else {
            std::thread::available_parallelism()?
        };
        let sem = Semaphore::new(n.into());
        let total_memory = usize::try_from(
            self.memory_limit
                .unwrap_or_else(default_memory_limit)
                .as_u64(),
        )
        .context("The memory limit is too high")?;
        let memory_per_thread = total_memory / n;
        Ok((sem, memory_per_thread))
    }
}

#[derive(Default, ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MLSSelector {
    /// Do not compute lower bounds. Turns A* into Dijkstra.
    None,
    /// Compute a lower bound by looking ahead from each candidate jump.
    Lookahead,
    /// Check for perfect matches of minimum length and filter out imperfect matches. Note that
    /// this is only implemented for reverse template switches; with forward ones enabled, prefer `lookahead`.
    #[default]
    PreprocessFilter,
    /// Check for perfect matches of minimum length and compute a lower bound for imperfect matches.
    PreprocessPrice,
    /// Check for perfect matches of minimum length and cache the costs of imperfect matches.
    PreprocessLookahead,
}

impl From<MLSSelector> for MinLengthStrategySelector {
    fn from(value: MLSSelector) -> Self {
        match value {
            MLSSelector::None => Self::None,
            MLSSelector::Lookahead => Self::Lookahead,
            MLSSelector::PreprocessFilter => Self::PreprocessFilter,
            MLSSelector::PreprocessPrice => Self::PreprocessPrice,
            MLSSelector::PreprocessLookahead => Self::PreprocessLookahead,
        }
    }
}

impl Display for MLSSelector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let pv = self.to_possible_value().ok_or(std::fmt::Error)?;
        f.write_str(pv.get_name())
    }
}

#[derive(Default, ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum URMSelector {
    /// Do not compute uncertainty ranges; they are reported as invalid (`[-]`).
    None,
    /// Extend TS entrance and exit as far as possible without increasing the alignment cost.
    #[default]
    EqualCost,
    /// Like `equal-cost`, but ignore cost increases that are caused by changing the template switch geometry.
    /// For example, with this it is possible to report the minimum and maximum length of a perfect match,
    /// even if the minimum (maximum) length is smaller than what is specified via `--costs`.
    EqualCostIgnoreGeometry,
}

impl From<URMSelector> for TSMUncertaintyRangeExtensionMode {
    fn from(value: URMSelector) -> Self {
        match value {
            URMSelector::None => Self::None,
            URMSelector::EqualCost => Self::EqualCost,
            URMSelector::EqualCostIgnoreGeometry => Self::EqualCostIgnoreGeometry,
        }
    }
}

impl Display for URMSelector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let pv = self.to_possible_value().ok_or(std::fmt::Error)?;
        f.write_str(pv.get_name())
    }
}

fn default_memory_limit() -> ByteSize {
    let mut system = sysinfo::System::new_all();
    system.refresh_memory();
    ByteSize::b(system.available_memory())
}

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

    #[test]
    fn parse_duration_milliseconds() {
        assert_eq!(parse_duration("100ms").unwrap(), Duration::from_millis(100));
    }

    #[test]
    fn parse_duration_seconds() {
        assert_eq!(parse_duration("5s").unwrap(), Duration::from_secs(5));
    }

    #[test]
    fn parse_duration_minutes() {
        assert_eq!(parse_duration("2m").unwrap(), Duration::from_mins(2));
    }

    #[test]
    fn parse_duration_hours() {
        assert_eq!(parse_duration("1h").unwrap(), Duration::from_hours(1));
    }

    #[test]
    fn parse_duration_empty_is_error() {
        assert!(parse_duration("").is_err());
    }

    #[test]
    fn parse_duration_no_unit_is_error() {
        assert!(parse_duration("100").is_err());
    }

    #[test]
    fn parse_duration_unknown_unit_is_error() {
        assert!(parse_duration("10d").is_err());
    }

    #[test]
    fn parse_default_costs() {
        let _ = default_costs();
    }
}