twitcher 0.7.0

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
use std::{error::Error, fmt::Display, time::Duration};

use anyhow::bail;
use generic_a_star::AStarResult;

use itertools::Itertools as _;
use lib_tsalign::{
    a_star_aligner::{
        alignment_result::{AlignmentResult, AlignmentStatistics, alignment::Alignment},
        template_switch_distance::{AlignmentType, EqualCostRange},
    },
    costs::U64Cost,
};
use serde::{Deserialize, Serialize};

use crate::common::{
    aligner::exec_stats::ExecStats,
    aligner::fpa::FpaAlignmentStatistics,
    alignment::consumed_reference,
    coords::{GenomePosition, GenomeRegion},
};

/// The outcome of an alignment, as reported by the aligner process.
pub type TwitcherAlignmentResult = Result<TwitcherAlignmentWithStatistics, AlignmentFailure>;

/// An alignment outcome together with what it took to produce it. This is the output of the whole
/// `aligner` module.
///
/// The [`ExecStats`] are attached to failures as well, so that a timed out or out-of-memory
/// alignment can still be reported with its runtime and memory.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TwitcherAlignment {
    pub outcome: TwitcherAlignmentResult,
    pub exec: ExecStats,
}

impl TwitcherAlignment {
    pub const fn new(outcome: TwitcherAlignmentResult, exec: ExecStats) -> Self {
        Self { outcome, exec }
    }
}

/// The result of a call to the aligner which completed successfully.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TwitcherAlignmentWithStatistics {
    pub alignment: AlignmentWithCost,
    pub stats: TwitcherAlignmentStatistics,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
/// Statistics that are returned by the aligner
pub enum TwitcherAlignmentStatistics {
    FPAStats(Box<FpaAlignmentStatistics>),
    TSAlign(Box<AlignmentStatistics<U64Cost>>),
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AlignmentWithCost {
    pub alignment: Alignment<AlignmentType>,
    pub cost: U64Cost,
}

impl AlignmentWithCost {
    pub const fn new(alignment: Alignment<AlignmentType>, cost: U64Cost) -> Self {
        Self { alignment, cost }
    }
    pub fn has_ts(&self) -> bool {
        self.alignment
            .iter_compact()
            .any(|(_, ty)| matches!(ty, AlignmentType::TemplateSwitchEntrance { .. }))
    }
}

/// The two ways an aligner can fail: expectedly or unexpectedly.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum AlignmentFailure {
    SoftFailure { reason: SoftFailureReason },
    Error { error: String },
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum SoftFailureReason {
    OutOfMemory,
    Timeout(Duration),
    Other(String),
}

impl TwitcherAlignmentWithStatistics {
    pub const fn new(
        alignment: Alignment<AlignmentType>,
        cost: U64Cost,
        stats: TwitcherAlignmentStatistics,
    ) -> Self {
        Self {
            alignment: AlignmentWithCost { alignment, cost },
            stats,
        }
    }

    pub fn has_ts(&self) -> bool {
        self.alignment.has_ts()
    }
}

impl TwitcherAlignmentStatistics {
    pub fn reference_offset(&self) -> usize {
        match self {
            Self::FPAStats(fpa_alignment_statistics) => {
                fpa_alignment_statistics.ranges.reference_offset()
            }
            Self::TSAlign(alignment_statistics) => alignment_statistics.reference_offset,
        }
    }

    pub fn query_offset(&self) -> usize {
        match self {
            Self::FPAStats(fpa_alignment_statistics) => {
                fpa_alignment_statistics.ranges.query_offset()
            }
            Self::TSAlign(alignment_statistics) => alignment_statistics.query_offset,
        }
    }

    /// How long the alignment itself took, excluding the overhead of the aligner process.
    pub fn duration(&self) -> Duration {
        match self {
            Self::FPAStats(fpa_alignment_statistics) => fpa_alignment_statistics.duration,
            Self::TSAlign(alignment_statistics) => {
                Duration::from_secs_f64(alignment_statistics.duration_seconds.raw().max(0.0))
            }
        }
    }
}

impl AlignmentFailure {
    pub const fn oom() -> Self {
        Self::SoftFailure {
            reason: SoftFailureReason::OutOfMemory,
        }
    }

