use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use anyhow::{Context as _, bail};
use compact_genome::implementation::alphabets::dna_alphabet_or_n::DnaAlphabetOrN;
use generic_a_star::cost::AStarCost as _;
use lib_ts_chainalign::{
alignment::{coordinates::PrimaryAlignmentCoordinates, sequences::AlignmentSequences},
anchors::Anchors,
chain_align::{self, performance_parameters::AlignmentPerformanceParameters},
chaining_cost_function::ChainingCostFunction,
chaining_lower_bounds::ChainingLowerBounds,
config::{ChainingLowerBoundConfig, InexactLowerBoundKind},
costs::AlignmentCosts,
dna_rc_fn,
};
use lib_tsalign::{
config::TemplateSwitchConfig,
costs::{U64Cost, cost_function::CostFunction},
};
use tokio::sync::{OnceCell, Semaphore};
use tracing::{debug, info, warn};
use xxhash_rust::xxh3::xxh3_64;
use crate::common::SequencePair;
use crate::common::aligner::{
AlignerSelector, AlignmentOrchestrator, AlignmentQuery,
result::{self, AlignmentFailure, TwitcherAlignmentResult},
};
use crate::worker::{WorkerQuery, WorkerResult, WorkerTask};
pub fn costs_from_config(
config: &TemplateSwitchConfig<DnaAlphabetOrN, U64Cost>,
no_ts: bool,
) -> anyhow::Result<AlignmentCosts<U64Cost>> {
let mut config = config.clone();
config.length_costs = length_as_hard_range(&config.length_costs)?;
let mut costs =
AlignmentCosts::try_from(config).context("The cost file cannot be used with --chain")?;
if no_ts {
costs.ts_base_cost = U64Cost::from_primitive(u64::MAX).into();
}
Ok(costs)
}
pub fn length_as_hard_range(
length_costs: &CostFunction<usize, U64Cost>,
) -> anyhow::Result<CostFunction<usize, U64Cost>> {
let zero = U64Cost::from_primitive(0);
let infinite = U64Cost::from_primitive(u64::MAX);
let mut points: Vec<(usize, U64Cost)> = Vec::new();
for (length, cost) in Vec::from(length_costs.clone()) {
let cost = if cost == zero { zero } else { infinite };
if points.last().is_none_or(|(_, last)| *last != cost) {
points.push((length, cost));
}
}
let zero_ranges = points.iter().filter(|(_, cost)| *cost == zero).count();
if zero_ranges != 1 {
bail!(
"--chain needs a `Length` table with exactly one range of zero-cost lengths, which becomes the range of allowed template switch lengths, but the cost file has {zero_ranges}"
);
}
Ok(CostFunction::try_from(points)?)
}
pub fn table_size(
reference_len: usize,
query_len: usize,
k: Option<u32>,
max_n: Option<usize>,
) -> (u32, usize) {
let max_n = max_n.unwrap_or_else(|| reference_len.max(query_len).next_power_of_two());
let k = k.unwrap_or_else(|| {
(usize::BITS
- (reference_len + query_len)
.saturating_sub(1)
.leading_zeros())
.saturating_sub(3)
.max(2)
});
(k, max_n)
}
pub fn align(
costs: &AlignmentCosts<U64Cost>,
k: Option<u32>,
max_n: Option<usize>,
query: AlignmentQuery,
table: &Path,
) -> TwitcherAlignmentResult {
let AlignmentQuery { sequences, ranges } = query;
let (reference, query) = (sequences.reference, sequences.query);
if reference.is_empty() || query.is_empty() {
return Err(AlignmentFailure::soft_fail(
&"chainalign cannot align an empty sequence",
));
}
if let Some(&base) = reference
.iter()
.chain(query.iter())
.find(|base| !matches!(base, b'A' | b'C' | b'G' | b'T'))
{
return Err(AlignmentFailure::soft_fail(&format!(
"chainalign supports only A, C, G, T; found {:?}",
char::from(base)
)));
}
let (k, max_n) = table_size(reference.len(), query.len(), k, max_n);
if reference.len().max(query.len()) > max_n {
return Err(AlignmentFailure::soft_fail(&format!(
"chainalign tables support sequences of up to {max_n} bases (--chain-max-n), but they have {} and {}",
reference.len(),
query.len()
)));
}
let bounds = read_table(table, costs, k).map_err(|error| {
AlignmentFailure::error(&format!(
"cannot read the --chain table {}: {error:#}",
table.display()
))
})?;
let sequences = AlignmentSequences::new_named(
reference.to_vec(),
query.to_vec(),
"reference".to_owned(),
"query".to_owned(),
PrimaryAlignmentCoordinates::new(ranges.reference_offset(), ranges.query_offset()),
PrimaryAlignmentCoordinates::new(ranges.reference_limit(), ranges.query_limit()),
);
let performance_parameters = AlignmentPerformanceParameters::default();
let anchors = Anchors::new_exact(&sequences, k, &dna_rc_fn);
let mut cost_function = ChainingCostFunction::new_from_lower_bounds(
&bounds,
&anchors,
&sequences,
performance_parameters.max_exact_cost_function_cost,
&dna_rc_fn,
);
result::from_tsalign(chain_align::align(
&sequences,
&performance_parameters,
bounds.alignment_costs(),
&dna_rc_fn,
bounds.config(),
&anchors,
&mut cost_function,
))
}
fn lower_bound_config(k: u32) -> ChainingLowerBoundConfig {
ChainingLowerBoundConfig {
anchor_k: k,
max_anchor_mutations: 0,
inexact_lower_bound: InexactLowerBoundKind::MaxMatchRun,
}
}
pub fn build_table(
path: &Path,
costs: &AlignmentCosts<U64Cost>,
k: u32,
max_n: usize,
) -> anyhow::Result<()> {
let bounds = ChainingLowerBounds::new(max_n, lower_bound_config(k), costs.clone());
let mut data = Vec::new();
bounds.write(&mut data)?;
let checksum = xxh3_64(&data);
data.extend_from_slice(&checksum.to_le_bytes());
fs::write(path, &data).with_context(|| format!("cannot write {}", path.display()))
}
fn read_table(
path: &Path,
costs: &AlignmentCosts<U64Cost>,
k: u32,
) -> anyhow::Result<ChainingLowerBounds<U64Cost>> {
let mut data = fs::read(path)?;
let checksum = data.split_off(data.len().checked_sub(8).context("truncated file")?);
if checksum != xxh3_64(&data).to_le_bytes() {
bail!("checksum mismatch");
}
let bounds = ChainingLowerBounds::read(&data[..])?;
let config = bounds.config();
if bounds.alignment_costs() != costs || config.anchor_k != k || config.max_anchor_mutations != 0
{
bail!("the tables were computed for other parameters");
}
Ok(bounds)
}
pub struct ChainTables {
dir: tempfile::TempDir,
costs: AlignmentCosts<U64Cost>,
k: Option<u32>,
max_n: Option<usize>,
parallelism: Arc<Semaphore>,
permits: u32,
memory: usize,
tables: Mutex<HashMap<(u32, usize), ChainTableCell>>,
}
pub type ChainTable = Result<PathBuf, AlignmentFailure>;
type ChainTableCell = Arc<OnceCell<ChainTable>>;
impl ChainTables {
pub fn for_aligner(
aligner: &AlignerSelector,
parallelism: &Arc<Semaphore>,
memory_per_thread: usize,
) -> anyhow::Result<Option<Self>> {
let AlignerSelector::Chain { costs, k, max_n } = aligner else {
return Ok(None);
};
let threads = parallelism.available_permits();
let dir = tempfile::Builder::new()
.prefix("twitcher-chain-")
.tempdir()
.context("cannot create a directory for the --chain tables")?;
debug!("Caching the --chain tables in {}", dir.path().display());
Ok(Some(Self {
dir,
costs: costs.clone(),
k: *k,
max_n: *max_n,
parallelism: parallelism.clone(),
permits: u32::try_from(threads).context("too many threads")?,
memory: memory_per_thread * threads,
tables: Mutex::default(),
}))
}
pub async fn get(&self, sequences: &SequencePair) -> ChainTable {
let (k, max_n) = table_size(
sequences.reference.len(),
sequences.query.len(),
self.k,
self.max_n,
);
let cell = self
.tables
.lock()
.unwrap()
.entry((k, max_n))
.or_default()
.clone();
cell.get_or_init(|| self.build(k, max_n)).await.clone()
}
async fn build(&self, k: u32, max_n: usize) -> ChainTable {
let _permits = self
.parallelism
.acquire_many(self.permits)
.await
.map_err(|error| AlignmentFailure::error(&error))?;
let path = self.dir.path().join(format!("{k}-{max_n}.tsc"));
let wq = WorkerQuery {
log_level: *crate::THIS_LOG_LEVEL.get_or_init(Default::default),
memory: self.memory,
task: WorkerTask::ChainTable {
costs: (&self.costs).into(),
k,
max_n,
path: path.clone(),
},
};
let start = Instant::now();
let WorkerResult::<()> { result, memory } =
AlignmentOrchestrator::run_worker(&wq, None).await;
match result {
Ok(()) => {
debug!(
"Built the --chain table for k = {k} and up to {max_n} bases in {:.1?}, peak memory {memory:?}",
start.elapsed()
);
Ok(path)
}
Err(failure) => {
warn!(
"Cannot build the --chain table for k = {k} and up to {max_n} bases, so the alignments that need it fail: {failure}"
);
Err(AlignmentFailure::soft_fail(&format!(
"the --chain table for k = {k} and up to {max_n} bases could not be built"
)))
}
}
}
}
pub fn log_retry_hint(use_chain: bool, failed_alignments_output: Option<&str>) {
let failed = crate::common::stats::get_stat("alignments.results.failed.oom")
+ crate::common::stats::get_stat("alignments.results.failed.timeout");
if use_chain || failed == 0 {
return;
}
let retry = failed_alignments_output.map_or_else(
|| {
"record them with --output-failed-alignments <FILE> and rerun with -R <FILE> --chain"
.to_owned()
},
|file| format!("rerun with -R {file} --chain"),
);
info!(
"{failed} alignments ran out of memory or time; to retry them with the chaining aligner, {retry}"
);
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use lib_tsalign::a_star_aligner::alignment_geometry::AlignmentRange;
use super::*;
use crate::common::aligner::result::SoftFailureReason;
const DEFAULT_TSA: &str = include_str!("../../../default_costs.tsa");
fn config(tsa: &str) -> TemplateSwitchConfig<DnaAlphabetOrN, U64Cost> {
TemplateSwitchConfig::read_plain(tsa.as_bytes()).unwrap()
}
fn default_costs() -> AlignmentCosts<U64Cost> {
costs_from_config(&config(DEFAULT_TSA), false).unwrap()
}
#[test]
fn default_costs_convert_with_the_zero_length_range() {
assert_eq!(default_costs().ts_limits.length_23, 8..401);
}
#[test]
fn length_table_needs_exactly_one_zero_range() {
let default_length = "Length\n 0 5 6 7 8 401\n inf 15 10 5 0 inf";
for length in [
"Length\n 0 5\n inf 15",
"Length\n 0 5 10 20\n inf 0 3 0",
] {
assert!(DEFAULT_TSA.contains(default_length));
let tsa = DEFAULT_TSA.replace(default_length, length);
let error = costs_from_config(&config(&tsa), false)
.unwrap_err()
.to_string();
assert!(error.contains("`Length` table"), "{error}");
}
}
#[test]
fn no_ts_disables_every_template_switch_kind() {
let costs = costs_from_config(&config(DEFAULT_TSA), true).unwrap();
assert_eq!(costs.ts_base_cost, U64Cost::from_primitive(u64::MAX).into());
}
#[test]
fn non_acgt_sequence_is_a_soft_failure() {
let query = AlignmentQuery {
sequences: SequencePair {
reference: Arc::from(&b"ACGTACGTAC"[..]),
query: Arc::from(&b"ACGTNCGTAC"[..]),
},
ranges: AlignmentRange::new_complete(10, 10),
};
let Err(AlignmentFailure::SoftFailure {
reason: SoftFailureReason::Other(reason),
}) = align(&default_costs(), None, None, query, Path::new("unused.tsc"))
else {
panic!("expected a soft failure");
};
assert!(reason.contains("found 'N'"), "{reason}");
}
#[test]
fn missing_table_is_a_hard_error() {
let query = AlignmentQuery {
sequences: SequencePair {
reference: Arc::from(&b"ACGTACGTAC"[..]),
query: Arc::from(&b"ACGTACGTAC"[..]),
},
ranges: AlignmentRange::new_complete(10, 10),
};
let dir = tempfile::tempdir().unwrap();
let result = align(
&default_costs(),
None,
None,
query,
&dir.path().join("gone.tsc"),
);
assert!(
matches!(result, Err(AlignmentFailure::Error { .. })),
"{result:?}"
);
}
#[test]
fn sequence_longer_than_max_n_is_a_soft_failure() {
let query = AlignmentQuery {
sequences: SequencePair {
reference: Arc::from(&b"ACGTACGTAC"[..]),
query: Arc::from(&b"ACGTACGTAC"[..]),
},
ranges: AlignmentRange::new_complete(10, 10),
};
let Err(AlignmentFailure::SoftFailure {
reason: SoftFailureReason::Other(reason),
}) = align(
&default_costs(),
None,
Some(8),
query,
Path::new("unused.tsc"),
)
else {
panic!("expected a soft failure");
};
assert!(reason.contains("--chain-max-n"), "{reason}");
}
#[test]
fn table_size_overrides() {
assert_eq!(table_size(600, 500, None, None), (8, 1024));
assert_eq!(table_size(600, 500, Some(12), None), (12, 1024));
assert_eq!(table_size(600, 500, None, Some(4096)), (8, 4096));
}
#[test]
fn table_round_trip() {
let dir = tempfile::tempdir().unwrap();
let costs = default_costs();
let (k, max_n) = (4, 64);
let path = dir.path().join("table.tsc");
build_table(&path, &costs, k, max_n).unwrap();
let read = read_table(&path, &costs, k).unwrap();
assert_eq!(read.alignment_costs(), &costs);
assert_eq!(read.config().anchor_k, k);
assert!(read_table(&path, &costs, k + 1).is_err());
fs::write(
&path,
b"not a table file, but long enough to be parsed as one",
)
.unwrap();
assert!(read_table(&path, &costs, k).is_err());
}
}