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
use std::io::IsTerminal;
use std::path::{Path, PathBuf};

use anyhow::bail;
use clap_verbosity_flag::Verbosity;
use compact_genome::{
    implementation::{
        alphabets::dna_alphabet_or_n::DnaAlphabetOrN, bit_vec_sequence::BitVectorGenome,
    },
    interface::{
        alphabet::{Alphabet, AlphabetError},
        sequence::{GenomeSequence, OwnedGenomeSequence},
    },
};
use lib_ts_chainalign::costs::AlignmentCosts;
use lib_tsalign::{
    a_star_aligner::{
        alignment_geometry::{AlignmentCoordinates, AlignmentRange},
        alignment_result::AlignmentResult,
        template_switch_distance::{
            AlignmentType,
            context::DynamicStrategies,
            strategies::{
                AlignmentStrategySelection,
                allow_ts_14_out_of_range::{
                    AdditionalExplicitTSMStartsAndEnds, Ts14OutOfRangeStrategy,
                },
                chaining::NoChainingStrategy,
                descendant::{
                    AnyTemplateSwitchDescendantStrategy, OnlyEqualTemplateSwitchDescendantStrategy,
                    TemplateSwitchDescendantStrategy,
                },
                node_ord::AntiDiagonalNodeOrdStrategy,
                primary_match::AllowPrimaryMatchStrategy,
                primary_range::NoPrunePrimaryRangeStrategy,
                secondary_deletion::AllowSecondaryDeletionStrategy,
                shortcut::NoShortcutStrategy,
                template_switch_count::{
                    MaxTemplateSwitchCountStrategy, NoTemplateSwitchCountStrategy,
                    TemplateSwitchCountStrategy,
                },
                template_switch_min_length::{
                    LookaheadTemplateSwitchMinLengthStrategy, NoTemplateSwitchMinLengthStrategy,
                    PreprocessedLookaheadTemplateSwitchMinLengthStrategy,
                    PreprocessedTemplateSwitchMinLengthStrategy, TemplateSwitchMinLengthStrategy,
                },
                template_switch_total_length::MaxTemplateSwitchTotalLengthStrategy,
            },
        },
        template_switch_distance_a_star_align,
    },
    config::TemplateSwitchConfig,
    costs::U64Cost,
};
use rlimit::Resource;
use serde::{Deserialize, Serialize};
use tracing::{error, info_span, instrument, warn};

use crate::{
    VerbositySelector,
    common::{
        SequencePair,
        aligner::{
            AlignerSelector, AlignmentQuery, chain,
            cli::{MLSSelector, URMSelector},
            exec_stats::MemoryUsage,
            result,
            result::{AlignmentFailure, TwitcherAlignmentResult, TwitcherAlignmentWithStatistics},
        },
        alignment::cut_range_extension,
        coords::GenomeRegion,
    },
    setup_tracing,
};

// Cow but without a `ToOwned` bound
pub enum RefOrOwned<'a, T: 'a> {
    Ref(&'a T),
    Owned(T),
}

impl<T> std::ops::Deref for RefOrOwned<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        match self {
            RefOrOwned::Ref(r) => r,
            RefOrOwned::Owned(o) => o,
        }
    }
}

impl<T: Serialize> Serialize for RefOrOwned<'_, T> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            RefOrOwned::Ref(r) => r.serialize(serializer),
            RefOrOwned::Owned(o) => o.serialize(serializer),
        }
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for RefOrOwned<'_, T> {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        T::deserialize(deserializer).map(RefOrOwned::Owned)
    }
}

impl<T> From<T> for RefOrOwned<'_, T> {
    fn from(value: T) -> Self {
        Self::Owned(value)
    }
}

impl<'a, T> From<&'a T> for RefOrOwned<'a, T> {
    fn from(value: &'a T) -> Self {
        Self::Ref(value)
    }
}

#[derive(Serialize, Deserialize)]
pub struct WorkerQuery<'a> {
    pub log_level: VerbositySelector,
    pub memory: usize,
    pub task: WorkerTask<'a>,
}

#[derive(Serialize, Deserialize)]
#[expect(clippy::large_enum_variant, reason = "one per worker process")]
pub enum WorkerTask<'a> {
    Align {
        aligner: RefOrOwned<'a, AlignerSelector>,
        query: AlignmentQuery,
        metadata: WorkerQueryMetadata,
        /// The `--chain` table for this alignment, built beforehand by a [`WorkerTask::ChainTable`].
        /// Not part of [`AlignerSelector`], whose description keys the alignment database and must
        /// stay the same across runs.
        chain_table: Option<PathBuf>,
    },
    /// Build the `--chain` table for k-mer size `k` and sequences of up to `max_n` bases at `path`.
    ChainTable {
        costs: RefOrOwned<'a, AlignmentCosts<U64Cost>>,
        k: u32,
        max_n: usize,
        path: PathBuf,
    },
}

#[derive(Serialize, Deserialize)]
pub struct WorkerQueryMetadata {
    pub cluster_region: GenomeRegion,
}

