twitcher 0.7.5

Find template switch mutations in genomic data
use std::{cmp::Ordering, collections::HashMap, mem};

use anyhow::Context as _;
use tokio::io::AsyncBufReadExt;

use crate::common::{contig::ContigName, coords::GenomeRegion};

#[derive(Clone, Debug, Default)]
pub struct Regions(HashMap<ContigName, Vec<GenomeRegion>>);

impl Regions {
    // Sorts by chr, as specified by argument closure and then concats all
    pub fn into_linear<F: for<'a> Fn(&'a ContigName) -> usize>(
        mut self,
        cmp: F,
    ) -> Vec<GenomeRegion> {
        let mut keys: Vec<_> = self.0.keys().cloned().collect();
        keys.sort_by_key(cmp);

        keys.into_iter()
            .filter_map(move |key| self.0.remove(&key))
            .flatten()
            .collect()
    }

    pub fn overlaps(&self, query: &GenomeRegion) -> bool {
        let Some(list) = self.0.get(query.contig()) else {
            return false;
        };

        // find (index of) first region that is not entirely before the query
        let ix = list.partition_point(|reg| {
            reg.end_excl()
                .is_some_and(|e| e.position_0() <= query.start().position_0())
        });
        let Some(region) = list.get(ix) else {
            return false;
        };

        region.intersection(query).is_some()
    }
}

pub struct Targets {
    regions: Regions,
    last_contig: Option<ContigName>,
}

pub enum TargetQueryAnswer {
    Include,
    Exclude,
    NoMoreTargets,
}

impl Targets {
    pub const fn new(regions: Regions) -> Self {
        Self {
            regions,
            last_contig: None,
        }
    }

    /// Requirement: Each contig only appears in one continuous block
    pub fn query(&mut self, region: &GenomeRegion) -> TargetQueryAnswer {
        if self.regions.0.is_empty() {
            return TargetQueryAnswer::NoMoreTargets;
        }

        if let Some(last_contig) = &mut self.last_contig {
            if region.contig() != last_contig {
                self.regions.0.remove(last_contig);
                *last_contig = region.contig().clone();
            }
        } else {
            self.last_contig = Some(region.contig().clone());
        }

        if self.regions.overlaps(region) {
            TargetQueryAnswer::Include
        } else {
            TargetQueryAnswer::Exclude
        }
    }
}

pub trait RegionsDefinition {
    async fn read_regions(&self) -> anyhow::Result<Option<Regions>>;
}

#[derive(clap::Args, Clone, Debug, Default)]
#[command(next_help_heading = "Region selection")]
pub struct CliRegionsArgs {
    /// A list of regions to process, comma-separated or by repeating the flag. Each region shall be given in the format `chr1:100-200` or `chr1`. The reader will use the index of the input file to jump to the specified regions.
    /// Therefore, the input file must be indexed.
    #[arg(
        short = 'r',
        long = "regions",
        value_name = "LIST",
        value_delimiter = ','
    )]
    pub r_list: Vec<String>,

    /// Same as -r, but the list of regions is specified in a file. Each line corresponds to a region; each region may be either be a BED-like tab-separated definition, or a "position" in the form of `chr1:100-200`
    #[arg(short = 'R', long = "regions-file", value_name = "FILE")]
    pub r_file: Option<String>,
}

impl RegionsDefinition for CliRegionsArgs {
    async fn read_regions(&self) -> anyhow::Result<Option<Regions>> {
        read_regions(&self.r_list, self.r_file.as_ref()).await
    }
}

#[derive(clap::Args, Clone, Debug, Default)]
#[group(multiple = false)]
#[command(next_help_heading = "Region selection")]
pub struct CliTargetsArgs {
    /// A list of targets, comma-separated or by repeating the flag. Format is the same as for -r, but the reader will stream the whole input and skip non-matching records, instead of jumping to the specified regions. This may be more performant if the list of targets is long, or if the input has no index.
    /// A record counts as `targeted` when it overlaps with a target region.
    #[arg(
        short = 't',
        long = "targets",
        value_name = "LIST",
        value_delimiter = ','
    )]
    pub t_list: Vec<String>,

    /// Same as -t, but the list of targets is specified in a file. See also -R.
    #[arg(short = 'T', long = "targets-file", value_name = "FILE")]
    pub t_file: Option<String>,
}

impl RegionsDefinition for CliTargetsArgs {
    async fn read_regions(&self) -> anyhow::Result<Option<Regions>> {
        read_regions(&self.t_list, self.t_file.as_ref()).await
    }
}

async fn read_regions(list: &[String], file: Option<&String>) -> anyhow::Result<Option<Regions>> {
    let mut result: Option<Regions> = None;

    for reg in list {
        add_region(result.get_or_insert_default(), reg)?;
    }

    if let Some(path) = file {
        let fr = tokio::fs::File::open(path).await?;
        let mut br = tokio::io::BufReader::new(fr).lines();
        let mut line_number = 0;
        while let Some(reg) = br.next_line().await? {
            line_number += 1;
            if is_ignored_line(&reg) {
                continue;
            }
            add_region(result.get_or_insert_default(), &reg)
                .with_context(|| format!("in {path}, line {line_number}"))?;
        }
    }

    if let Some(ref mut regions) = result {
        for list in regions.0.values_mut() {
            list.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Less)); // they should all, by definition have the same contig, i.e. be comparable
            merge(list);
        }
    }

    Ok(result)
}

