fgumi 0.2.0

High-performance tools for UMI-tagged sequencing data: extraction, grouping, and consensus calling
Documentation
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
//! End-to-end CLI tests for the zipper command.
//!
//! These tests run the actual `fgumi zipper` binary and validate:
//! 1. Basic merge of unmapped + mapped BAMs with tag transfer
//! 2. Tag removal via `--tags-to-remove`
//! 3. Error on missing input files

use fgumi_lib::sam::SamTag;
use fgumi_raw_bam::{RawRecord, SamBuilder, flags};
use noodles::bam;
use noodles::sam;
use noodles::sam::alignment::io::Write as AlignmentWrite;
use noodles::sam::alignment::record::data::field::Tag;
use noodles::sam::alignment::record_buf::RecordBuf;
use std::fs;
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use tempfile::TempDir;

use crate::helpers::bam_generator::{create_minimal_header, create_test_reference, to_record_buf};

/// Create a queryname-sorted unmapped BAM with UMI tags (RX/QX).
fn create_unmapped_bam(path: &Path, records: &[RawRecord]) {
    let header = sam::Header::default();
    let mut writer =
        bam::io::Writer::new(fs::File::create(path).expect("Failed to create unmapped BAM"));
    writer.write_header(&header).expect("Failed to write header");
    for record in records {
        writer
            .write_alignment_record(&header, &to_record_buf(record))
            .expect("Failed to write record");
    }
    writer.finish(&header).expect("Failed to finish BAM");
}

/// Create a mapped SAM file with aligned reads (same read names as unmapped).
fn create_mapped_sam(path: &Path, header: &sam::Header, records: &[RawRecord]) {
    let file = fs::File::create(path).expect("Failed to create mapped SAM");
    let mut writer = sam::io::Writer::new(file);
    writer.write_header(header).expect("Failed to write header");
    for record in records {
        writer
            .write_alignment_record(header, &to_record_buf(record))
            .expect("Failed to write record");
    }
}

/// Create a mapped BAM file with aligned reads (same read names as unmapped).
fn create_mapped_bam(path: &Path, header: &sam::Header, records: &[RawRecord]) {
    let mut writer =
        bam::io::Writer::new(fs::File::create(path).expect("Failed to create mapped BAM"));
    writer.write_header(header).expect("Failed to write header");
    for record in records {
        writer
            .write_alignment_record(header, &to_record_buf(record))
            .expect("Failed to write record");
    }
    writer.finish(header).expect("Failed to finish BAM");
}