/// What the worker process writes to stdout: `T` is the alignment, or `()` for a built table.
#[derive(Serialize, Deserialize)]
pub struct WorkerResult<T = TwitcherAlignmentWithStatistics> {
    pub result: Result<T, AlignmentFailure>,
    /// Peak memory of the worker process, measured just before it reports its result.
    pub memory: MemoryUsage,
}

/// Read the query from stdin and write the result to stdout.
/// Errors are reported either to stderr, through non-zero exit or abort.
#[instrument]
pub fn run_fallible() -> anyhow::Result<()> {
    let WorkerQuery {
        log_level,
        memory,
        task,
    } = read_from_stdin()?;

    setup_tracing(log_level)?;

    // limit address space memory usage
    let bytes = memory as u64;
    rlimit::setrlimit(Resource::AS, bytes, bytes)
        .inspect_err(|e| error!("Can't set resource limit: {e}"))?;

    // do not create core files
    rlimit::setrlimit(Resource::CORE, 0, 0)
        .inspect_err(|e| error!("Can't set resource limit: {e}"))?;

    match task {
        WorkerTask::Align {
            aligner,
            query,
            metadata,
            chain_table,
        } => {
            let span = info_span!("Aligning sequences", pos = %metadata.cluster_region).entered();
            let result = align(&aligner, memory, query, chain_table.as_deref())?;
            span.exit();

            let _span = info_span!("Reporting alignment", pos = %metadata.cluster_region).entered();
            write_result(result)
        }
        WorkerTask::ChainTable {
            costs,
            k,
            max_n,
            path,
        } => {
            let _span = info_span!("Building --chain table", k, max_n).entered();
            chain::build_table(&path, &costs, k, max_n)?;
            write_result(Ok(()))
        }
    }
}

fn align(
    aligner: &AlignerSelector,
    memory: usize,
    query: AlignmentQuery,
    chain_table: Option<&Path>,
) -> anyhow::Result<TwitcherAlignmentResult> {
    let ranges = query.ranges.clone();

    Ok(match aligner {
        AlignerSelector::AStar {
            costs,
            min_length_strategy,
            uncertainty_range_mode,
            allow_mixed_descendants,
            no_ts,
        } => {
            let with_ts = align_select_min_length_strategy(AStarQueryData {
                memory,
                query,
                costs,
                min_length_strategy,
                uncertainty_range_mode: *uncertainty_range_mode,
                allow_mixed_descendants: *allow_mixed_descendants,
                no_ts: *no_ts,
            })?;
            cut_extension(result::from_tsalign(with_ts), &ranges)
        }
        AlignerSelector::Fpa(four_point_aligner) => {
            // fpa, and especially the donstream tsalign alignment methods that we use to post-process the alignment expects valid sequences
            verify_sequences(&query.sequences)?;
            four_point_aligner.align(
                query.sequences.reference,
                query.sequences.query,
                query.ranges,
            )
        }
        AlignerSelector::Chain { costs, k, max_n } => match chain_table {
            Some(table) => chain::align(costs, *k, *max_n, query, table),
            None => Err(AlignmentFailure::error(
                "no --chain table was built for this alignment",
            )),
        },
    })
}

fn write_result<T: Serialize>(result: Result<T, AlignmentFailure>) -> anyhow::Result<()> {
    let result = WorkerResult {
        result,
        memory: MemoryUsage::of_current_process(),
    };
    rmp_serde::encode::write(&mut std::io::stdout().lock(), &result)?;
    Ok(())
}

/// Cut the equal-cost range extension the aligner added while measuring the TSM uncertainty
/// ranges, so the reported alignment spans the range it was asked for.
///
/// A cluster whose extension cannot be cut is soft-failed rather than reported: its cluster-local
/// cigars would otherwise silently span the whole context. A soft failure skips one cluster and is
/// logged; a hard failure would end the whole `reads` run.
fn cut_extension(
    result: TwitcherAlignmentResult,
    ranges: &AlignmentRange,
) -> TwitcherAlignmentResult {
    // A failed alignment has nothing to cut.
    let mut with_statistics = result?;

    let offsets = AlignmentCoordinates::new(
        with_statistics.stats.reference_offset(),
        with_statistics.stats.query_offset(),
    );

    match cut_range_extension(&with_statistics.alignment.alignment, offsets, ranges) {
        Ok(None) => {}
        Ok(Some(cut)) => {
            with_statistics.alignment.alignment = cut;
            with_statistics.stats.set_range(ranges);
        }
        Err(error) => {
            warn!(
                cigar = with_statistics.alignment.alignment.cigar(),
                "Cannot cut the range extension: {error:#}"
            );
            return Err(AlignmentFailure::soft_fail(&format!("{error:#}")));
        }
    }

    Ok(with_statistics)
}

fn verify_sequences(seqs: &SequencePair) -> anyhow::Result<()> {
    for (s, bs) in [("reference", &seqs.reference), ("query", &seqs.query)] {
        if let Some(e) = bs
            .iter()
            .find_map(|c| DnaAlphabetOrN::ascii_to_character(*c).err())
        {
            anyhow::bail!("{s} sequence contains an unsupported ASCII character: {e}")
        }
    }
    Ok(())
}

