twitcher 0.7.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
#![cfg(test)]
use bstr::ByteSlice;

use crate::common::twitcher_cmd;

mod common;

/// Extract a counter value printed by `--stat-output` / `-v` mode from captured stderr.
/// Searches for `{key}: {number}` anywhere in the output (ANSI codes are ignored).
fn parse_counter(stderr: &[u8], key: &str) -> usize {
    let text = String::from_utf8_lossy(stderr);
    let needle = format!("{key}: ");
    for line in text.lines() {
        if let Some(pos) = line.find(&needle) {
            let (_, after) = line.split_at(pos + needle.len());
            let digits: String = after.chars().take_while(char::is_ascii_digit).collect();
            if let Ok(n) = digits.parse() {
                return n;
            }
        }
    }
    0
}

const BAM: &str = "tests/data/reads/test.bam";
const REF: &str = "tests/data/reads/test.fa.gz";

fn csv_data_rows(output: &std::process::Output) -> usize {
    // Header is always the first line; all subsequent lines are data rows.
    output.stdout.as_bstr().lines().count().saturating_sub(1)
}

#[test]
fn test_reads_produces_ts_rows() {
    // Default run: output only clusters with detected template switches.
    let cmd = twitcher_cmd(&["reads", BAM, "--reference", REF]);
    let stderr = cmd.stderr.as_bstr();
    eprintln!("{stderr}");
    assert!(cmd.status.success());
    let rows = csv_data_rows(&cmd);
    assert!(rows > 0, "expected at least one TS row in CSV output");
    // Every data line must be parseable CSV (has the id field, a non-empty uuid-like string).
    for line in cmd.stdout.as_bstr().lines().skip(1) {
        assert!(!line.is_empty(), "unexpected empty data line in CSV output");
    }
}

#[test]
fn test_reads_all_clusters_includes_non_ts() {
    // --all-clusters emits every cluster regardless of TS detection.
    // The fixture BAM has 8 TS rows (default) and 34 rows total (all clusters).
    let cmd = twitcher_cmd(&["reads", BAM, "--reference", REF, "--all-clusters"]);
    let stderr = cmd.stderr.as_bstr();
    eprintln!("{stderr}");
    assert!(cmd.status.success());
    let rows = csv_data_rows(&cmd);
    assert!(
        rows > 8,
        "--all-clusters should produce more rows than the TS-only default (8); got {rows}"
    );
}

#[test]
fn test_reads_n_flag_limits_processed_reads() {
    // -n 5 restricts processing to the first 5 reads.
    // The fixture BAM has 8 TS rows without -n; -n 5 must produce fewer.
    let cmd = twitcher_cmd(&["reads", BAM, "--reference", REF, "-n", "5"]);
    let stderr = cmd.stderr.as_bstr();
    eprintln!("{stderr}");
    assert!(cmd.status.success());
    let rows = csv_data_rows(&cmd);
    assert!(
        rows < 8,
        "-n 5 should produce fewer than 8 TS rows; got {rows}"
    );
}

#[test]
fn test_reads_no_ts_suppresses_output() {
    // --no-ts disables TS detection; default output (TS-only) must be empty.
    let cmd = twitcher_cmd(&["reads", BAM, "--reference", REF, "--no-ts"]);
    let stderr = cmd.stderr.as_bstr();
    eprintln!("{stderr}");
    assert!(cmd.status.success());
    let rows = csv_data_rows(&cmd);
    assert_eq!(rows, 0, "expected no TS rows when --no-ts is set");
}

#[test]
fn test_reads_fpa_detects_template_switches() {
    // --fpa uses the Four-Point-Aligner; must still produce TS rows.
    let cmd = twitcher_cmd(&["reads", BAM, "--reference", REF, "--fpa"]);
    let stderr = cmd.stderr.as_bstr();
    eprintln!("{stderr}");
    assert!(cmd.status.success());
    let rows = csv_data_rows(&cmd);
    assert!(rows > 0, "expected TS rows with --fpa; got {rows}");
}