/// Test basic zipper merge — unmapped tags are transferred to mapped reads.
#[test]
fn test_zipper_basic_merge() {
    let temp_dir = TempDir::new().unwrap();
    let unmapped_bam = temp_dir.path().join("unmapped.bam");
    let mapped_sam = temp_dir.path().join("mapped.sam");
    let output_bam = temp_dir.path().join("output.bam");
    let ref_path = create_test_reference(temp_dir.path());

    // Unmapped reads with RX/QX tags
    let unmapped_records = vec![
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read1")
                .sequence(b"ACGTACGT")
                .qualities(&[30; 8])
                .flags(flags::UNMAPPED)
                .add_string_tag(b"RX", b"AACCGGTT")
                .add_string_tag(b"QX", b"IIIIIIII");
            b.build()
        },
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read2")
                .sequence(b"TGCATGCA")
                .qualities(&[30; 8])
                .flags(flags::UNMAPPED)
                .add_string_tag(b"RX", b"GGTTCCAA")
                .add_string_tag(b"QX", b"IIIIIIII");
            b.build()
        },
    ];
    create_unmapped_bam(&unmapped_bam, &unmapped_records);

    // Mapped reads (same names, aligned to chr1)
    let mapped_header = create_minimal_header("chr1", 10000);
    let mapped_records = vec![
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read1")
                .sequence(b"ACGTACGT")
                .qualities(&[30; 8])
                .ref_id(0)
                .pos(99)
                .mapq(60)
                .cigar_ops(&[8 << 4]); // 8M
            b.build()
        },
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read2")
                .sequence(b"TGCATGCA")
                .qualities(&[30; 8])
                .ref_id(0)
                .pos(199)
                .mapq(60)
                .cigar_ops(&[8 << 4]); // 8M
            b.build()
        },
    ];
    create_mapped_sam(&mapped_sam, &mapped_header, &mapped_records);

    let status = Command::new(env!("CARGO_BIN_EXE_fgumi"))
        .args([
            "zipper",
            "--input",
            mapped_sam.to_str().unwrap(),
            "--unmapped",
            unmapped_bam.to_str().unwrap(),
            "--reference",
            ref_path.to_str().unwrap(),
            "--output",
            output_bam.to_str().unwrap(),
            "--compression-level",
            "1",
        ])
        .status()
        .expect("Failed to run zipper command");

    assert!(status.success(), "Zipper command failed");
    assert!(output_bam.exists(), "Output BAM not created");

    // Verify output records have UMI tags transferred
    let mut reader = bam::io::Reader::new(fs::File::open(&output_bam).unwrap());
    let header = reader.read_header().unwrap();
    let records: Vec<RecordBuf> = reader.record_bufs(&header).map(|r| r.unwrap()).collect();
    assert_eq!(records.len(), 2, "Should have 2 records in output");

    let rx_tag = Tag::from(SamTag::RX);
    for record in &records {
        assert!(record.data().get(&rx_tag).is_some(), "Output record should have RX tag");
    }
}

/// Test zipper with `--tags-to-remove` strips specified tags.
#[test]
fn test_zipper_tag_removal() {
    let temp_dir = TempDir::new().unwrap();
    let unmapped_bam = temp_dir.path().join("unmapped.bam");
    let mapped_sam = temp_dir.path().join("mapped.sam");
    let output_bam = temp_dir.path().join("output.bam");
    let ref_path = create_test_reference(temp_dir.path());

    // Unmapped read with RX and a custom tag XY
    let unmapped_records = vec![{
        let mut b = SamBuilder::new();
        b.read_name(b"read1")
            .sequence(b"ACGTACGT")
            .qualities(&[30; 8])
            .flags(flags::UNMAPPED)
            .add_string_tag(b"RX", b"AACCGGTT")
            .add_string_tag(b"XY", b"REMOVE_ME");
        b.build()
    }];
    create_unmapped_bam(&unmapped_bam, &unmapped_records);

    let mapped_header = create_minimal_header("chr1", 10000);
    let mapped_records = vec![{
        let mut b = SamBuilder::new();
        b.read_name(b"read1")
            .sequence(b"ACGTACGT")
            .qualities(&[30; 8])
            .ref_id(0)
            .pos(99)
            .mapq(60)
            .cigar_ops(&[8 << 4]); // 8M
        b.build()
    }];
    create_mapped_sam(&mapped_sam, &mapped_header, &mapped_records);

    let status = Command::new(env!("CARGO_BIN_EXE_fgumi"))
        .args([
            "zipper",
            "--input",
            mapped_sam.to_str().unwrap(),
            "--unmapped",
            unmapped_bam.to_str().unwrap(),
            "--reference",
            ref_path.to_str().unwrap(),
            "--output",
            output_bam.to_str().unwrap(),
            "--tags-to-remove",
            "XY",
            "--compression-level",
            "1",
        ])
        .status()
        .expect("Failed to run zipper command");

    assert!(status.success(), "Zipper command with --tags-to-remove failed");

    // Verify XY tag was removed but RX tag was kept
    let mut reader = bam::io::Reader::new(fs::File::open(&output_bam).unwrap());
    let header = reader.read_header().unwrap();
    let records: Vec<RecordBuf> = reader.record_bufs(&header).map(|r| r.unwrap()).collect();
    assert_eq!(records.len(), 1);

    let rx_tag = Tag::from(SamTag::RX);
    let xy_tag = Tag::from(SamTag::new(b'X', b'Y'));
    assert!(records[0].data().get(&rx_tag).is_some(), "RX tag should be present");
    assert!(records[0].data().get(&xy_tag).is_none(), "XY tag should have been removed");
}