    pub const fn timeout(duration: Duration) -> Self {
        Self::SoftFailure {
            reason: SoftFailureReason::Timeout(duration),
        }
    }

    pub fn soft_fail<S: ToString>(error: &S) -> Self {
        Self::SoftFailure {
            reason: SoftFailureReason::Other(error.to_string()),
        }
    }

    pub fn error<S: ToString + ?Sized>(error: &S) -> Self {
        Self::Error {
            error: error.to_string(),
        }
    }
}

pub fn from_tsalign(
    tsalign_result: AlignmentResult<AlignmentType, U64Cost>,
) -> TwitcherAlignmentResult {
    let (alignment_cigar, mut statistics) = match tsalign_result {
        AlignmentResult::WithTarget {
            alignment,
            statistics,
        } => (Some(alignment), statistics),
        AlignmentResult::WithoutTarget { statistics } => (None, statistics),
    };

    // Remove the sequences from the statistics, since we handle sequences throughout twitcher as shared references (Arc<[u8]>) elsewhere.
    statistics.sequences.reference = String::new();
    statistics.sequences.reference_rc = String::new();
    statistics.sequences.query = String::new();
    statistics.sequences.query_rc = String::new();

    if let Some(alignment_cigar) = alignment_cigar {
        let cost = statistics.result.cost();
        Ok(TwitcherAlignmentWithStatistics::new(
            alignment_cigar,
            cost,
            statistics.into(),
        ))
    } else {
        let reason = match statistics.result {
            AStarResult::FoundTarget { .. } => {
                anyhow::anyhow!("There should be an alignment available, but it is not reported")
            }
            AStarResult::ExceededCostLimit { cost_limit } => {
                anyhow::anyhow!("Exceeded cost limit. Lower bound for the cost: {cost_limit}")
            }
            AStarResult::ExceededMemoryLimit { .. } => {
                return Err(AlignmentFailure::oom());
            }
            AStarResult::NoTarget => {
                anyhow::anyhow!("There was no target (implementation error?)")
            }
        };
        Err(AlignmentFailure::soft_fail(&reason))
    }
}

impl From<FpaAlignmentStatistics> for TwitcherAlignmentStatistics {
    fn from(value: FpaAlignmentStatistics) -> Self {
        Self::FPAStats(value.into())
    }
}

impl From<AlignmentStatistics<U64Cost>> for TwitcherAlignmentStatistics {
    fn from(value: AlignmentStatistics<U64Cost>) -> Self {
        Self::TSAlign(value.into())
    }
}

impl From<anyhow::Error> for AlignmentFailure {
    fn from(value: anyhow::Error) -> Self {
        Self::Error {
            error: value.to_string(),
        }
    }
}

impl From<std::io::Error> for AlignmentFailure {
    fn from(value: std::io::Error) -> Self {
        Self::Error {
            error: value.to_string(),
        }
    }
}

impl Display for AlignmentFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SoftFailure {
                reason: SoftFailureReason::OutOfMemory,
            } => write!(f, "Expected failure: Out of memory."),
            Self::SoftFailure {
                reason: SoftFailureReason::Timeout(dur),
            } => write!(f, "Expected failure: Timeout ({dur:?})."),
            Self::SoftFailure {
                reason: SoftFailureReason::Other(e),
            } => write!(f, "Expected failure: {e}."),
            Self::Error { error } => write!(f, "Unexpected failure: {error}"),
        }
    }
}

impl Error for AlignmentFailure {}

#[derive(Debug)]
pub struct TSData {
    pub inner_len: usize,
    pub jump_1_2: isize,
    pub er: Option<EqualCostRange>,
    pub inner_aln: Alignment<AlignmentType>,
    pub apg: isize,
    pub pos_1: GenomePosition,
    pub pos_4: GenomePosition,
}

