twitcher 0.9.2

Find template switch mutations in genomic data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
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};

/// Converts the cost model into the one of the chaining aligner, failing if that would lose more
/// than the `Length` grading.
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 {
        // The chaining aligner skips every kind of template switch with an infinite base cost.
        costs.ts_base_cost = U64Cost::from_primitive(u64::MAX).into();
    }
    Ok(costs)
}

/// The chaining aligner only knows a range of allowed inner lengths, so every length with a zero
/// cost is allowed and every other one is forbidden.
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)?)
}

/// The k-mer size and the maximum sequence length of the tables for aligning sequences of these
/// lengths: `k` and `max_n` (`--chain-k`, `--chain-max-n`) if given, otherwise inferred from the
/// lengths, with `max_n` the next power of two.
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());
    // Mirrors `infer_tschain_k` of tsalign: about log2 of the number of k-mers, minus a bit.
    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)
}

/// Aligns with the chaining aligner. Sequences it cannot handle are soft failures, so that they
/// are stored in the database and not tried again on every run.
///
/// `table` is the file written by [`build_table`] for this [`table_size`]. The tables are never
/// computed here, so a table that cannot be read is a hard error.
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,
    ))
}

/// Exact anchors of length `k`. `k` must be in `1..=64`, which `--chain-k` and [`table_size`]
/// guarantee, as [`ChainingLowerBounds::new`] panics otherwise.
fn lower_bound_config(k: u32) -> ChainingLowerBoundConfig {
    ChainingLowerBoundConfig {
        anchor_k: k,
        max_anchor_mutations: 0,
        // Only used for inexact anchors.
        inexact_lower_bound: InexactLowerBoundKind::MaxMatchRun,
    }
}

/// Computes the lower bound tables and writes them to `path`. Computing them takes seconds to
/// minutes, much longer than a typical alignment, so the main process has each one built only once
/// per run.
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());
    // No need to write atomically: the main process hands the path out only after a successful build.
    fs::write(path, &data).with_context(|| format!("cannot write {}", path.display()))
}

/// The table files end with a checksum, because tsalign trusts the array sizes it reads, so a
/// damaged file could make it allocate without bound instead of failing.
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)
}

/// The tables of this run. The first alignment that needs a table has a worker build it, the
/// others that need it wait, and then the alignment workers only read it.
pub struct ChainTables {
    /// Private to this run, so the tables are never shared with other runs, cost models or users.
    /// Removed once the last alignment holding it has finished.
    dir: tempfile::TempDir,
    costs: AlignmentCosts<U64Cost>,
    /// `--chain-k` and `--chain-max-n`, see [`table_size`].
    k: Option<u32>,
    max_n: Option<usize>,
    parallelism: Arc<Semaphore>,
    /// All of them, as a build stalls the alignments that need its table anyway.
    permits: u32,
    /// The whole memory budget: building a table needs far more memory than the result.
    memory: usize,
    /// By [`table_size`]. Each table is built at most once, even when that fails.
    tables: Mutex<HashMap<(u32, usize), ChainTableCell>>,
}

/// A built table, or the failure of every alignment that needs it.
pub type ChainTable = Result<PathBuf, AlignmentFailure>;

type ChainTableCell = Arc<OnceCell<ChainTable>>;

impl ChainTables {
    /// `None` unless `aligner` is the chaining aligner. Call it before any alignment takes a permit
    /// from `parallelism`, as a build takes all of them.
    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(),
        }))
    }

    /// The table for aligning these sequences, built first if no alignment needed it before.
    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();
        // No timeout, as the alignment timeout is meant for single alignments.
        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}"
                );
                // Not `OutOfMemory`, whose database retry compares the per-alignment allowance,
                // while the build had the whole budget.
                Err(AlignmentFailure::soft_fail(&format!(
                    "the --chain table for k = {k} and up to {max_n} bases could not be built"
                )))
            }
        }
    }
}

/// At the end of a run, points out that alignments which ran out of memory or time can be retried
/// with `--chain`.
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());
    }
}