fn merge(list: &mut Vec<GenomeRegion>) {
    let mut reduced_list = Vec::with_capacity(list.len());

    let mut iter = list.iter().cloned();
    if let Some(mut current) = iter.next() {
        for region in iter {
            if let Some(merged) = current.merge(&region) {
                // They were mergeable; keep growing the current region
                current = merged;
            } else {
                // Not mergeable; finalize current and move on
                reduced_list.push(current);
                current = region;
            }
        }
        reduced_list.push(current);
    }

    reduced_list.shrink_to_fit();
    mem::swap(&mut reduced_list, list);
}

/// Blank lines, BED comments and the track/browser lines a BED file may start with carry no
/// region and are skipped rather than rejected.
fn is_ignored_line(line: &str) -> bool {
    let trimmed = line.trim_start();
    trimmed.is_empty()
        || trimmed.starts_with('#')
        || trimmed.starts_with("track ")
        || trimmed.starts_with("browser ")
}

/// A region that cannot be parsed is an error, not a warning: skipping it would silently narrow
/// the analysis, and skipping the only region given would produce an empty output that looks like
/// a legitimate result.
fn add_region(list: &mut Regions, region: &str) -> anyhow::Result<()> {
    let reg = GenomeRegion::parse(region.as_bytes())
        .with_context(|| format!("Cannot parse region '{region}'"))?;
    list.0.entry(reg.contig().clone()).or_default().push(reg);
    Ok(())
}

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

    /// `-r a,b` is one argument holding two regions; clap splits it on the comma.
    #[test]
    fn comma_separated_regions_are_split() {
        use clap::Parser as _;

        #[derive(clap::Parser)]
        struct Cli {
            #[command(flatten)]
            regions: CliRegionsArgs,
        }

        let cli = Cli::parse_from(["test", "-r", "chr1:1-1000,chr2"]);
        assert_eq!(cli.regions.r_list, ["chr1:1-1000", "chr2"]);
    }

    #[test]
    fn comma_separated_targets_are_split() {
        use clap::Parser as _;

        #[derive(clap::Parser)]
        struct Cli {
            #[command(flatten)]
            targets: CliTargetsArgs,
        }

        let cli = Cli::parse_from(["test", "-t", "chr1:1-1000,chr2"]);
        assert_eq!(cli.targets.t_list, ["chr1:1-1000", "chr2"]);
    }

    #[tokio::test]
    async fn regions_of_a_list_all_arrive() {
        let list = ["chr1:1-1000".to_string(), "chr2".to_string()];
        let regions = read_regions(&list, None).await.unwrap().unwrap();
        assert_eq!(regions.0.len(), 2);
    }

    /// An unparseable region must fail the run: silently dropping it would narrow the analysis,
    /// and dropping the only one would produce an empty output that looks legitimate.
    #[tokio::test]
    async fn an_unparseable_region_is_an_error() {
        let list = ["chr1:1-1000".to_string(), "not a region".to_string()];
        let error = read_regions(&list, None).await.unwrap_err();
        assert!(
            format!("{error:#}").contains("not a region"),
            "the message must name the offending region: {error:#}"
        );
    }

    /// IDs of the records in `tests/data/targets_overlap.vcf` that `targets` lets through.
    async fn included_record_ids(targets: &[&str]) -> Vec<String> {
        use rust_htslib::bcf::{self, Read as _};

        let list: Vec<String> = targets.iter().map(ToString::to_string).collect();
        let regions = read_regions(&list, None).await.unwrap().unwrap();
        let mut targets = Targets::new(regions);

        let mut reader = bcf::Reader::from_path("./tests/data/targets_overlap.vcf").unwrap();
        let mut included = Vec::new();
        for record in reader.records() {
            let record = record.unwrap();
            let region = GenomeRegion::try_from(&record).unwrap();
            match targets.query(&region) {
                TargetQueryAnswer::Include => {
                    included.push(String::from_utf8(record.id()).unwrap());
                }
                TargetQueryAnswer::Exclude => {}
                TargetQueryAnswer::NoMoreTargets => break,
            }
        }
        included
    }

    /// A record is selected as soon as one of its reference bases lies in a target, even if the
    /// target covers only its first, last or an inner base.
    #[tokio::test]
    async fn targets_select_partially_overlapping_records() {
        let included = included_record_ids(&[
            "chrZ:90-100",  // ends on the SNP
            "chrZ:203-210", // last deleted base of `del` (200-203)
            "chrZ:300-310", // anchor base of `ins`
            "chrZ:401-401", // inner base of `multi` (400-402)
            "chrZ:480-500", // first base of `mnv` (500-502)
        ])
        .await;
        assert_eq!(included, ["snp", "del", "ins", "multi", "mnv"]);
    }

    /// Targets that fill the gaps between the records touch them on both sides, but share no
    /// base with any of them.
    #[tokio::test]
    async fn targets_adjacent_to_records_select_nothing() {
        let included = included_record_ids(&[
            "chrZ:1-99",
            "chrZ:101-199",
            "chrZ:204-299",
            "chrZ:301-399",
            "chrZ:403-499",
            "chrZ:503-600",
        ])
        .await;
        assert!(included.is_empty(), "unexpectedly included: {included:?}");
    }

    #[test]
    fn bed_decorations_are_ignored() {
        for line in ["", "   ", "# comment", "track name=x", "browser hide all"] {
            assert!(is_ignored_line(line), "should be ignored: {line:?}");
        }
        for line in ["chr1:1-1000", "chr1\t0\t100", "chr1"] {
            assert!(!is_ignored_line(line), "should be parsed: {line:?}");
        }
    }
}