impl TSData {
    pub fn compute(
        region: &GenomeRegion,
        result: &TwitcherAlignmentWithStatistics,
    ) -> anyhow::Result<Vec<Self>> {
        let alignment = &result.alignment.alignment;

        let mut pos = region.start().clone() + result.stats.reference_offset();

        let mut results = Vec::new();
        let mut curr_data = None;
        let mut curr_ts_descendant = None;
        for (n, ty) in alignment.iter_compact() {
            pos += consumed_reference(n, ty, curr_ts_descendant)?;
            match ty {
                AlignmentType::TemplateSwitchEntrance {
                    first_offset,
                    equal_cost_range,
                    descendant,
                    ..
                } => {
                    curr_data = Some(Self {
                        inner_len: 0, // will change
                        jump_1_2: *first_offset,
                        er: (equal_cost_range.is_valid()).then_some(*equal_cost_range),
                        inner_aln: Alignment::new(), // will change
                        apg: 0,                      // will change
                        pos_1: pos.clone(),
                        pos_4: pos.clone(), // Will change
                    });
                    curr_ts_descendant = Some(*descendant);
                }
                AlignmentType::TemplateSwitchExit {
                    anti_descendant_gap,
                } => {
                    let Some(mut current) = curr_data.take() else {
                        bail!("Invalid alignment");
                    };
                    current.apg = *anti_descendant_gap;
                    current.pos_4 = pos.clone();
                    results.push(current);
                    curr_ts_descendant = None;
                }
                AlignmentType::SecondaryInsertion
                | AlignmentType::SecondarySubstitution
                | AlignmentType::SecondaryMatch => {
                    let Some(current) = &mut curr_data else {
                        bail!("Invalid alignment");
                    };
                    current.inner_len += n;
                    current.inner_aln.push_n(n, *ty);
                }
                AlignmentType::SecondaryDeletion => {
                    let Some(current) = &mut curr_data else {
                        bail!("Invalid alignment");
                    };
                    current.inner_aln.push_n(n, *ty);
                }
                _ => {}
            }
        }
        Ok(results)
    }

    pub fn to_field<S: ToString>(data: &[Self], sep: &str, f: impl Fn(&Self) -> S) -> String {
        data.iter().map(|d| f(d).to_string()).join(sep)
    }

    pub fn to_field_fallible<S: ToString>(
        data: &[Self],
        sep: &str,
        f: impl Fn(&Self) -> anyhow::Result<S>,
    ) -> anyhow::Result<String> {
        itertools::process_results(data.iter().map(f), |iter| {
            iter.map(|s| s.to_string()).join(sep)
        })
    }

    pub fn to_opt_field<S: ToString, K>(
        data: &[Self],
        sep: &str,
        opt: impl Fn(&Self) -> Option<&K>,
        f: impl Fn(&Self, &K) -> S,
    ) -> String {
        data.iter()
            .map(|d| opt(d).map(|k| f(d, k).to_string()).unwrap_or_default())
            .join(sep)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::contig::ContigName;

    fn ts_data(er: Option<EqualCostRange>) -> TSData {
        let pos = GenomePosition::new_0(ContigName::new(b"chr1"), 100);
        TSData {
            inner_len: 10,
            jump_1_2: -20,
            er,
            inner_aln: Alignment::new(),
            apg: 5,
            pos_1: pos.clone(),
            pos_4: pos,
        }
    }

    /// `to_opt_field` must behave like `to_field` for valid ranges, and yield
    /// empty entries (but keep the separators) for missing ones.
    #[test]
    fn to_opt_field_skips_missing_equal_cost_ranges() {
        let valid = EqualCostRange {
            min_start: -1,
            max_start: 2,
            min_end: -3,
            max_end: 4,
        };
        assert!(valid.is_valid());
        assert!(!EqualCostRange::new_invalid().is_valid());

        let data = [ts_data(Some(valid)), ts_data(None), ts_data(Some(valid))];
        let field =
            |d: &[TSData]| TSData::to_opt_field(d, ",", |d| d.er.as_ref(), |_, er| er.max_end);

        // No regression: with all ranges present the output matches `to_field`.
        let all_valid = [ts_data(Some(valid)), ts_data(Some(valid))];
        assert_eq!(
            field(&all_valid),
            TSData::to_field(&all_valid, ",", |d| d.er.unwrap().max_end)
        );

        // Missing range yields a null string in its slot.
        assert_eq!(field(&data), "4,,4");
        assert_eq!(field(&[ts_data(None)]), "");

        // Same for the derived min/max columns.
        assert_eq!(
            TSData::to_opt_field(
                &data,
                ",",
                |d| d.er.as_ref(),
                |d, er| d.inner_len
                    - usize::try_from(er.max_start).unwrap_or_default()
                    - usize::try_from(-er.min_end).unwrap_or_default()
            ),
            "5,,5"
        );
    }
}