fn read_from_stdin() -> anyhow::Result<WorkerQuery<'static>> {
    let mut stdin = std::io::stdin().lock();
    if stdin.is_terminal() {
        setup_tracing(Verbosity::default())?;
        bail!(
            "The `worker` subcommand is not designed to be called directly but only as a subroutine of twitcher."
        );
    }

    let wq = rmp_serde::from_read(&mut stdin)?;
    Ok(wq)
}

struct AStarQueryData<'a> {
    memory: usize,
    query: AlignmentQuery,
    costs: &'a TemplateSwitchConfig<DnaAlphabetOrN, U64Cost>,
    min_length_strategy: &'a MLSSelector,
    uncertainty_range_mode: URMSelector,
    allow_mixed_descendants: bool,
    no_ts: bool,
}

fn align_select_min_length_strategy(
    data: AStarQueryData,
) -> Result<AlignmentResult<AlignmentType, U64Cost>, AlphabetError> {
    match data.min_length_strategy {
        MLSSelector::None => {
            align_select_descendant_strategy::<NoTemplateSwitchMinLengthStrategy<U64Cost>>(data)
        }
        MLSSelector::Lookahead => align_select_descendant_strategy::<
            LookaheadTemplateSwitchMinLengthStrategy<U64Cost>,
        >(data),
        MLSSelector::PreprocessFilter => align_select_descendant_strategy::<
            PreprocessedTemplateSwitchMinLengthStrategy<true, U64Cost>,
        >(data),
        MLSSelector::PreprocessPrice => align_select_descendant_strategy::<
            PreprocessedTemplateSwitchMinLengthStrategy<false, U64Cost>,
        >(data),
        MLSSelector::PreprocessLookahead => align_select_descendant_strategy::<
            PreprocessedLookaheadTemplateSwitchMinLengthStrategy<U64Cost>,
        >(data),
    }
}

fn align_select_descendant_strategy<ML: TemplateSwitchMinLengthStrategy<U64Cost>>(
    data: AStarQueryData,
) -> Result<AlignmentResult<AlignmentType, U64Cost>, AlphabetError> {
    if data.allow_mixed_descendants {
        align_select_no_ts_strategy::<ML, AnyTemplateSwitchDescendantStrategy>(data)
    } else {
        align_select_no_ts_strategy::<ML, OnlyEqualTemplateSwitchDescendantStrategy>(data)
    }
}

fn align_select_no_ts_strategy<
    ML: TemplateSwitchMinLengthStrategy<U64Cost>,
    DS: TemplateSwitchDescendantStrategy,
>(
    data: AStarQueryData,
) -> Result<AlignmentResult<AlignmentType, U64Cost>, AlphabetError> {
    if data.no_ts {
        align_call::<ML, DS, MaxTemplateSwitchCountStrategy>(data, 0)
    } else {
        align_call::<ML, DS, NoTemplateSwitchCountStrategy>(data, ())
    }
}

fn align_call<
    ML: TemplateSwitchMinLengthStrategy<U64Cost>,
    DS: TemplateSwitchDescendantStrategy,
    TS: TemplateSwitchCountStrategy,
>(
    data: AStarQueryData,
    count_mem: TS::Memory,
) -> Result<AlignmentResult<AlignmentType, U64Cost>, AlphabetError> {
    let reference = seq_to_genome(&data.query.sequences.reference)?;
    let query = seq_to_genome(&data.query.sequences.query)?;
    Ok(template_switch_distance_a_star_align::<
        AlignmentStrategySelection<
            DnaAlphabetOrN,
            U64Cost,
            AntiDiagonalNodeOrdStrategy,
            ML,
            NoChainingStrategy<U64Cost>,
            TS,
            AllowSecondaryDeletionStrategy,
            NoShortcutStrategy<U64Cost>,
            AllowPrimaryMatchStrategy,
            // The alignment range only marks the region of interest; the padded context around
            // it is there so that template switches can jump into it. Pruning the primary
            // alignment to the range would strand the alignment whenever a template switch
            // exits outside of it, forcing artificial extra template switches.
            // TODO probably we want to fix this upstream and then remove this line here.
            NoPrunePrimaryRangeStrategy,
            MaxTemplateSwitchTotalLengthStrategy,
            DS,
        >,
        _,
    >(
        reference.as_genome_subsequence(),
        query.as_genome_subsequence(),
        "reference",
        "query",
        data.query.ranges,
        AdditionalExplicitTSMStartsAndEnds::default(),
        data.costs,
        DynamicStrategies {
            ts_14_out_of_range: Ts14OutOfRangeStrategy::default(),
        },
        None,
        Some(data.memory),
        false,
        true,
        data.uncertainty_range_mode.into(),
        count_mem,
    ))
}

/// `verify_query` MUST be called before running this to ensure that the sequences are valid DNA+N
fn seq_to_genome(seq: &[u8]) -> Result<BitVectorGenome<DnaAlphabetOrN>, AlphabetError> {
    let bvg = BitVectorGenome::from_iter_u8(seq.iter().copied())?;
    Ok(bvg)
}