/// Test zipper errors with non-zero exit code for missing input file.
#[test]
fn test_zipper_missing_input() {
    let temp_dir = TempDir::new().unwrap();
    let output_bam = temp_dir.path().join("output.bam");
    let ref_path = create_test_reference(temp_dir.path());

    let missing_mapped = temp_dir.path().join("missing.mapped.sam");
    let missing_unmapped = temp_dir.path().join("missing.unmapped.bam");

    let status = Command::new(env!("CARGO_BIN_EXE_fgumi"))
        .args([
            "zipper",
            "--input",
            missing_mapped.to_str().unwrap(),
            "--unmapped",
            missing_unmapped.to_str().unwrap(),
            "--reference",
            ref_path.to_str().unwrap(),
            "--output",
            output_bam.to_str().unwrap(),
        ])
        .status()
        .expect("Failed to run zipper command");

    assert!(!status.success(), "Zipper should fail for nonexistent input");
}

/// Test zipper accepts BAM as mapped input (--input).
#[test]
fn test_zipper_bam_mapped_input() {
    let temp_dir = TempDir::new().unwrap();
    let unmapped_bam = temp_dir.path().join("unmapped.bam");
    let mapped_bam = temp_dir.path().join("mapped.bam");
    let output_bam = temp_dir.path().join("output.bam");
    let ref_path = create_test_reference(temp_dir.path());

    let unmapped_records = vec![
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read1")
                .sequence(b"ACGTACGT")
                .qualities(&[30; 8])
                .flags(flags::UNMAPPED)
                .add_string_tag(b"RX", b"AACCGGTT")
                .add_string_tag(b"QX", b"IIIIIIII");
            b.build()
        },
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read2")
                .sequence(b"TGCATGCA")
                .qualities(&[30; 8])
                .flags(flags::UNMAPPED)
                .add_string_tag(b"RX", b"GGTTCCAA")
                .add_string_tag(b"QX", b"IIIIIIII");
            b.build()
        },
    ];
    create_unmapped_bam(&unmapped_bam, &unmapped_records);

    let mapped_header = create_minimal_header("chr1", 10000);
    let mapped_records = vec![
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read1")
                .sequence(b"ACGTACGT")
                .qualities(&[30; 8])
                .ref_id(0)
                .pos(99)
                .mapq(60)
                .cigar_ops(&[8 << 4]); // 8M
            b.build()
        },
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read2")
                .sequence(b"TGCATGCA")
                .qualities(&[30; 8])
                .ref_id(0)
                .pos(199)
                .mapq(60)
                .cigar_ops(&[8 << 4]); // 8M
            b.build()
        },
    ];
    create_mapped_bam(&mapped_bam, &mapped_header, &mapped_records);

    let output = Command::new(env!("CARGO_BIN_EXE_fgumi"))
        .args([
            "zipper",
            "--input",
            mapped_bam.to_str().unwrap(),
            "--unmapped",
            unmapped_bam.to_str().unwrap(),
            "--reference",
            ref_path.to_str().unwrap(),
            "--output",
            output_bam.to_str().unwrap(),
            "--compression-level",
            "1",
        ])
        .output()
        .expect("Failed to run zipper command");

    assert!(
        output.status.success(),
        "Zipper command failed with BAM input: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output_bam.exists(), "Output BAM not created");

    // Verify output records have UMI tags transferred
    let mut reader = bam::io::Reader::new(fs::File::open(&output_bam).unwrap());
    let header = reader.read_header().unwrap();
    let records: Vec<RecordBuf> = reader.record_bufs(&header).map(|r| r.unwrap()).collect();
    assert_eq!(records.len(), 2, "Should have 2 records in output");

    let rx_tag = Tag::from(SamTag::RX);
    for record in &records {
        assert!(record.data().get(&rx_tag).is_some(), "Output record should have RX tag");
    }

    // Verify warning about BAM input was emitted
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("BAM input detected"), "Should warn about BAM input. stderr: {stderr}");
}