#[test]
fn test_reads_output_file_flag() {
    // -o writes CSV to a file instead of stdout.
    let dir = tempfile::tempdir().unwrap();
    let csv_path = dir.path().join("out.csv");
    let cmd = twitcher_cmd(&[
        "reads",
        BAM,
        "--reference",
        REF,
        "-o",
        csv_path.to_str().unwrap(),
    ]);
    let stderr = cmd.stderr.as_bstr();
    eprintln!("{stderr}");
    assert!(cmd.status.success());
    assert!(csv_path.exists(), "output CSV file was not created");
    let content = std::fs::read_to_string(&csv_path).unwrap();
    let mut lines = content.lines();
    let header = lines.next().expect("CSV must have a header row");
    assert!(!header.is_empty());
    assert!(lines.next().is_some(), "expected at least one data row");
}

#[test]
#[expect(clippy::too_many_lines)]
fn test_db_retries_oom_on_larger_memory() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("cache.db");
    let db_str = db_path.to_str().unwrap();

    // Run 1: tiny memory limit → all alignments OOM → failures stored to DB.
    let run1 = twitcher_cmd(&[
        "reads",
        BAM,
        "--reference",
        REF,
        "-v",
        "-m",
        "1mb",
        "--threads",
        "12",
        "-n",
        "10",
        "--db",
        db_str,
    ]);
    let run1_err = String::from_utf8_lossy(&run1.stderr);
    eprintln!("run1 stderr:\n{run1_err}");
    assert!(run1.status.success());
    let computations1 = parse_counter(&run1.stderr, "alignments.computations");
    let oom1 = parse_counter(&run1.stderr, "alignments.results.failed.oom");
    assert!(computations1 > 0, "run 1 should compute alignments");
    assert!(
        oom1 > 0,
        "run 1 should produce OOM failures with tiny memory; computations={computations1}"
    );

    // Run 2: identical settings → DB serves every result, nothing recomputed.
    let run2 = twitcher_cmd(&[
        "reads",
        BAM,
        "--reference",
        REF,
        "-v",
        "-m",
        "1mb",
        "--threads",
        "12",
        "-n",
        "10",
        "--db",
        db_str,
    ]);
    let run2_err = String::from_utf8_lossy(&run2.stderr);
    eprintln!("run2 stderr:\n{run2_err}");
    assert!(run2.status.success());
    let computations2 = parse_counter(&run2.stderr, "alignments.computations");
    let from_db2 = parse_counter(&run2.stderr, "alignments.from_db");
    assert_eq!(
        computations2, 0,
        "run 2 (same memory) should not recompute anything; from_db={from_db2}"
    );
    assert!(from_db2 > 0, "run 2 should serve results from DB");

    // Run 3: larger memory → OOM failures in DB are retried instead of served.
    let run3 = twitcher_cmd(&[
        "reads",
        BAM,
        "--reference",
        REF,
        "-v",
        "-m",
        "1gb",
        "--threads",
        "12",
        "-n",
        "10",
        "--db",
        db_str,
    ]);
    let run3_err = String::from_utf8_lossy(&run3.stderr);
    eprintln!("run3 stderr:\n{run3_err}");
    assert!(run3.status.success());
    let computations3 = parse_counter(&run3.stderr, "alignments.computations");
    assert!(
        computations3 > 0,
        "run 3 (larger memory) should retry cached OOM failures; from_db2={from_db2}"
    );

    // Run 4: repeat run 3 settings → retried results now in DB, nothing recomputed.
    let run4 = twitcher_cmd(&[
        "reads",
        BAM,
        "--reference",
        REF,
        "-v",
        "-m",
        "1gb",
        "--threads",
        "12",
        "-n",
        "10",
        "--db",
        db_str,
    ]);
    let run4_err = String::from_utf8_lossy(&run4.stderr);
    eprintln!("run4 stderr:\n{run4_err}");
    assert!(run4.status.success());
    let computations4 = parse_counter(&run4.stderr, "alignments.computations");
    let from_db4 = parse_counter(&run4.stderr, "alignments.from_db");
    assert_eq!(
        computations4, 0,
        "run 4 should serve everything from DB after retry; from_db={from_db4}"
    );
    assert!(from_db4 > 0, "run 4 should find retried results in DB");
}

