rsomics-annotation 0.1.0

Typed GFF3 and GTF validation, selection, conversion, and sequence extraction
Documentation
use std::io::{BufRead, Write};

use rsomics_common::{Result, RsomicsError};

use crate::annotation::{AnnotationLine, AnnotationWriter, Dialect, FeatureRecord, for_each_line};

pub(crate) struct Selection {
    pub(crate) types: Vec<Vec<u8>>,
    pub(crate) attributes: Vec<AttributePredicate>,
    pub(crate) region: Option<Region>,
    pub(crate) contained: bool,
    pub(crate) head: Option<usize>,
}

pub(crate) struct AttributePredicate {
    key: Vec<u8>,
    value: Option<Vec<u8>>,
}

impl AttributePredicate {
    pub(crate) fn parse(value: &str) -> Result<Self> {
        let (key, expected) = value
            .split_once('=')
            .map_or((value, None), |(key, value)| (key, Some(value)));
        if key.is_empty() {
            return Err(RsomicsError::ConfigError(
                "attribute predicate requires a non-empty key".to_owned(),
            ));
        }
        Ok(Self {
            key: key.as_bytes().to_vec(),
            value: expected.map(|value| value.as_bytes().to_vec()),
        })
    }

    fn matches(&self, record: &FeatureRecord) -> bool {
        record
            .attribute_values(&self.key)
            .is_some_and(|values| match &self.value {
                None => true,
                Some(expected) => values.into_iter().any(|value| value == expected),
            })
    }
}

pub(crate) struct Region {
    seqid: Vec<u8>,
    start: u64,
    end: u64,
}

impl Region {
    pub(crate) fn parse(value: &str) -> Result<Self> {
        let (seqid, range) = value.rsplit_once(':').ok_or_else(|| {
            RsomicsError::ConfigError("region must use SEQID:START-END".to_owned())
        })?;
        let (start, end) = range.split_once('-').ok_or_else(|| {
            RsomicsError::ConfigError("region must use SEQID:START-END".to_owned())
        })?;
        let start = parse_position(start, "start")?;
        let end = parse_position(end, "end")?;
        if start > end {
            return Err(RsomicsError::ConfigError(format!(
                "region start {start} exceeds end {end}"
            )));
        }
        if seqid.is_empty() {
            return Err(RsomicsError::ConfigError(
                "region requires a non-empty sequence name".to_owned(),
            ));
        }
        Ok(Self {
            seqid: seqid.as_bytes().to_vec(),
            start,
            end,
        })
    }

    fn matches(&self, record: &FeatureRecord, contained: bool) -> bool {
        if record.seqid() != self.seqid {
            return false;
        }
        if contained {
            self.start <= record.start() && record.end() <= self.end
        } else {
            record.start() <= self.end && self.start <= record.end()
        }
    }
}

pub(crate) fn view<R: BufRead>(
    input: R,
    output: &mut dyn Write,
    dialect: Dialect,
    selection: &Selection,
) -> Result<()> {
    let mut writer = AnnotationWriter::new(dialect, output);
    let mut emitted = 0;

    for_each_line(input, dialect, |_, line| {
        match &line {
            AnnotationLine::Directive(_) | AnnotationLine::Comment(_) => writer.write(&line)?,
            AnnotationLine::Record(record) if selection.matches(record) => {
                if selection.head.is_none_or(|limit| emitted < limit) {
                    writer.write(&line)?;
                    emitted += 1;
                }
            }
            AnnotationLine::Record(_) => {}
        }
        Ok(())
    })
}

impl Selection {
    fn matches(&self, record: &FeatureRecord) -> bool {
        (self.types.is_empty() || self.types.iter().any(|ty| ty == record.ty()))
            && self
                .attributes
                .iter()
                .all(|predicate| predicate.matches(record))
            && self
                .region
                .as_ref()
                .is_none_or(|region| region.matches(record, self.contained))
    }
}

fn parse_position(value: &str, name: &str) -> Result<u64> {
    let position = value.parse::<u64>().map_err(|error| {
        RsomicsError::ConfigError(format!("region {name} is not an integer: {error}"))
    })?;
    if position == 0 {
        return Err(RsomicsError::ConfigError(format!(
            "region {name} must be at least 1"
        )));
    }
    Ok(position)
}

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

    #[test]
    fn inclusive_range_touches_both_edges() {
        let region = Region::parse("chr1:10-20").unwrap();
        for (start, end) in [(1, 10), (20, 30), (5, 9), (21, 40)] {
            let line = format!("chr1\tsrc\tgene\t{start}\t{end}\t.\t+\t.\tID=g\n");
            let mut matched = false;
            crate::annotation::for_each_line(line.as_bytes(), Dialect::Gff3, |_, record| {
                if let AnnotationLine::Record(record) = record {
                    matched = region.matches(&record, false);
                }
                Ok(())
            })
            .unwrap();
            assert_eq!(matched, end >= 10 && start <= 20);
        }
    }

    #[test]
    fn zero_coordinate_is_rejected() {
        assert!(Region::parse("chr1:0-10").is_err());
    }

    #[test]
    fn percent_encoded_attribute_matches_decoded_value() {
        let predicate = AttributePredicate::parse("Name=A;B").unwrap();
        let mut matched = false;
        crate::annotation::for_each_line(
            &b"chr1\tsrc\tgene\t1\t2\t.\t+\t.\tID=g1;Name=A%3BB\n"[..],
            Dialect::Gff3,
            |_, line| {
                if let AnnotationLine::Record(record) = line {
                    matched = predicate.matches(&record);
                }
                Ok(())
            },
        )
        .unwrap();
        assert!(matched);
    }
}