use std::{
iter::Peekable,
ops::{Deref, DerefMut, Range},
};
use anyhow::{Context as _, bail, ensure};
use lib_tsalign::a_star_aligner::{
alignment_geometry::{AlignmentCoordinates, AlignmentRange},
alignment_result::alignment::Alignment,
template_switch_distance::{
AlignmentType, TSMUncertaintyRange, TemplateSwitchAncestor, TemplateSwitchDescendant,
TemplateSwitchDirection,
},
};
use crate::common::aligner::result::TwitcherAlignmentWithStatistics;
#[derive(Clone, Debug)]
pub struct ForwardAlignment(pub Alignment<AlignmentType>);
impl Deref for ForwardAlignment {
type Target = Alignment<AlignmentType>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ForwardAlignment {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<Alignment<AlignmentType>> for ForwardAlignment {
fn from(value: Alignment<AlignmentType>) -> Self {
Self(value)
}
}
impl ForwardAlignment {
pub fn insert_ts_alignment(
&self,
ts_alignment: &TwitcherAlignmentWithStatistics,
) -> anyhow::Result<Alignment<AlignmentType>> {
let mut forward_flat_iter = self.0.iter_flat_cloned().peekable();
let mut result = Alignment::new();
let (reference_gap, query_gap) = consume_within_offsets(
&mut forward_flat_iter,
ts_alignment.stats.reference_offset(),
ts_alignment.stats.query_offset(),
|ty| result.push(ty),
)?;
push_gaps(&mut result, reference_gap, query_gap);
let mut ts = None;
let mut rlen = isize::try_from(reference_gap)?;
let mut qlen = isize::try_from(query_gap)?;
for (n, ty) in ts_alignment.alignment.alignment.iter_compact_cloned() {
rlen += consumed_reference(n, &ty, ts)?;
qlen += consumed_query(n, &ty, ts)?;
match &ty {
AlignmentType::TemplateSwitchEntrance { descendant, .. } => {
ts = Some(*descendant);
}
AlignmentType::TemplateSwitchExit { .. } => {
ts.take();
}
_ => {}
}
result.push_n(n, ty);
}
while rlen > 0 || qlen > 0 {
let Some(next) = forward_flat_iter.next() else {
bail!("Incomplete forward alignment");
};
rlen -= consumed_reference(1, &next, None)?;
qlen -= consumed_query(1, &next, None)?;
}
push_gaps(
&mut result,
usize::try_from((-rlen).max(0))?,
usize::try_from((-qlen).max(0))?,
);
for ty in forward_flat_iter {
result.push(ty);
}
Ok(result)
}
pub fn crop_to_ts_region(
&self,
ts_alignment: &TwitcherAlignmentWithStatistics,
) -> anyhow::Result<Alignment<AlignmentType>> {
let mut forward_flat_iter = self.0.iter_flat_cloned().peekable();
let mut result = Alignment::new();
let (reference_overshoot, query_overshoot) = consume_beyond_offsets(
&mut forward_flat_iter,
ts_alignment.stats.reference_offset(),
ts_alignment.stats.query_offset(),
)?;
push_gaps(&mut result, reference_overshoot, query_overshoot);
let mut ts = None;
let mut ref_length = -isize::try_from(reference_overshoot)?;
for (n, ty) in ts_alignment.alignment.alignment.iter_compact_cloned() {
ref_length += match &ty {
AlignmentType::TemplateSwitchEntrance { descendant, .. } => {
ts = Some(*descendant);
consumed_reference(n, &ty, None)? }
AlignmentType::TemplateSwitchExit { .. } => {
let ts = ts.take();
consumed_reference(n, &ty, ts)?
}
ty => consumed_reference(n, ty, ts)?,
};
}
while ref_length > 0 {
let Some(next) = forward_flat_iter.next() else {
bail!("Incomplete forward alignment");
};
ref_length -= consumed_reference(1, &next, None)?;
result.push(next);
}
Ok(result)
}
}
fn consume_within_offsets<I: Iterator<Item = AlignmentType>>(
forward_flat_iter: &mut Peekable<I>,
reference_offset: usize,
query_offset: usize,
mut push: impl FnMut(AlignmentType),
) -> anyhow::Result<(usize, usize)> {
let mut reference = 0;
let mut query = 0;
while let Some(next) = forward_flat_iter.peek() {
let delta_reference = usize::try_from(consumed_reference(1, next, None)?)?;
let delta_query = usize::try_from(consumed_query(1, next, None)?)?;
if reference + delta_reference > reference_offset || query + delta_query > query_offset {
break;
}
reference += delta_reference;
query += delta_query;
#[expect(clippy::expect_used)]
let next = forward_flat_iter.next().expect("peeked above");
push(next);
}
if forward_flat_iter.peek().is_none() && (reference < reference_offset || query < query_offset)
{
bail!("Incomplete forward alignment");
}
Ok((reference_offset - reference, query_offset - query))
}
fn consume_beyond_offsets(
forward_flat_iter: &mut impl Iterator<Item = AlignmentType>,
reference_offset: usize,
query_offset: usize,
) -> anyhow::Result<(usize, usize)> {
let mut reference = 0;
let mut query = 0;
while reference < reference_offset || query < query_offset {
let Some(next) = forward_flat_iter.next() else {
bail!("Incomplete forward alignment");
};
reference += usize::try_from(consumed_reference(1, &next, None)?)?;
query += usize::try_from(consumed_query(1, &next, None)?)?;
}
Ok((reference - reference_offset, query - query_offset))
}
fn push_gaps(alignment: &mut Alignment<AlignmentType>, reference_gap: usize, query_gap: usize) {
if reference_gap > 0 {
alignment.push_n(reference_gap, AlignmentType::PrimaryDeletion);
}
if query_gap > 0 {
alignment.push_n(query_gap, AlignmentType::PrimaryInsertion);
}
}
pub fn cut_range_extension(
alignment: &Alignment<AlignmentType>,
offsets: AlignmentCoordinates,
range: &AlignmentRange,
) -> anyhow::Result<Option<Alignment<AlignmentType>>> {
let leading_reference = range
.reference_offset()
.checked_sub(offsets.reference())
.context("alignment starts after the reference range offset")?;
let leading_query = range
.query_offset()
.checked_sub(offsets.query())
.context("alignment starts after the query range offset")?;
ensure!(
leading_reference == leading_query,
"the range extension added {leading_reference} reference but {leading_query} query columns"
);
let (reference_limit, query_limit) =
alignment_limits(alignment, offsets.reference(), offsets.query())?;
let trailing_reference = reference_limit
.checked_sub(range.reference_limit())
.context("alignment ends before the reference range limit")?;
let trailing_query = query_limit
.checked_sub(range.query_limit())
.context("alignment ends before the query range limit")?;
ensure!(
trailing_reference == trailing_query,
"the range extension added {trailing_reference} reference but {trailing_query} query columns at the end"
);
if leading_reference == 0 && trailing_reference == 0 {
return Ok(None);
}
for ty in alignment.iter_flat().take(leading_reference) {
ensure!(
matches!(ty, AlignmentType::PrimaryMatch),
"the range extension prepended {ty:?}, but only PrimaryMatch is expected"
);
}
for ty in alignment.iter_flat().rev().take(trailing_reference) {
ensure!(
matches!(ty, AlignmentType::PrimaryMatch),
"the range extension appended {ty:?}, but only PrimaryMatch is expected"
);
}
let aln_iter = alignment.iter_flat_cloned();
let cropped_len = aln_iter
.len()
.checked_sub(leading_reference + trailing_reference)
.context("the range extension is longer than the alignment")?;
let cropped =
aln_iter
.skip(leading_reference)
.take(cropped_len)
.fold(Alignment::new(), |mut a, ty| {
a.push(ty);
a
});
Ok(Some(cropped))
}
pub fn alignment_limits(
alignment: &Alignment<AlignmentType>,
r_offset: usize,
q_offset: usize,
) -> anyhow::Result<(usize, usize)> {
let mut r = isize::try_from(r_offset)?;
let mut q = isize::try_from(q_offset)?;
let mut ts = None;
for (n, ty) in alignment.iter_compact_cloned() {
let (dr, dq) = consumes(n, &ty, ts)?;
r += dr;
q += dq;
match &ty {
AlignmentType::TemplateSwitchEntrance { descendant, .. } => ts = Some(*descendant),
AlignmentType::TemplateSwitchExit { .. } => {
ts.take();
}
_ => {}
}
}
Ok((usize::try_from(r)?, usize::try_from(q)?))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateSpan {
pub ancestor: TemplateSwitchAncestor,
pub range: Range<usize>,
}
impl TemplateSpan {
pub fn touches_query(&self, spans: &[Range<usize>]) -> bool {
self.ancestor == TemplateSwitchAncestor::Query
&& spans
.iter()
.any(|s| s.start <= self.range.end && self.range.start <= s.end)
}
}
pub fn template_spans(
ops: impl IntoIterator<Item = (usize, AlignmentType)>,
reference_offset: usize,
query_offset: usize,
) -> anyhow::Result<Vec<TemplateSpan>> {
struct Open {
descendant: TemplateSwitchDescendant,
ancestor: TemplateSwitchAncestor,
step: isize,
start: isize,
at: isize,
}
let mut r = isize::try_from(reference_offset)?;
let mut q = isize::try_from(query_offset)?;
let mut open: Option<Open> = None;
let mut spans = Vec::new();
for (n, ty) in ops {
let (dr, dq) = consumes(n, &ty, open.as_ref().map(|o| o.descendant))?;
match (&ty, &mut open) {
(
AlignmentType::TemplateSwitchEntrance {
descendant,
ancestor,
direction,
first_offset,
..
},
None,
) => {
let start = match ancestor {
TemplateSwitchAncestor::Reference => r,
TemplateSwitchAncestor::Query => q,
} + first_offset;
open = Some(Open {
descendant: *descendant,
ancestor: *ancestor,
step: match direction {
TemplateSwitchDirection::Forward => 1,
TemplateSwitchDirection::Reverse => -1,
},
start,
at: start,
});
}
(
AlignmentType::SecondaryMatch
| AlignmentType::SecondarySubstitution
| AlignmentType::SecondaryDeletion,
Some(o),
) => o.at += o.step * isize::try_from(n)?,
(AlignmentType::TemplateSwitchExit { .. }, Some(o)) => {
let (start, end) = if o.step > 0 {
(o.start, o.at)
} else {
(o.at, o.start)
};
spans.push(TemplateSpan {
ancestor: o.ancestor,
range: usize::try_from(start.max(0))?..usize::try_from(end.max(0))?,
});
open = None;
}
_ => {}
}
r += dr;
q += dq;
}
Ok(spans)
}
pub fn query_offset_at(
alignment: &Alignment<AlignmentType>,
reference_offset: usize,
after_insertions: bool,
) -> anyhow::Result<usize> {
let (mut r, mut q) = (0usize, 0usize);
for (n, ty) in alignment.iter_compact_cloned() {
let (dr, dq) = consumes(n, &ty, None)?;
let (dr, dq) = (usize::try_from(dr)?, usize::try_from(dq)?);
if dr == 0 {
if r < reference_offset || (r == reference_offset && after_insertions) {
q += dq;
continue;
}
break;
}
if r + dr <= reference_offset {
r += dr;
q += dq;
continue;
}
return Ok(q + (reference_offset - r).min(dq));
}
Ok(q)
}
pub fn consumed_reference(
n: usize,
ty: &AlignmentType,
ts: Option<TemplateSwitchDescendant>,
) -> anyhow::Result<isize> {
Ok(consumes(n, ty, ts)?.0)
}
pub fn consumed_query(
n: usize,
ty: &AlignmentType,
ts: Option<TemplateSwitchDescendant>,
) -> anyhow::Result<isize> {
Ok(consumes(n, ty, ts)?.1)
}
fn consumes(
n: usize,
ty: &AlignmentType,
ts: Option<TemplateSwitchDescendant>,
) -> anyhow::Result<(isize, isize)> {
let n = isize::try_from(n)?;
let (r, q) = if let Some(descendant) = ts {
let (mut r, mut q) = match ty {
AlignmentType::PrimaryInsertion
| AlignmentType::PrimaryDeletion
| AlignmentType::PrimarySubstitution
| AlignmentType::PrimaryMatch
| AlignmentType::PrimaryFlankInsertion
| AlignmentType::PrimaryFlankDeletion
| AlignmentType::PrimaryFlankSubstitution
| AlignmentType::PrimaryFlankMatch
| AlignmentType::Root
| AlignmentType::PrimaryReentry { .. }
| AlignmentType::PrimaryShortcut { .. } => {
bail!("Primary alignments cannot happen inside a template switch")
}
AlignmentType::TemplateSwitchEntrance { .. } => {
bail!("A new template switch cannot start inside a template switch")
}
AlignmentType::SecondaryInsertion
| AlignmentType::SecondarySubstitution
| AlignmentType::SecondaryMatch => (n, 0),
AlignmentType::SecondaryDeletion | AlignmentType::SecondaryRoot => (0, 0),
AlignmentType::TemplateSwitchExit {
anti_descendant_gap,
} => (0, *anti_descendant_gap),
AlignmentType::AlternativeStart { .. } => {
bail!("Alternative start not yet supported by twitcher")
}
};
if descendant != TemplateSwitchDescendant::Reference {
std::mem::swap(&mut r, &mut q);
}
(r, q)
} else {
match ty {
AlignmentType::PrimaryInsertion | AlignmentType::PrimaryFlankInsertion => (0, n),
AlignmentType::PrimaryDeletion | AlignmentType::PrimaryFlankDeletion => (n, 0),
AlignmentType::PrimarySubstitution
| AlignmentType::PrimaryFlankSubstitution
| AlignmentType::PrimaryMatch
| AlignmentType::PrimaryFlankMatch => (n, n),
AlignmentType::TemplateSwitchEntrance { .. }
| AlignmentType::Root
| AlignmentType::PrimaryReentry { .. } => (0, 0),
AlignmentType::PrimaryShortcut {
delta_reference,
delta_query,
} => (*delta_reference, *delta_query),
AlignmentType::SecondaryInsertion
| AlignmentType::SecondaryDeletion
| AlignmentType::SecondarySubstitution
| AlignmentType::SecondaryMatch
| AlignmentType::SecondaryRoot
| AlignmentType::TemplateSwitchExit { .. } => {
bail!("Secondary alignments require a preceding template switch entrance")
}
AlignmentType::AlternativeStart { .. } => {
bail!("Alternative start not yet supported by twitcher")
}
}
};
Ok((r, q))
}
#[allow(clippy::too_many_lines)]
pub fn cigar_to_alignment<S: AsRef<str>>(cigar: &S) -> anyhow::Result<Alignment<AlignmentType>> {
let s = cigar.as_ref();
let mut alignment = Alignment::new();
let mut chars = s.char_indices().peekable();
let mut inside_ts = false;
while let Some((i, c)) = chars.peek().copied() {
match c {
'0'..='9' => {
let start = i;
while chars.peek().is_some_and(|(_, c)| c.is_ascii_digit()) {
chars.next();
}
let end = chars.peek().map_or(s.len(), |(i, _)| *i);
let amount: usize = s
.get(start..end)
.context("non-utf8 cigar??")?
.parse()
.with_context(|| format!("Invalid repeat count at offset {start}"))?;
let (_, type_char) = chars.next().with_context(|| {
format!("Expected alignment type char after count at offset {end}")
})?;
let atype = parse_repeatable_char(type_char, inside_ts).with_context(|| {
format!("Unknown alignment type char '{type_char}' at offset {end}")
})?;
alignment.push_n(amount, atype);
}
'I' | 'D' | 'X' | '=' => {
chars.next();
let atype = parse_repeatable_char(c, inside_ts)
.with_context(|| format!("parse_repeatable_char failed to parse {c}"))?;
alignment.push(atype);
}
'[' => {
chars.next();
let (_, next) = chars.next().context("Unexpected end after '['")?;
match next {
'T' => {
if inside_ts {
bail!("Nested TemplateSwitchEntrance is not allowed");
}
expect_char(&mut chars, 'S').context("Expected 'S' in '[TS...'")?;
let (_, p) = chars.next().context("Expected descendant char")?;
let descendant = parse_ts_descendant(p)
.with_context(|| format!("Invalid TemplateSwitchDescendant '{p}'"))?;
let (_, s_char) = chars.next().context("Expected ancestor char")?;
let ancestor = parse_ts_ancestor(s_char).with_context(|| {
format!("Invalid TemplateSwitchAncestor '{s_char}'")
})?;
let (_, d) = chars.next().context("Expected direction char")?;
let direction = parse_ts_direction(d)
.with_context(|| format!("Invalid TemplateSwitchDirection '{d}'"))?;
expect_char(&mut chars, ':').context("Expected ':' after direction")?;
let uncertainty_range = parse_uncertainty_range(&mut chars)
.context("Failed to parse TSMUncertaintyRange")?;
expect_char(&mut chars, ':')
.context("Expected ':' after TSMUncertaintyRange")?;
let first_offset = parse_isize(&mut chars, &[':', ']'])
.context("Failed to parse first_offset")?;
expect_char(&mut chars, ':')
.context("Expected trailing ':' after first_offset")?;
inside_ts = true;
alignment.push(AlignmentType::TemplateSwitchEntrance {
descendant,
ancestor,
direction,
uncertainty_range,
first_offset,
});
}
'P' => {
expect_char(&mut chars, 'S').context("Expected 'S' in '[PS...'")?;
expect_char(&mut chars, ':').context("Expected ':' in '[PS:...'")?;
expect_char(&mut chars, 'R')
.context("Expected 'R' before delta_reference")?;
let delta_reference = parse_isize(&mut chars, &['Q'])
.context("Failed to parse delta_reference")?;
expect_char(&mut chars, 'Q').context("Expected 'Q' before delta_query")?;
let delta_query = parse_isize(&mut chars, &[']'])
.context("Failed to parse delta_query")?;
expect_char(&mut chars, ']').context("Expected ']' to close '[PS...'")?;
alignment.push(AlignmentType::PrimaryShortcut {
delta_reference,
delta_query,
});
}
other => bail!("Unknown bracket expression starting with '[{other}'"),
}
}
':' => {
if !inside_ts {
bail!(
"TemplateSwitchExit at offset {i} without a preceding TemplateSwitchEntrance"
);
}
chars.next();
let anti_descendant_gap = parse_isize(&mut chars, &[']'])
.context("Failed to parse anti_descendant_gap")?;
expect_char(&mut chars, ']').context("Expected ']' to close TemplateSwitchExit")?;
inside_ts = false;
alignment.push(AlignmentType::TemplateSwitchExit {
anti_descendant_gap,
});
}
other => bail!("Unexpected character '{other}' at offset {i}"),
}
}
if inside_ts {
bail!("Unexpected end of input: unclosed TemplateSwitchEntrance");
}
Ok(alignment)
}
const fn parse_repeatable_char(c: char, inside_ts: bool) -> Option<AlignmentType> {
match (c, inside_ts) {
('I', false) => Some(AlignmentType::PrimaryInsertion),
('D', false) => Some(AlignmentType::PrimaryDeletion),
('X', false) => Some(AlignmentType::PrimarySubstitution),
('=', false) => Some(AlignmentType::PrimaryMatch),
('I', true) => Some(AlignmentType::SecondaryInsertion),
('D', true) => Some(AlignmentType::SecondaryDeletion),
('X', true) => Some(AlignmentType::SecondarySubstitution),
('=', true) => Some(AlignmentType::SecondaryMatch),
_ => None,
}
}
const fn parse_ts_descendant(c: char) -> Option<TemplateSwitchDescendant> {
match c {
'R' => Some(TemplateSwitchDescendant::Reference),
'Q' => Some(TemplateSwitchDescendant::Query),
_ => None,
}
}
const fn parse_ts_ancestor(c: char) -> Option<TemplateSwitchAncestor> {
match c {
'R' => Some(TemplateSwitchAncestor::Reference),
'Q' => Some(TemplateSwitchAncestor::Query),
_ => None,
}
}
const fn parse_ts_direction(c: char) -> Option<TemplateSwitchDirection> {
match c {
'F' => Some(TemplateSwitchDirection::Forward),
'R' => Some(TemplateSwitchDirection::Reverse),
_ => None,
}
}
fn parse_isize(
chars: &mut Peekable<impl Iterator<Item = (usize, char)>>,
terminators: &[char],
) -> anyhow::Result<isize> {
let mut buf = String::new();
if chars.peek().is_some_and(|(_, c)| *c == '-') {
buf.push('-');
chars.next();
}
while let Some((_, c)) = chars.peek() {
if terminators.contains(c) {
break;
}
buf.push(*c);
chars.next();
}
buf.parse::<isize>()
.with_context(|| format!("Invalid integer '{buf}'"))
}
fn expect_char(
chars: &mut Peekable<impl Iterator<Item = (usize, char)>>,
expected: char,
) -> anyhow::Result<()> {
match chars.next() {
Some((_, c)) if c == expected => Ok(()),
Some((i, c)) => bail!("Expected '{expected}' at offset {i}, got '{c}'"),
None => bail!("Expected '{expected}' but got end of input"),
}
}
fn parse_uncertainty_range(
chars: &mut Peekable<impl Iterator<Item = (usize, char)> + Clone>,
) -> anyhow::Result<Option<TSMUncertaintyRange>> {
expect_char(chars, '[')?;
let is_invalid = {
#[expect(clippy::unused_peekable)]
let mut tmp = chars.clone();
tmp.next().is_some_and(|(_, c)| c == '-') && tmp.next().is_some_and(|(_, c)| c == ']')
};
if is_invalid {
chars.next(); expect_char(chars, ']')?;
expect_char(chars, ':')?;
expect_char(chars, '[')?;
expect_char(chars, '-')?;
expect_char(chars, ']')?;
return Ok(None);
}
let neg_start_left_shift = parse_isize(chars, &[',']).context("neg_start_left_shift")?;
expect_char(chars, ',')?;
let start_right_shift = parse_isize(chars, &[']']).context("start_right_shift")?;
expect_char(chars, ']')?;
expect_char(chars, ':')?;
expect_char(chars, '[')?;
let neg_end_left_shift = parse_isize(chars, &[',']).context("neg_end_left_shift")?;
expect_char(chars, ',')?;
let end_right_shift = parse_isize(chars, &[']']).context("end_right_shift")?;
expect_char(chars, ']')?;
Ok(Some(TSMUncertaintyRange {
start_left_shift: neg_start_left_shift
.checked_neg()
.context("start_left_shift is isize::MIN")?
.try_into()?,
start_right_shift: start_right_shift.try_into()?,
end_left_shift: neg_end_left_shift
.checked_neg()
.context("start_right_shift is isize::MIN")?
.try_into()?,
end_right_shift: end_right_shift.try_into()?,
}))
}
#[cfg(test)]
mod tests {
use super::*;
fn round_trip(alignment: &Alignment<AlignmentType>) -> Alignment<AlignmentType> {
let cigar = alignment.cigar();
cigar_to_alignment(&cigar).unwrap()
}
fn ur(
start_left_shift: u16,
start_right_shift: u16,
end_left_shift: u16,
end_right_shift: u16,
) -> TSMUncertaintyRange {
TSMUncertaintyRange {
start_left_shift,
start_right_shift,
end_left_shift,
end_right_shift,
}
}
#[test]
fn query_offset_at_follows_indels() {
let mut alignment = Alignment::new();
alignment.push_n(3, AlignmentType::PrimaryMatch);
alignment.push_n(2, AlignmentType::PrimaryInsertion);
alignment.push_n(2, AlignmentType::PrimaryDeletion);
alignment.push_n(3, AlignmentType::PrimaryMatch);
let at = |r, after| query_offset_at(&alignment, r, after).unwrap();
assert_eq!(at(0, false), 0);
assert_eq!(at(2, false), 2);
assert_eq!(at(3, false), 3, "before the insertion");
assert_eq!(at(3, true), 5, "after the insertion");
assert_eq!(at(4, true), 5, "inside the deletion");
assert_eq!(at(5, false), 5);
assert_eq!(at(8, false), 8, "the end");
}
#[test]
#[expect(clippy::single_range_in_vec_init, reason = "lists of one span")]
fn template_spans_follow_the_ancestor() {
let entrance = |ancestor, direction, first_offset| AlignmentType::TemplateSwitchEntrance {
first_offset,
uncertainty_range: None,
descendant: TemplateSwitchDescendant::Reference,
ancestor,
direction,
};
let ops = [
(5, AlignmentType::PrimaryMatch),
(
1,
entrance(
TemplateSwitchAncestor::Query,
TemplateSwitchDirection::Reverse,
10,
),
),
(3, AlignmentType::SecondaryMatch),
(1, AlignmentType::SecondaryInsertion),
(1, AlignmentType::SecondaryDeletion),
(
1,
AlignmentType::TemplateSwitchExit {
anti_descendant_gap: -6,
},
),
(2, AlignmentType::PrimaryMatch),
(
1,
entrance(
TemplateSwitchAncestor::Reference,
TemplateSwitchDirection::Forward,
-3,
),
),
(2, AlignmentType::SecondaryMatch),
(
1,
AlignmentType::TemplateSwitchExit {
anti_descendant_gap: 0,
},
),
];
let spans = template_spans(ops, 100, 200).unwrap();
assert_eq!(spans[0].ancestor, TemplateSwitchAncestor::Query);
assert_eq!(spans[0].range, 211..215);
assert_eq!(spans[1].ancestor, TemplateSwitchAncestor::Reference);
assert_eq!(spans[1].range, 108..110);
assert!(spans[0].touches_query(&[215..215]));
assert!(spans[0].touches_query(&[200..212]));
assert!(!spans[0].touches_query(&[216..220]));
assert!(
!spans[1].touches_query(&[100..120]),
"a template on the reference"
);
}
#[test]
fn test_empty() {
let alignment = Alignment::new();
assert_eq!(round_trip(&alignment), Alignment::new());
}
#[test]
fn test_single_match() {
let mut a = Alignment::new();
a.push_n(1, AlignmentType::PrimaryMatch);
assert_eq!(round_trip(&a), a);
}
#[test]
fn test_primary_only() {
let mut a = Alignment::new();
a.push_n(5, AlignmentType::PrimaryMatch);
a.push_n(2, AlignmentType::PrimaryInsertion);
a.push_n(3, AlignmentType::PrimaryDeletion);
a.push_n(1, AlignmentType::PrimarySubstitution);
a.push_n(4, AlignmentType::PrimaryMatch);
assert_eq!(round_trip(&a), a);
}
#[test]
fn test_large_counts() {
let mut a = Alignment::new();
a.push_n(10_000, AlignmentType::PrimaryMatch);
a.push_n(9_999, AlignmentType::PrimaryDeletion);
assert_eq!(round_trip(&a), a);
}
fn make_ts_entrance(
descendant: TemplateSwitchDescendant,
ancestor: TemplateSwitchAncestor,
direction: TemplateSwitchDirection,
uncertainty_range: Option<TSMUncertaintyRange>,
first_offset: isize,
) -> AlignmentType {
AlignmentType::TemplateSwitchEntrance {
descendant,
ancestor,
direction,
uncertainty_range,
first_offset,
}
}
fn push_simple_ts(
a: &mut Alignment<AlignmentType>,
descendant: TemplateSwitchDescendant,
ancestor: TemplateSwitchAncestor,
direction: TemplateSwitchDirection,
uncertainty_range: Option<TSMUncertaintyRange>,
first_offset: isize,
anti_descendant_gap: isize,
) {
a.push(make_ts_entrance(
descendant,
ancestor,
direction,
uncertainty_range,
first_offset,
));
a.push_n(5, AlignmentType::SecondaryMatch);
a.push(AlignmentType::TemplateSwitchExit {
anti_descendant_gap,
});
}
#[test]
fn test_ts_empty_body() {
let mut a = Alignment::new();
push_simple_ts(
&mut a,
TemplateSwitchDescendant::Reference,
TemplateSwitchAncestor::Query,
TemplateSwitchDirection::Forward,
Some(TSMUncertaintyRange::new()),
0,
0,
);
assert_eq!(round_trip(&a), a);
}
#[test]
fn test_ts_with_secondary_ops() {
let mut a = Alignment::new();
a.push(make_ts_entrance(
TemplateSwitchDescendant::Query,
TemplateSwitchAncestor::Reference,
TemplateSwitchDirection::Reverse,
Some(ur(1, 2, 3, 4)),
-5,
));
a.push_n(3, AlignmentType::SecondaryMatch);
a.push_n(1, AlignmentType::SecondarySubstitution);
a.push_n(2, AlignmentType::SecondaryInsertion);
a.push_n(1, AlignmentType::SecondaryDeletion);
a.push(AlignmentType::TemplateSwitchExit {
anti_descendant_gap: -3,
});
dbg!(a.cigar());
assert_eq!(round_trip(&a), a);
}
#[test]
fn test_ts_negative_offsets() {
let mut a = Alignment::new();
push_simple_ts(
&mut a,
TemplateSwitchDescendant::Reference,
TemplateSwitchAncestor::Reference,
TemplateSwitchDirection::Reverse,
Some(ur(5, 0, 2, 0)),
-10,
-7,
);
assert_eq!(round_trip(&a), a);
}
#[test]
fn test_ts_invalid_equal_cost_range() {
let mut a = Alignment::new();
push_simple_ts(
&mut a,
TemplateSwitchDescendant::Reference,
TemplateSwitchAncestor::Query,
TemplateSwitchDirection::Forward,
None,
0,
0,
);
assert_eq!(round_trip(&a), a);
}
#[test]
fn test_primary_ts_primary() {
let mut a = Alignment::new();
a.push_n(10, AlignmentType::PrimaryMatch);
a.push_n(2, AlignmentType::PrimaryDeletion);
push_simple_ts(
&mut a,
TemplateSwitchDescendant::Reference,
TemplateSwitchAncestor::Query,
TemplateSwitchDirection::Forward,
Some(ur(1, 1, 1, 1)),
3,
2,
);
a.push_n(5, AlignmentType::PrimaryMatch);
assert_eq!(round_trip(&a), a);
}
#[test]
fn test_multiple_ts() {
let mut a = Alignment::new();
a.push_n(4, AlignmentType::PrimaryMatch);
push_simple_ts(
&mut a,
TemplateSwitchDescendant::Reference,
TemplateSwitchAncestor::Query,
TemplateSwitchDirection::Forward,
Some(ur(0, 1, 1, 0)),
1,
0,
);
a.push_n(3, AlignmentType::PrimarySubstitution);
push_simple_ts(
&mut a,
TemplateSwitchDescendant::Query,
TemplateSwitchAncestor::Reference,
TemplateSwitchDirection::Reverse,
Some(ur(2, 0, 0, 3)),
-1,
4,
);
a.push_n(6, AlignmentType::PrimaryMatch);
assert_eq!(round_trip(&a), a);
}
fn make_stats(
ref_offset: usize,
query_offset: usize,
ref_len: usize,
) -> TwitcherAlignmentWithStatistics {
use std::time::Duration;
use generic_a_star::cost::AStarCost as _;
use lib_tsalign::a_star_aligner::alignment_geometry::{
AlignmentCoordinates, AlignmentRange,
};
use lib_tsalign::costs::U64Cost;
use crate::common::aligner::fpa::FpaAlignmentStatistics;
use crate::common::aligner::result::{AlignmentWithCost, TwitcherAlignmentStatistics};
let mut cluster_aln = Alignment::new();
cluster_aln.push_n(ref_len, AlignmentType::PrimaryMatch);
TwitcherAlignmentWithStatistics {
alignment: AlignmentWithCost::new(cluster_aln, U64Cost::from_primitive(0)),
stats: TwitcherAlignmentStatistics::FPAStats(Box::new(FpaAlignmentStatistics {
duration: Duration::ZERO,
ranges: AlignmentRange::new_offset_limit(
AlignmentCoordinates::new(ref_offset, query_offset),
AlignmentCoordinates::new(ref_offset + ref_len, query_offset + ref_len),
),
})),
}
}
fn fw(cigar: &str) -> ForwardAlignment {
cigar_to_alignment(&cigar.to_owned())
.map(ForwardAlignment)
.unwrap()
}
#[test]
fn test_crop_skips_insertion_at_boundary() {
let cropped = fw("20=1I108=1I70=1I9=1I200=")
.crop_to_ts_region(&make_stats(128, 130, 279))
.unwrap();
assert_eq!(cropped.cigar(), "70=1I9=1I200=");
}
#[test]
fn test_insert_offsets_off_forward_path_query_ahead() {
let inserted = fw("10=2I10=")
.insert_ts_alignment(&make_stats(12, 12, 8))
.unwrap();
assert_eq!(
alignment_limits(&inserted, 0, 0).unwrap(),
(20, 22),
"cigar: {}",
inserted.cigar()
);
assert_eq!(inserted.cigar(), "10=2I2D8=2I");
}
#[test]
fn test_insert_offsets_off_forward_path_reference_ahead() {
let inserted = fw("10=2D10=")
.insert_ts_alignment(&make_stats(12, 12, 8))
.unwrap();
assert_eq!(
alignment_limits(&inserted, 0, 0).unwrap(),
(22, 20),
"cigar: {}",
inserted.cigar()
);
assert_eq!(inserted.cigar(), "10=2D2I8=2D");
}
#[test]
fn test_insert_on_path_offsets_roundtrip() {
let inserted = fw("10=2I10=")
.insert_ts_alignment(&make_stats(10, 12, 10))
.unwrap();
assert_eq!(inserted.cigar(), "10=2I10=");
}
#[test]
fn test_crop_zero_offset_returns_full() {
let cropped = fw("10=2I5=")
.crop_to_ts_region(&make_stats(0, 0, 15))
.unwrap();
assert_eq!(cropped.cigar(), "10=2I5=");
}
fn limits(cigar: &str, r_offset: usize, q_offset: usize) -> (usize, usize) {
alignment_limits(&cigar_to_alignment(&cigar).unwrap(), r_offset, q_offset).unwrap()
}
#[test]
fn test_limits_primary() {
assert_eq!(limits("10=2I3D1X5=", 0, 0), (19, 18));
assert_eq!(limits("10=2I3D1X5=", 100, 200), (119, 218));
}
#[test]
fn test_limits_empty() {
assert_eq!(limits("", 7, 9), (7, 9));
}
#[test]
fn test_limits_ts_reference_descendant() {
let mut a = Alignment::new();
a.push_n(10, AlignmentType::PrimaryMatch);
push_simple_ts(
&mut a,
TemplateSwitchDescendant::Reference,
TemplateSwitchAncestor::Query,
TemplateSwitchDirection::Forward,
Some(TSMUncertaintyRange::new()),
0,
3,
);
a.push_n(4, AlignmentType::PrimaryMatch);
assert_eq!(
alignment_limits(&a, 0, 0).unwrap(),
(10 + 5 + 4, 10 + 3 + 4)
);
}
#[test]
fn test_limits_ts_query_descendant() {
let mut a = Alignment::new();
a.push_n(10, AlignmentType::PrimaryMatch);
push_simple_ts(
&mut a,
TemplateSwitchDescendant::Query,
TemplateSwitchAncestor::Reference,
TemplateSwitchDirection::Reverse,
Some(TSMUncertaintyRange::new()),
0,
-2,
);
a.push_n(4, AlignmentType::PrimaryMatch);
assert_eq!(
alignment_limits(&a, 0, 0).unwrap(),
(10 - 2 + 4, 10 + 5 + 4)
);
}
#[test]
fn test_error_unclosed_ts() {
let cigar = "[TSRQF:[0,0]:[0,0]:0:";
assert!(cigar_to_alignment(&cigar).is_err());
}
#[test]
fn test_error_exit_without_entrance() {
let cigar = ":0]";
assert!(cigar_to_alignment(&cigar).is_err());
}
#[test]
fn test_error_nested_ts() {
let cigar = "[TSRQF:[0,0]:[0,0]:0:[TSRQF:[0,0]:[0,0]:0::0]:0]";
assert!(cigar_to_alignment(&cigar).is_err());
}
#[test]
fn test_error_invalid_char() {
assert!(cigar_to_alignment(&"5Z").is_err());
}
#[test]
fn test_error_truncated_ts_entrance() {
assert!(cigar_to_alignment(&"[TSR").is_err());
}
fn aln(cigar: &str) -> Alignment<AlignmentType> {
cigar_to_alignment(&cigar.to_owned()).unwrap()
}
fn rng(r_offset: usize, q_offset: usize, r_limit: usize, q_limit: usize) -> AlignmentRange {
AlignmentRange::new_offset_limit(
AlignmentCoordinates::new(r_offset, q_offset),
AlignmentCoordinates::new(r_limit, q_limit),
)
}
#[test]
fn test_cut_range_extension_nothing_to_cut() {
let cut = cut_range_extension(
&aln("5=1X5="),
AlignmentCoordinates::new(10, 10),
&rng(10, 10, 21, 21),
)
.unwrap();
assert!(cut.is_none());
}
#[test]
fn test_cut_range_extension_both_ends() {
let cut = cut_range_extension(
&aln("10=1X10="),
AlignmentCoordinates::new(5, 5),
&rng(10, 10, 21, 21),
)
.unwrap()
.expect("the alignment was extended");
assert_eq!(cut.cigar(), "5=1X5=");
}
#[test]
fn test_cut_range_extension_keeps_template_switch() {
let cut = cut_range_extension(
&aln("8=[TSRQR:[-2,0]:[0,1]:37:8=:8]8="),
AlignmentCoordinates::new(0, 0),
&rng(3, 3, 21, 21),
)
.unwrap()
.expect("the alignment was extended");
assert_eq!(cut.cigar(), "5=[TSRQR:[-2,0]:[0,1]:37:8=:8]5=");
}
#[test]
fn test_cut_range_extension_negative_net_template_switch() {
let cut = cut_range_extension(
&aln("4=[TSQRR:[0,0]:[0,0]:-1:5=:-6][TSRQR:[0,0]:[0,0]:0:5=:2]3="),
AlignmentCoordinates::new(2, 2),
&rng(4, 4, 8, 16),
)
.unwrap()
.expect("the alignment was extended");
assert_eq!(
cut.cigar(),
"2=[TSQRR:[0,0]:[0,0]:-1:5=:-6][TSRQR:[0,0]:[0,0]:0:5=:2]3="
);
}
#[test]
fn test_cut_range_extension_rejects_non_match() {
let error = cut_range_extension(
&aln("2X5=1X"),
AlignmentCoordinates::new(8, 8),
&rng(10, 10, 15, 15),
)
.expect_err("a substitution is not something the extension appends");
assert!(
format!("{error:#}").contains("PrimarySubstitution"),
"the error should name what was found: {error:#}"
);
}
#[test]
fn test_cut_range_extension_rejects_asymmetric_offsets() {
cut_range_extension(
&aln("10=1X10="),
AlignmentCoordinates::new(5, 6),
&rng(10, 10, 21, 21),
)
.expect_err("reference and query extensions differ");
}
#[test]
fn test_cut_range_extension_rejects_alignment_inside_range() {
cut_range_extension(
&aln("5="),
AlignmentCoordinates::new(12, 12),
&rng(10, 10, 21, 21),
)
.expect_err("the alignment starts after the range offset");
}
}