#[test]
fn test_output_failed_alignments() {
    let dir = tempfile::tempdir().unwrap();
    let failed_path = dir.path().join("failed.txt");

    // Run 1: tiny memory limit forces OOM failures; regions file must capture them.
    let run1 = twitcher_cmd(&[
        "reads",
        BAM,
        "--reference",
        REF,
        "-v",
        "-m",
        "1mb",
        "--threads",
        "12",
        "-n",
        "10",
        "--output-failed-alignments",
        failed_path.to_str().unwrap(),
    ]);
    eprintln!("{}", run1.stderr.as_bstr());
    assert!(run1.status.success());
    assert!(
        failed_path.exists(),
        "failed-alignments file was not created"
    );

    let content = std::fs::read_to_string(&failed_path).unwrap();
    let lines: Vec<&str> = content.lines().collect();
    assert!(!lines.is_empty(), "expected at least one failed region");
    for line in &lines {
        assert!(
            line.contains(':') && line.contains('-'),
            "line does not look like a region: {line:?}"
        );
    }
    let _failed_count = lines.len();

    // Run 2: feed the failed regions back via -T with the same memory limit.
    // Every region from run 1 must be re-attempted and fail again.
    let failed_path2 = dir.path().join("failed2.txt");
    let run2 = twitcher_cmd(&[
        "reads",
        BAM,
        "--reference",
        REF,
        "-v",
        "-m",
        "1mb",
        "--threads",
        "12",
        "-T",
        failed_path.to_str().unwrap(),
        "--output-failed-alignments",
        failed_path2.to_str().unwrap(),
    ]);
    eprintln!("{}", run2.stderr.as_bstr());
    assert!(run2.status.success());

    let computations2 = parse_counter(&run2.stderr, "alignments.computations");
    let oom2 = parse_counter(&run2.stderr, "alignments.results.failed.oom");
    assert!(
        computations2 > 0,
        "run 2 should re-attempt the failed regions; got 0 computations"
    );
    assert!(
        oom2 > 0,
        "run 2 should fail again with the same memory limit; got 0 OOM failures"
    );

    // Every failed alignment (fresh or cached) must appear in the file.
    // With 1 mb every alignment OOMs, so file line count == total OOM count.
    let content2 = std::fs::read_to_string(&failed_path2).unwrap();
    let failed_count2 = content2.lines().count();
    assert_eq!(
        failed_count2, oom2,
        "failed-alignments file line count ({failed_count2}) must equal total OOM counter ({oom2})"
    );
}

#[test]
fn test_output_alignment_stats() {
    let dir = tempfile::tempdir().unwrap();
    let stats_path = dir.path().join("alignment_stats.csv");

    let run = twitcher_cmd(&[
        "reads",
        BAM,
        "--reference",
        REF,
        "-v",
        "--output-alignment-stats",
        stats_path.to_str().unwrap(),
    ]);
    eprintln!("{}", run.stderr.as_bstr());
    assert!(run.status.success());

    let content = std::fs::read_to_string(&stats_path).unwrap();
    let mut lines = content.lines();
    let header: Vec<&str> = lines
        .next()
        .expect("stats file is empty")
        .split(',')
        .collect();
    assert_eq!(header[0], "cluster_region");

    let column = |row: &str, name: &str| -> String {
        let index = header.iter().position(|h| *h == name).unwrap();
        row.split(',').nth(index).unwrap().to_string()
    };

    // Every alignment request must be reported, exactly once.
    let rows: Vec<&str> = lines.collect();
    let requests = parse_counter(&run.stderr, "alignments");
    assert_eq!(
        rows.len(),
        requests,
        "one row per alignment request expected; counter says {requests}"
    );

    let mut computed = 0;
    for row in &rows {
        let source = column(row, "source");
        assert!(
            ["computed", "mem_cache", "db"].contains(&source.as_str()),
            "unexpected source {source:?} in row {row:?}"
        );
        let outcome = column(row, "outcome");
        assert!(
            ["ts", "no_ts", "oom", "timeout", "error"].contains(&outcome.as_str()),
            "unexpected outcome {outcome:?} in row {row:?}"
        );
        assert!(
            column(row, "wall_ms").parse::<f64>().is_ok(),
            "wall_ms is not a number in row {row:?}"
        );

        if source == "computed" {
            computed += 1;
            // The aligner process reports its own peak memory whenever it survives.
            assert!(
                column(row, "peak_vsz")
                    .parse::<u64>()
                    .is_ok_and(|vsz| vsz > 0),
                "computed alignment without peak memory: {row:?}"
            );
        }
    }
    assert_eq!(
        computed,
        parse_counter(&run.stderr, "alignments.computations"),
        "computed rows must match the computation counter"
    );
}