/// Test zipper accepts BAM piped to stdin (auto-detected via BGZF magic bytes).
///
/// Common in nf-core / Galaxy pipelines that produce BAM from intermediate steps
/// (e.g. `bwameth.py | samtools view -b | fgumi zipper`). Without auto-detection,
/// fgumi treats stdin as SAM text and crashes with a confusing
/// "invalid flags / lexical parse error" error from the SAM parser misreading
/// BGZF binary bytes.
#[test]
fn test_zipper_bam_stdin_input() {
    let temp_dir = TempDir::new().unwrap();
    let unmapped_bam = temp_dir.path().join("unmapped.bam");
    let mapped_bam = temp_dir.path().join("mapped.bam");
    let output_bam = temp_dir.path().join("output.bam");
    let ref_path = create_test_reference(temp_dir.path());

    let unmapped_records = vec![
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read1")
                .sequence(b"ACGTACGT")
                .qualities(&[30; 8])
                .flags(flags::UNMAPPED)
                .add_string_tag(b"RX", b"AACCGGTT")
                .add_string_tag(b"QX", b"IIIIIIII");
            b.build()
        },
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read2")
                .sequence(b"TGCATGCA")
                .qualities(&[30; 8])
                .flags(flags::UNMAPPED)
                .add_string_tag(b"RX", b"GGTTCCAA")
                .add_string_tag(b"QX", b"IIIIIIII");
            b.build()
        },
    ];
    create_unmapped_bam(&unmapped_bam, &unmapped_records);

    let mapped_header = create_minimal_header("chr1", 10000);
    let mapped_records = vec![
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read1")
                .sequence(b"ACGTACGT")
                .qualities(&[30; 8])
                .ref_id(0)
                .pos(99)
                .mapq(60)
                .cigar_ops(&[8 << 4]); // 8M
            b.build()
        },
        {
            let mut b = SamBuilder::new();
            b.read_name(b"read2")
                .sequence(b"TGCATGCA")
                .qualities(&[30; 8])
                .ref_id(0)
                .pos(199)
                .mapq(60)
                .cigar_ops(&[8 << 4]); // 8M
            b.build()
        },
    ];
    create_mapped_bam(&mapped_bam, &mapped_header, &mapped_records);

    // Pipe the BAM bytes into the child's stdin; do NOT pass --input so that
    // the default ("-") triggers the stdin code path.
    let bam_bytes = fs::read(&mapped_bam).expect("read mapped BAM bytes");
    let mut child = Command::new(env!("CARGO_BIN_EXE_fgumi"))
        .args([
            "zipper",
            "--unmapped",
            unmapped_bam.to_str().unwrap(),
            "--reference",
            ref_path.to_str().unwrap(),
            "--output",
            output_bam.to_str().unwrap(),
            "--compression-level",
            "1",
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn zipper command");

    child
        .stdin
        .as_mut()
        .expect("Failed to open child stdin")
        .write_all(&bam_bytes)
        .expect("Failed to write BAM bytes to stdin");

    let output = child.wait_with_output().expect("Failed to wait for zipper");

    assert!(
        output.status.success(),
        "Zipper command failed with BAM on stdin: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output_bam.exists(), "Output BAM not created");

    // Verify output records have UMI tags transferred
    let mut reader = bam::io::Reader::new(fs::File::open(&output_bam).unwrap());
    let header = reader.read_header().unwrap();
    let records: Vec<RecordBuf> = reader.record_bufs(&header).map(|r| r.unwrap()).collect();
    assert_eq!(records.len(), 2, "Should have 2 records in output");

    let rx_tag = Tag::from(SamTag::RX);
    for record in &records {
        assert!(record.data().get(&rx_tag).is_some(), "Output record should have RX tag");
    }
}