use crate::scoring::ScoringScheme;
use crate::types::{AlignmentResult, CigarOp};
use cyanea_core::{CyaneaError, Result};
pub fn semi_global(
query: &[u8],
target: &[u8],
scoring: &ScoringScheme,
) -> Result<AlignmentResult> {
let m = query.len();
let n = target.len();
if m == 0 || n == 0 {
return Err(CyaneaError::InvalidInput(
"sequences must not be empty".into(),
));
}
let gap_open = scoring.gap_open();
let gap_extend = scoring.gap_extend();
let rows = m + 1;
let cols = n + 1;
let mut h = vec![i32::MIN / 2; rows * cols];
let mut e = vec![i32::MIN / 2; rows * cols];
let mut f = vec![i32::MIN / 2; rows * cols];
let idx = |i: usize, j: usize| -> usize { i * cols + j };
h[idx(0, 0)] = 0;
for j in 1..cols {
h[idx(0, j)] = 0; }
for i in 1..rows {
h[idx(i, 0)] = 0; }
for i in 1..rows {
for j in 1..cols {
e[idx(i, j)] = (h[idx(i, j - 1)] + gap_open).max(e[idx(i, j - 1)] + gap_extend);
f[idx(i, j)] = (h[idx(i - 1, j)] + gap_open).max(f[idx(i - 1, j)] + gap_extend);
let sub = scoring.score_pair(query[i - 1], target[j - 1]);
let diag = h[idx(i - 1, j - 1)] + sub;
h[idx(i, j)] = diag.max(e[idx(i, j)]).max(f[idx(i, j)]);
}
}
let mut best_score = i32::MIN;
let mut best_i = m;
let mut best_j = n;
for j in 0..cols {
if h[idx(m, j)] > best_score {
best_score = h[idx(m, j)];
best_i = m;
best_j = j;
}
}
for i in 0..rows {
if h[idx(i, n)] > best_score {
best_score = h[idx(i, n)];
best_i = i;
best_j = n;
}
}
let mut aligned_query = Vec::new();
let mut aligned_target = Vec::new();
let mut cigar_ops: Vec<CigarOp> = Vec::new();
let mut i = best_i;
let mut j = best_j;
#[derive(Clone, Copy, PartialEq)]
enum State {
H,
E,
F,
}
let mut state = State::H;
while i > 0 || j > 0 {
if i == 0 && j == 0 {
break;
}
if state == State::H && (i == 0 || j == 0) {
break;
}
match state {
State::H => {
if i > 0 && j > 0 {
let sub = scoring.score_pair(query[i - 1], target[j - 1]);
let diag = h[idx(i - 1, j - 1)] + sub;
if h[idx(i, j)] == diag {
aligned_query.push(query[i - 1]);
aligned_target.push(target[j - 1]);
let op = if query[i - 1].to_ascii_uppercase()
== target[j - 1].to_ascii_uppercase()
{
CigarOp::Match(1)
} else {
CigarOp::Mismatch(1)
};
push_cigar(&mut cigar_ops, op);
i -= 1;
j -= 1;
} else if h[idx(i, j)] == e[idx(i, j)] {
state = State::E;
} else {
state = State::F;
}
} else if j > 0 {
state = State::E;
} else {
state = State::F;
}
}
State::E => {
aligned_query.push(b'-');
aligned_target.push(target[j - 1]);
push_cigar(&mut cigar_ops, CigarOp::Insertion(1));
if e[idx(i, j)] == h[idx(i, j - 1)] + gap_open {
state = State::H;
}
j -= 1;
}
State::F => {
aligned_query.push(query[i - 1]);
aligned_target.push(b'-');
push_cigar(&mut cigar_ops, CigarOp::Deletion(1));
if f[idx(i, j)] == h[idx(i - 1, j)] + gap_open {
state = State::H;
}
i -= 1;
}
}
}
aligned_query.reverse();
aligned_target.reverse();
cigar_ops.reverse();
Ok(AlignmentResult {
score: best_score,
aligned_query,
aligned_target,
query_start: i,
query_end: best_i,
target_start: j,
target_end: best_j,
cigar: cigar_ops,
})
}
fn push_cigar(ops: &mut Vec<CigarOp>, op: CigarOp) {
if let Some(last) = ops.last_mut() {
match (last, &op) {
(CigarOp::Match(ref mut n), CigarOp::Match(1)) => {
*n += 1;
return;
}
(CigarOp::Mismatch(ref mut n), CigarOp::Mismatch(1)) => {
*n += 1;
return;
}
(CigarOp::Insertion(ref mut n), CigarOp::Insertion(1)) => {
*n += 1;
return;
}
(CigarOp::Deletion(ref mut n), CigarOp::Deletion(1)) => {
*n += 1;
return;
}
_ => {}
}
}
ops.push(op);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scoring::{ScoringMatrix, SubstitutionMatrix};
fn dna_scheme() -> ScoringScheme {
ScoringScheme::Simple(ScoringMatrix::dna_default())
}
#[test]
fn identical_sequences() {
let result = semi_global(b"ACGT", b"ACGT", &dna_scheme()).unwrap();
assert_eq!(result.score, 8); assert_eq!(result.cigar_string(), "4=");
assert!((result.identity() - 1.0).abs() < f64::EPSILON);
}
#[test]
fn query_contained_in_target() {
let result = semi_global(b"CGT", b"AACGTAA", &dna_scheme()).unwrap();
assert_eq!(result.score, 6); assert_eq!(result.matches(), 3);
}
#[test]
fn target_contained_in_query() {
let result = semi_global(b"AACGTAA", b"CGT", &dna_scheme()).unwrap();
assert_eq!(result.score, 6); assert_eq!(result.matches(), 3);
}
#[test]
fn adapter_trimming() {
let result = semi_global(b"ACGTACGT", b"ACGTACGTTTTT", &dna_scheme()).unwrap();
assert_eq!(result.score, 16); }
#[test]
fn overlap_detection() {
let result = semi_global(b"AAAACGT", b"CGTTTTT", &dna_scheme()).unwrap();
assert_eq!(result.score, 6); }
#[test]
fn empty_sequence_errors() {
assert!(semi_global(b"", b"ACGT", &dna_scheme()).is_err());
assert!(semi_global(b"ACGT", b"", &dna_scheme()).is_err());
}
#[test]
fn protein_semi_global() {
let scheme = ScoringScheme::Substitution(SubstitutionMatrix::blosum62());
let result = semi_global(b"HEAG", b"XXHEAGXX", &scheme).unwrap();
assert!(
result.score > 0,
"expected positive score for embedded peptide"
);
}
#[test]
fn single_base() {
let result = semi_global(b"A", b"A", &dna_scheme()).unwrap();
assert_eq!(result.score, 2);
assert_eq!(result.cigar_string(), "1=");
}
#[test]
fn no_match_region() {
let result = semi_global(b"AAAA", b"TTTT", &dna_scheme()).unwrap();
assert!(result.score <= 0 || result.length() > 0);
}
}