/// The uncertainty ranges are measured on an alignment extended across the padding, but the
/// extension is cut again before reporting, so the cluster-local cigars stay cluster-local while
/// the measurement survives.
#[test]
fn test_reads_uncertainty_range_survives_the_cut() {
    let cmd = twitcher_cmd(&["reads", BAM, "--reference", REF]);
    let stderr = cmd.stderr.as_bstr();
    eprintln!("{stderr}");
    assert!(cmd.status.success());
    assert!(
        !stderr.contains_str("Cannot cut the range extension"),
        "the range extension could not be cut"
    );

    let stdout = String::from_utf8_lossy(&cmd.stdout);
    let mut rows = stdout.lines();
    let header: Vec<&str> = rows.next().expect("csv header").split(',').collect();
    let index = |name: &str| {
        header
            .iter()
            .position(|h| *h == name)
            .expect("column exists")
    };
    let (ts_cigar, ts_cigar_ctx) = (index("ts_cigar"), index("ts_cigar_ctx"));

    let mut checked = 0;
    for row in rows {
        let fields: Vec<&str> = row.split(',').collect();
        let cigar = fields[ts_cigar].trim_matches('"');
        let ctx = fields[ts_cigar_ctx].trim_matches('"');
        assert_ne!(
            cigar, ctx,
            "the cluster cigar must not have spread over the whole context"
        );
        checked += 1;
    }
    assert!(checked > 0, "expected at least one TS row");
}

/// `ts_cigar` and `fw_cigar` cover the alignment range, not the cluster region, and that range
/// has to be named for them to be readable.
#[test]
fn test_reads_emits_aln_region() {
    let cmd = twitcher_cmd(&["reads", BAM, "--reference", REF]);
    eprintln!("{}", cmd.stderr.as_bstr());
    assert!(cmd.status.success());

    let stdout = String::from_utf8_lossy(&cmd.stdout);
    let mut rows = stdout.lines();
    let header: Vec<&str> = rows.next().expect("csv header").split(',').collect();
    let index = |name: &str| {
        header
            .iter()
            .position(|h| *h == name)
            .expect("column exists")
    };
    let fields: Vec<&str> = rows.next().expect("a data row").split(',').collect();

    let cluster = fields[index("cluster_region")];
    let aln = fields[index("aln_region")];
    let ctx = fields[index("ref_ctx_region")];
    let start = |region: &str| -> usize {
        region
            .split(':')
            .nth(1)
            .unwrap()
            .split('-')
            .next()
            .unwrap()
            .parse()
            .unwrap()
    };

    // The alignment range sits between the context window and the cluster it surrounds.
    assert!(
        start(ctx) <= start(aln),
        "{ctx} should start at or before {aln}"
    );
    assert!(
        start(aln) <= start(cluster),
        "{aln} should start at or before {cluster}"
    );
    // Default --range-extension is 5.
    assert_eq!(start(cluster) - start(aln), 5, "{aln} vs {cluster}");
}