Debian Codegraph @

samtools/bam_mate.c

raw symbols SCIP
1 /* bam_mate.c -- fix mate pairing information and clean up flags.
2
3 Copyright (C) 2009, 2011-2017, 2019, 2022, 2024 Genome Research Ltd.
4 Portions copyright (C) 2011 Broad Institute.
5 Portions copyright (C) 2012 Peter Cock, The James Hutton Institute.
6
7 Author: Heng Li <[email protected]>
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notices and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 DEALINGS IN THE SOFTWARE. */
26
27 #include <config.h>
28
29 #include <assert.h>
30 #include <stdbool.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <ctype.h>
35 #include "htslib/thread_pool.h"
36 #include "sam_opts.h"
37 #include "htslib/kstring.h"
38 #include "htslib/sam.h"
39 #include "samtools.h"
40
41
42 #define MD_MIN_QUALITY 15
43
44 /*
45 * This function calculates ct tag for two bams, it assumes they are from the same template and
46 * writes the tag to the first read in position terms.
47 */
48 static void bam_template_cigar(bam1_t *b1, bam1_t *b2, kstring_t *str)
49 {
50 bam1_t *swap;
51 int i;
52 hts_pos_t end;
53 uint32_t *cigar;
54 str->l = 0;
55 if (b1->core.tid != b2->core.tid || b1->core.tid < 0 || b1->core.pos < 0 || b2->core.pos < 0 || b1->core.flag&BAM_FUNMAP || b2->core.flag&BAM_FUNMAP) return; // coordinateless or not on the same chr; skip
56 if (b1->core.pos > b2->core.pos) swap = b1, b1 = b2, b2 = swap; // make sure b1 has a smaller coordinate
57 kputc((b1->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index
58 kputc((b1->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand
59 for (i = 0, cigar = bam_get_cigar(b1); i < b1->core.n_cigar; ++i) {
60 kputw(bam_cigar_oplen(cigar[i]), str);
61 kputc(bam_cigar_opchr(cigar[i]), str);
62 }
63 end = bam_endpos(b1);
64 kputw(b2->core.pos - end, str);
65 kputc('T', str);
66 kputc((b2->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index
67 kputc((b2->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand
68 for (i = 0, cigar = bam_get_cigar(b2); i < b2->core.n_cigar; ++i) {
69 kputw(bam_cigar_oplen(cigar[i]), str);
70 kputc(bam_cigar_opchr(cigar[i]), str);
71 }
72
73 uint8_t* data;
74 if ((data = bam_aux_get(b1,"ct")) != NULL) bam_aux_del(b1, data);
75 if ((data = bam_aux_get(b2,"ct")) != NULL) bam_aux_del(b2, data);
76
77 bam_aux_append(b1, "ct", 'Z', str->l+1, (uint8_t*)str->s);
78 }
79
80 /*
81 * What This Program is Supposed To Do:
82 * Fill in mate coordinates, ISIZE and mate related flags from a name-sorted
83 * alignment.
84 *
85 * How We Handle Input
86 *
87 * Secondary and supplementary Reads:
88 * -write to output unchanged
89 * All Reads:
90 * -if pos == 0 (1 based), tid == -1 set UNMAPPED flag
91 * single Reads:
92 * -if pos == 0 (1 based), tid == -1, or UNMAPPED then set UNMAPPED, pos = 0,
93 * tid = -1
94 * -clear bad flags (MREVERSE, PROPER_PAIR)
95 * -set mpos = 0 (1 based), mtid = -1 and isize = 0
96 * -write to output
97 * Paired Reads:
98 * -if read is unmapped and mate is not, set pos and tid to equal that of mate
99 * -sync mate flags (MREVERSE, MUNMAPPED), mpos, mtid
100 * -recalculate ISIZE if possible, otherwise set it to 0
101 * -optionally clear PROPER_PAIR flag from reads where mapping or orientation
102 * indicate this is not possible (Illumina orientation only)
103 * -calculate ct and apply to lowest positioned read
104 * -write to output
105 * Limitations
106 * -Does not handle tandem reads
107 * -Should mark supplementary reads the same as primary.
108 * Notes
109 * -CT definition appears to be something else in spec, this was in here before
110 * I started tampering with it, anyone know what is going on here? To work
111 * around this I have demoted the CT this tool generates to ct.
112 */
113
114 static void sync_unmapped_pos_inner(bam1_t* src, bam1_t* dest) {
115 if ((dest->core.flag & BAM_FUNMAP) && !(src->core.flag & BAM_FUNMAP)) {
116 // Set unmapped read's RNAME and POS to those of its mapped mate
117 // (recommended best practice, ensures if coord sort will be together)
118 dest->core.tid = src->core.tid;
119 dest->core.pos = src->core.pos;
120 }
121 }
122
123 static void sync_mate_inner(bam1_t* src, bam1_t* dest)
124 {
125 // sync mate pos information
126 dest->core.mtid = src->core.tid; dest->core.mpos = src->core.pos;
127 // sync flag info
128 if (src->core.flag&BAM_FREVERSE)
129 dest->core.flag |= BAM_FMREVERSE;
130 else
131 dest->core.flag &= ~BAM_FMREVERSE;
132 if (src->core.flag & BAM_FUNMAP) {
133 dest->core.flag |= BAM_FMUNMAP;
134 }
135 }
136
137 // Is it plausible that these reads are properly paired?
138 // Can't really give definitive answer without checking isize
139 static bool plausibly_properly_paired(bam1_t* a, bam1_t* b)
140 {
141 if ((a->core.flag & BAM_FUNMAP) || (b->core.flag & BAM_FUNMAP)) return false;
142 assert(a->core.tid >= 0); // This should never happen if FUNMAP is set correctly
143
144 if (a->core.tid != b->core.tid) return false;
145
146 bam1_t* first = a;
147 bam1_t* second = b;
148 hts_pos_t a_pos = a->core.flag&BAM_FREVERSE ? bam_endpos(a) : a->core.pos;
149 hts_pos_t b_pos = b->core.flag&BAM_FREVERSE ? bam_endpos(b) : b->core.pos;
150 if (a_pos > b_pos) {
151 first = b;
152 second = a;
153 } else {
154 first = a;
155 second = b;
156 }
157
158 if (!(first->core.flag&BAM_FREVERSE) && (second->core.flag&BAM_FREVERSE))
159 return true;
160 else
161 return false;
162 }
163
164 // Returns 0 on success, -1 on failure.
165 static int bam_format_cigar(const bam1_t* b, kstring_t* str)
166 {
167 // An empty cigar is a special case return "*" rather than ""
168 if (b->core.n_cigar == 0) {
169 return (kputc('*', str) == EOF) ? -1 : 0;
170 }
171
172 const uint32_t *cigar = bam_get_cigar(b);
173 uint32_t i;
174
175 for (i = 0; i < b->core.n_cigar; ++i) {
176 if (kputw(bam_cigar_oplen(cigar[i]), str) == EOF) return -1;
177 if (kputc(bam_cigar_opchr(cigar[i]), str) == EOF) return -1;
178 }
179
180 return 0;
181 }
182
183 // Returns 0 on success, -1 on failure.
184 static int sync_mq_mc(bam1_t* src, bam1_t* dest)
185 {
186 if ( (src->core.flag & BAM_FUNMAP) == 0 ) { // If mapped
187 // Copy Mate Mapping Quality
188 uint32_t mq = src->core.qual;
189 uint8_t* data;
190 if ((data = bam_aux_get(dest,"MQ")) != NULL) {
191 bam_aux_del(dest, data);
192 }
193
194 bam_aux_append(dest, "MQ", 'i', sizeof(uint32_t), (uint8_t*)&mq);
195 }
196 // Copy mate cigar if either read is mapped
197 if ( (src->core.flag & BAM_FUNMAP) == 0 || (dest->core.flag & BAM_FUNMAP) == 0 ) {
198 uint8_t* data_mc;
199 if ((data_mc = bam_aux_get(dest,"MC")) != NULL) {
200 bam_aux_del(dest, data_mc);
201 }
202
203 // Convert cigar to string
204 kstring_t mc = { 0, 0, NULL };
205 if (bam_format_cigar(src, &mc) < 0) return -1;
206
207 bam_aux_append(dest, "MC", 'Z', ks_len(&mc)+1, (uint8_t*)ks_str(&mc));
208 free(mc.s);
209 }
210 return 0;
211 }
212
213 // Copy flags.
214 // Returns 0 on success, -1 on failure.
215 static int sync_mate(bam1_t* a, bam1_t* b)
216 {
217 sync_unmapped_pos_inner(a,b);
218 sync_unmapped_pos_inner(b,a);
219 sync_mate_inner(a,b);
220 sync_mate_inner(b,a);
221 if (sync_mq_mc(a,b) < 0) return -1;
222 if (sync_mq_mc(b,a) < 0) return -1;
223 return 0;
224 }
225
226
227 static uint32_t calc_mate_score(bam1_t *b)
228 {
229 uint32_t score = 0;
230 uint8_t *qual = bam_get_qual(b);
231 int i;
232
233 for (i = 0; i < b->core.l_qseq; i++) {
234 if (qual[i] >= MD_MIN_QUALITY) score += qual[i];
235 }
236
237 return score;
238 }
239
240
241 static int add_mate_score(bam1_t *src, bam1_t *dest)
242 {
243 uint8_t *data_ms;
244 uint32_t mate_score = calc_mate_score(src);
245
246 if ((data_ms = bam_aux_get(dest, "ms")) != NULL) {
247 bam_aux_del(dest, data_ms);
248 }
249
250 if (bam_aux_append(dest, "ms", 'i', sizeof(uint32_t), (uint8_t*)&mate_score) == -1) {
251 return -1;
252 }
253
254 return 0;
255 }
256
257 // Completely delete the CIGAR field
258 static void clear_cigar(bam1_t *b) {
259 memmove(bam_get_cigar(b), bam_get_seq(b),
260 b->data + b->l_data - bam_get_seq(b));
261 b->l_data -= 4*b->core.n_cigar;
262 b->core.n_cigar = 0;
263 }
264
265 // Trim a CIGAR field to end on reference position "end". Remaining bases
266 // are turned to soft clips.
267 static int bam_trim(bam1_t *b, hts_pos_t end) {
268 hts_pos_t pos = b->core.pos;
269 int n_cigar = b->core.n_cigar, i;
270 uint32_t new_cigar_a[1024];
271 uint32_t *new_cigar = new_cigar_a;
272 uint32_t *cigar = bam_get_cigar(b);
273
274 // Find end of alignment or end of ref
275 int op = 0, oplen = 0;
276 for (i = 0; i < n_cigar; i++) {
277 op = bam_cigar_op(cigar[i]);
278 oplen = bam_cigar_oplen(cigar[i]);
279 if (!(bam_cigar_type(op) & 2))
280 continue;
281 pos += oplen;
282 if (pos > end)
283 break;
284 }
285
286 if (i == n_cigar)
287 // looks fine already
288 return 0;
289
290 int old_i = i, j = 0;
291 // At worst we grow by 1 element (eg 100M -> 70M30S)
292 if (n_cigar-i >= 1024-1) {
293 new_cigar = malloc(4*(n_cigar-i+1));
294 if (!new_cigar)
295 return -1;
296 }
297
298 // We fill out to new_cigar from here on.
299 if (pos-oplen < end) {
300 // Partial CIGAR op? Split existing tag.
301 cigar[old_i++] = bam_cigar_gen(end - (pos-oplen), op);
302 new_cigar[j++] = bam_cigar_gen(pos-end, BAM_CSOFT_CLIP);
303 } else if (pos > end) {
304 // entirely off the chromosome; this will trigger CIGAR *, MQUAL 0
305 b->core.flag |= BAM_FUNMAP;
306 b->core.flag &= ~BAM_FPROPER_PAIR;
307 } else {
308 // CIGAR op started on the trim junction
309 new_cigar[j++] = bam_cigar_gen(oplen, BAM_CSOFT_CLIP);
310 }
311
312 // Replace trailing elements.
313 for (i++; i < n_cigar; i++) {
314 op = bam_cigar_op(cigar[i]);
315 oplen = bam_cigar_oplen(cigar[i]);
316 if (op == BAM_CHARD_CLIP) {
317 new_cigar[j++] = cigar[i];
318 } else {
319 new_cigar[j-1] =
320 bam_cigar_gen(bam_cigar_oplen(new_cigar[j-1]) + oplen,
321 BAM_CSOFT_CLIP);
322 }
323 }
324
325 // We now have cigar[0..old_i-1] for existing CIGAR
326 // and new_cigar[0..j-1] for new CIGAR trailing component.
327
328 if (old_i+j == n_cigar) {
329 // Fits and no data move needed
330 memcpy(&cigar[old_i], new_cigar, j*4);
331 } else {
332 uint8_t *seq_old = bam_get_seq(b);
333 uint8_t *aux_end = b->data + b->l_data;
334 int nshift;
335 if (old_i+j < n_cigar) {
336 // Smaller, and can move data down
337 nshift = -4*(n_cigar - (old_i+j));
338 } else {
339 // Bigger, so grow BAM and move data up
340 nshift = 4*(old_i+j - n_cigar);
341 // FIXME: make htslib's sam_realloc_bam_data public
342 if (b->l_data + nshift > b->m_data) {
343 uint8_t *new_data = realloc(b->data, b->l_data + nshift);
344 if (!new_data) {
345 if (new_cigar != new_cigar_a)
346 free(new_cigar);
347 return -1;
348 }
349 b->m_data = b->l_data + nshift;
350 if (b->data != new_data) {
351 b->data = new_data;
352 seq_old = bam_get_seq(b);
353 aux_end = b->data + b->l_data;
354 cigar = bam_get_cigar(b);
355 }
356 }
357 }
358 memmove(seq_old+nshift, seq_old, aux_end - seq_old);
359 b->l_data += nshift;
360 memcpy(&cigar[old_i], new_cigar, j*4);
361 b->core.n_cigar = old_i+j;
362 }
363
364 if (new_cigar != new_cigar_a)
365 free(new_cigar);
366
367 return 0;
368 }
369
370 // Parses a comma-separated list of "pos", "mqual", "unmap", "cigar", and "aux"
371 // keywords for the bam sanitizer.
372 int bam_sanitize_options(const char *str) {
373 int opt = 0;
374
375 while (str && *str) {
376 const char *str_start;
377 while(*str && *str == ',')
378 str++;
379
380 for (str_start = str; *str && *str != ','; str++);
381 int len = str - str_start;
382 if (strncmp(str_start, "all", 3) == 0 || *str_start == '*')
383 opt = FIX_ALL;
384 else if (strncmp(str_start, "none", 4) == 0 ||
385 strncmp(str_start, "off", 3) == 0)
386 opt = 0;
387 else if (strncmp(str_start, "on", 2) == 0)
388 // default for position sorted data
389 opt = FIX_MQUAL | FIX_UNMAP | FIX_CIGAR | FIX_AUX;
390 else if (strncmp(str_start, "pos", 3) == 0)
391 opt |= FIX_POS;
392 else if (strncmp(str_start, "mqual", 5) == 0)
393 opt |= FIX_MQUAL;
394 else if (strncmp(str_start, "unmap", 5) == 0)
395 opt |= FIX_UNMAP;
396 else if (strncmp(str_start, "cigar", 5) == 0)
397 opt |= FIX_CIGAR;
398 else if (strncmp(str_start, "aux", 3) == 0)
399 opt |= FIX_AUX;
400 else {
401 print_error("sanitize", "Unrecognised keyword %.*s\n",
402 len, str_start);
403 return -1;
404 }
405 }
406
407 return opt;
408 }
409
410 int bam_sanitize(sam_hdr_t *h, bam1_t *b, int flags) {
411 if ((flags & FIX_POS) && b->core.tid < 0) {
412 // RNAME * => pos 0. NB can break alignment chr/pos sort order
413 b->core.pos = -1;
414 if (flags & FIX_UNMAP)
415 b->core.flag |= BAM_FUNMAP;
416 }
417
418 if ((flags & FIX_CIGAR) && !(b->core.flag & BAM_FUNMAP)) {
419 // Mapped => unmapped correction
420 if (b->core.pos < 0 && (flags & FIX_UNMAP)) {
421 b->core.flag |= BAM_FUNMAP;
422 } else {
423 hts_pos_t cur_end, rlen = sam_hdr_tid2len(h, b->core.tid);
424 if (b->core.pos >= rlen && (flags & FIX_UNMAP)) {
425 b->core.flag |= BAM_FUNMAP;
426 if (flags & FIX_POS)
427 b->core.tid = b->core.pos = -1;
428 } else if ((cur_end = bam_endpos(b)) > rlen) {
429 if (bam_trim(b, rlen) < 0)
430 return -1;
431 }
432 }
433 }
434
435 if (b->core.flag & BAM_FUNMAP) {
436 // Unmapped -> cigar/qual correctoins
437 if ((flags & FIX_CIGAR) && b->core.n_cigar > 0)
438 clear_cigar(b);
439
440 if (flags & FIX_MQUAL)
441 b->core.qual = 0;
442
443 // Remove NM, MD, CG, SM tags.
444 if (flags & FIX_AUX) {
445 uint8_t *from = bam_aux_first(b);
446 uint8_t *end = b->data + b->l_data;
447 uint8_t *to = from ? from-2 : end;
448
449 #define XTAG(a) (((a)[0]<<8) + (a)[1])
450 while (from) {
451 uint8_t *next = bam_aux_next(b, from);
452 if (!next && errno != ENOENT)
453 return -1;
454
455 // Keep tag unless one of a specific set.
456 // NB "to" always points to an aux tag start, while
457 // "from" is after key.
458 from -= 2;
459 int key = (int)from[0]<<8 | from[1];
460 if (key != XTAG("NM") && key != XTAG("MD") &&
461 key != XTAG("CG") && key != XTAG("SM")) {
462 ptrdiff_t len = (next ? next-2 : end) - from;
463 if (from != to)
464 memmove(to, from, len);
465 to += len;
466 }
467 from = next;
468 }
469 b->l_data = to - b->data;
470 }
471 }
472
473 return 0;
474 }
475
476 // Look for 3 tags in one pass, for efficiencies sake.
477 // We also convert the draft tags Mm and Ml to MM and ML here.
478 static inline void find_tags(bam1_t *b,
479 char *t1, uint8_t **t1p,
480 char *t2, uint8_t **t2p,
481 char *t3, uint8_t **t3p) {
482 *t1p = *t2p = *t3p = NULL;
483 uint8_t *aux = bam_aux_first(b);
484
485 while (aux) {
486 if (aux[-2] == t1[0] && toupper(aux[-1]) == t1[1]) {
487 *t1p = aux;
488 if (islower(aux[-1]))
489 aux[-1] = t1[1];
490 } else if (aux[-2] == t2[0] && toupper(aux[-1]) == t2[1]) {
491 *t2p = aux;
492 if (islower(aux[-1]))
493 aux[-1] = t2[1];
494 } else if (aux[-2] == t3[0] && toupper(aux[-1]) == t3[1]) {
495 *t3p = aux;
496 if (islower(aux[-1]))
497 aux[-1] = t3[1];
498 }
499 aux = bam_aux_next(b, aux);
500 }
501 }
502
503 // Return 5' and 3' CIGAR hard-clip counts
504 static inline void hard_clips(bam1_t *b, int *end5, int *end3) {
505 uint32_t *cigar = bam_get_cigar(b);
506 int ncigar = b->core.n_cigar;
507 int endL = 0, endR = 0, nh = 0;
508
509 if (ncigar && bam_cigar_op(cigar[0]) == BAM_CHARD_CLIP)
510 endL = bam_cigar_oplen(cigar[0]), nh=1;
511 if (ncigar > nh && bam_cigar_op(cigar[ncigar-1]) == BAM_CHARD_CLIP)
512 endR = bam_cigar_oplen(cigar[ncigar-1]);
513
514 if (b->core.flag & BAM_FREVERSE) {
515 *end5 = endR;
516 *end3 = endL;
517 } else {
518 *end5 = endL;
519 *end3 = endR;
520 }
521 }
522
523 // Get MM, ML and MN tags, and 5' and 3' hard-clip lengths.
524 // MNi is integer copy of MN, or -1 if absent/invalid
525 void get_mod_info(bam1_t *b, uint8_t **MM, uint8_t **ML, uint8_t **MN,
526 int *MNi, int *end5, int *end3) {
527 find_tags(b, "MM", MM, "ML", ML, "MN", MN);
528 if (*MN) {
529 int save_errno = errno;
530 errno = 0;
531 *MNi = bam_aux2i(*MN);
532 if (errno == EINVAL)
533 *MNi = -1;
534 errno = save_errno;
535 } else {
536 *MNi = -1;
537 }
538
539 if (*MM)
540 hard_clips(b, end5, end3);
541 else
542 *end5 = *end3 = 0; // don't need if MM not found
543 }
544
545 typedef struct MM_state {
546 // tags found on "pre" BAM
547 uint8_t *MM, *ML, *MN;
548 } MM_state;
549
550 uint8_t *MN_enc(uint8_t *tag, uint32_t n) {
551 if (n > UINT16_MAX) {
552 tag[0] = 'I';
553 i32_to_le(n, tag+1);
554 tag += 5;
555 } else if (n > UINT8_MAX) {
556 tag[0] = 'S';
557 i16_to_le(n, tag+1);
558 tag += 3;
559 } else {
560 *tag++ = 'C';
561 *tag++ = n;
562 }
563
564 return tag;
565 }
566
567 // Trim 5'/3' bases off MM and ML tags, using a previous sequence as a guide.
568 int trim_MM(bam1_t *pre, bam1_t *cur, int end5, int end3,
569 uint8_t *MM, uint8_t *ML, uint8_t *MN) {
570 // Count number of bases
571 int counts5[16] = {0}, counts3[16] = {0};
572
573 uint8_t *seq = bam_get_seq(pre);
574 int i;
575 for (i = 0; i < end5; i++)
576 counts5[bam_seqi(seq, i)]++;
577 memcpy(counts3, counts5, 16 * sizeof(*counts3));
578 for (; i < pre->core.l_qseq - end3; i++)
579 counts3[bam_seqi(seq, i)]++;
580
581 // "p" is position in pre.
582 // "q" is position in cur.
583 // Hence move up "p" to start and copy from there to "q".
584 uint8_t *MMp, *MLp, *MMq = NULL, *MLq = NULL;
585 if (ML && ML[0] == 'B' && ML[1] == 'C') {
586 MLp = ML+6;
587 } else {
588 ML = MLp = NULL;
589 }
590 MMq = MM+1;
591 MLq = MLp;
592 for (MMp = MM+1; *MMp; ) {
593 int fundamental = seq_nt16_table[*MMp];
594 while (*MMp && *MMp != ',')
595 *MMq++ = *MMp++;
596 if (*MMp)
597 *MMq++ = *MMp++;
598
599 // Now on comma separated list for MM and BC array for ML. Skip
600 int n = 0;
601 while (*MMp != ';' && n < counts5[fundamental]) {
602 char *endptr;
603 long delta = strtol((char *)MMp, &endptr, 10);
604 if (counts5[fundamental] - n > delta) {
605 // Skip entire delta in MM and ML.
606 // Eg counts[]=10, MM=3,10 ML=<10><20> => MM=10 ML=<20>
607 n += delta+1;
608 if(ML) MLp++;
609 } else if (counts3[fundamental] > counts5[fundamental]) {
610 // Shrink delta, writing MM and ML is unchanged.
611 // Eg counts[]=3, MM=10,4 ML=<10><20> => MM=7,4 ML=<10><20>
612 char num[50];
613 int l = sprintf(num, "%ld",
614 delta - (counts5[fundamental]-n));
615 memcpy((char *)MMq, num, l);
616 MMq += l;
617 *MMq++ = *endptr;
618 n += delta+1;
619 if (ML)
620 *MLq++ = *MLp++;
621 } else {
622 // next base mod is on boundary of 3' clip point
623 break;
624 }
625
626 MMp = (uint8_t *)endptr;
627 if (*MMp != ',')
628 // error? if not ; also?
629 break;
630 MMp++;
631 }
632
633 // Copy
634 while (*MMp != ';' && n < counts3[fundamental]) {
635 char *endptr;
636 long delta = strtol((char *)MMp, &endptr, 10);
637 if (counts3[fundamental] - n > delta) {
638 // Copy entire delta in MM and ML including [,;]
639 memmove(MMq, MMp, (uint8_t *)endptr - MMp + 1);
640 MMq += (uint8_t *)endptr - MMp + 1;
641 n += delta+1;
642 if (ML)
643 *MLq++ = *MLp++;
644 } else {
645 // Next mod is into 3' cutoff, so can terminate MM/ML now
646 n = counts3[fundamental];
647 if (ML)
648 MLp++;
649 }
650
651 MMp = (uint8_t *)endptr;
652 if (*MMp != ',')
653 break;
654 MMp++;
655 }
656
657 // Skip
658 while (*MMp && *MMp != ';') {
659 while (*MMp && *MMp != ',' && *MMp != ';')
660 MMp++;
661 if (*MMp == ',')
662 MMp++;
663
664 if (ML)
665 MLp++;
666 }
667 MMq[-1] = ';'; // replaces , with ; if clipping right
668 if (*MMp)
669 MMp++;
670 }
671
672 MMp++; // skip nul
673 *MMq++ = 0;
674
675 // Adjust ML B array length
676 if (ML)
677 u32_to_le(MLq-(ML+6), ML+2);
678
679 // Move MM and ML down to include their MM:Z and ML:B bits
680 if (MM) MM-=2;
681 if (ML) ML-=2;
682
683 // Now MM/ML are start of tags, MMq/MLq are ends of edited tags,
684 // and MMp/MLp are ends of original tags. Walk through tags taking up
685 // any gaps
686 //
687 // Eg XXXXXXmmmmm--YYYlllll-ZZ (m and l are edited MM and ML tags)
688 // => XXXXXXmmmmmYYYlllllZZ
689
690 uint8_t *tag = bam_get_aux(cur), *tag_end = cur->data + cur->l_data;
691 uint8_t *to = tag;
692 while (tag && tag < tag_end) {
693 if (tag[0] == 'M' && (tag[1] == 'M' || tag[1] == 'm')) {
694 // Slow but easy
695 memmove(to, MM, MMq-MM); // length of new tag
696 to += MMq-MM;
697 tag = MMp; // size of old tag
698 } else if (tag[0] == 'M' && (tag[1] == 'L' || tag[1] == 'l')) {
699 memmove(to, ML, MLq-ML);
700 to += MLq-ML;
701 tag = MLp;
702 } else if (tag[0] == 'M' && tag[1] == 'N') {
703 tag = bam_aux_next(cur, tag+2);
704 // Skip it as we'll overwrite this later, although this
705 // does change the tag order. Instead we could do:
706 //
707 // *to++ = 'M';
708 // *to++ = 'N';
709 // to = MN_enc(to, cur->core.l_qseq);
710 } else {
711 // Want aux_skip, but it's private.
712 // So we use bam_aux_next with work-arounds. :(
713 uint8_t *from = tag;
714 tag = bam_aux_next(cur, tag+2);
715 tag = tag ? tag-2 : tag_end;
716 memmove(to, from, tag-from);
717 to += tag-from;
718 }
719 }
720 cur->l_data = to - cur->data;
721
722 return 0;
723 }
724
725 // Removes base modification tags: MM, ML and MN.
726 // This is more efficient than a series of bam_aux_remove and
727 // bam_aux_find calls, as the previous removes shuffle the tags we've
728 // previously found. However it's still not optimal.
729 void delete_mod_tags(bam1_t *b) {
730 uint8_t *tag = bam_aux_first(b), *next;
731 uint8_t *to = tag;
732 while (tag) {
733 next = bam_aux_next(b, tag);
734 if (tag[-2] == 'M' &&
735 (tag[-1] == 'M' || tag[-1] == 'm' ||
736 tag[-1] == 'L' || tag[-1] == 'l' ||
737 tag[-1] == 'N')) {
738 // Skip. Equivalent to bam_aux_remove without multiple passes
739 } else {
740 // Copy. All these +/-2s are an annoyance caused by the
741 // tag iterator pointing to the byte after the 2-letter code
742 uint8_t *end = next ? next : b->data + b->l_data + 2;
743 if (tag != to)
744 memmove(to-2, tag-2, end-tag);
745 to += end-tag;
746 }
747 tag = next;
748 }
749
750 b->l_data = (to-2) - b->data;
751 }
752
753 int validate_MM(bam1_t *b, hts_base_mod_state *state) {
754 hts_base_mod mods[10];
755 int n, pos;
756 while ((n = bam_next_basemod(b, state, mods, 10, &pos)) > 0) {
757 // bam_next_basemod will trigger MM out-of-bound checks
758 }
759 return n;
760 }
761
762 // Fix base modification tags MM, ML and MN.
763 // For supplementary-style alignments we may have hard-clipped the sequence
764 // and just duplicated the MM/ML tags. Use the primary alignment to get the
765 // clipped sequence so we can trim MM/ML accordingly.
766 //
767 // We call this first on primary reads with pre == NULL. This caches
768 // MM and ML data into MM_state.
769 //
770 // We then call it again on secondary and/or supplementary data with
771 // pre == the primary record and pass in the associated state. This then
772 // validates MM/ML/MN match, and if not adjusts them if they have hard-clips
773 // which yields consistent data.
774 //
775 // TODO: add sanity check on counts of base types and MM tag to ensure it's
776 // possible. We can do this post-trimming, so we sanitize everything.
777 //
778 // Returns 0 on success,
779 // -1 on failure
780 int fix_MM(bam1_t *pre, bam1_t *cur, MM_state *state) {
781 int end5, end3;
782 int MNi = 0; // MN of -1 is used as indicator for no valid mods
783
784 if (!pre && state) {
785 // First time we've see this name.
786 // Look for base modification tags and sanity check.
787 get_mod_info(cur, &state->MM, &state->ML, &state->MN, &MNi,
788 &end5, &end3);
789 if (!state->MM) {
790 delete_mod_tags(cur);
791 return 0;
792 }
793
794 if (!end5 && !end3 && MNi <= 0) {
795 // No MN tag, but also no clipping. Assume MM is valid
796 if (cur->core.l_qseq)
797 if (bam_aux_update_int(cur, "MN", cur->core.l_qseq) < 0)
798 return -1;
799 } else if ((end3 || end5) && cur->core.l_qseq != MNi) {
800 // We have hard clips and MN tag, but the MN tag doesn't match
801 // observed sequence length so it appears the hard-clipping
802 // happened after base-mods called without updating.
803 // Fail as this is a primary read.
804 delete_mod_tags(cur);
805 }
806 // Otherwise we assume the base modifications are correct
807
808 } else if (state) {
809 // A supplementary or secondary alignment with known primary
810 uint8_t *cur_MM = NULL, *cur_ML = NULL, *cur_MN = NULL;
811 MNi = -1;
812 get_mod_info(cur, &cur_MM, &cur_ML, &cur_MN, &MNi, &end5, &end3);
813
814 if (!cur_MM) {
815 delete_mod_tags(cur);
816 return 0;
817 }
818
819 // Does MN match seq length? If so, we believe it's already valid
820 if (MNi == cur->core.l_qseq)
821 goto validate;
822
823 // Length mismatch and/or no known length, so check vs full seq.
824 if (pre->core.l_qseq != cur->core.l_qseq + end3 + end5) {
825 delete_mod_tags(cur);
826 return 0;
827 } else if (end5 || end3) {
828 if (MNi < 0 || MNi == pre->core.l_qseq)
829 trim_MM(pre, cur, end5, end3, cur_MM, cur_ML, cur_MN);
830 } // else no hard clips so MM is already valid
831
832 // Set MN so we've validated it, provided seq isn't "*".
833 // inefficient, but minimal compared to everything else
834 if (cur->core.l_qseq)
835 if (bam_aux_update_int(cur, "MN", cur->core.l_qseq) < 0)
836 return -1;
837 }
838
839 validate:
840 ;
841
842 // Also validate MM length matches sequence length. This mirrors the
843 // logic in htslib/sam_mods.c.
844 // For now we take the inefficient approach of using bam_parse_basemod2.
845 // Inefficient, but robust.
846 hts_base_mod_state *mst = hts_base_mod_state_alloc();
847 if (!mst)
848 return -1;
849
850 enum htsLogLevel lvl = hts_get_log_level();
851 hts_set_log_level(HTS_LOG_OFF);
852 if (bam_parse_basemod(cur, mst) < 0)
853 // Maybe we want hts_log_warning still though?
854 delete_mod_tags(cur);
855 if (validate_MM(cur, mst) < 0)
856 delete_mod_tags(cur);
857 hts_set_log_level(lvl);
858 hts_base_mod_state_free(mst);
859
860 return 0;
861 }
862
863 // Ensure the b[] array is at least n.
864 // Returns 0 on success,
865 // -1 on failure
866 static int grow_b_array(bam1_t **b, int *ba, int n) {
867 if (n < *ba)
868 return 0;
869
870 bam1_t *bnew = realloc(*b, (n+=10) * sizeof(**b));
871 if (!bnew)
872 return -1;
873 *b = bnew;
874
875 // bam_init1 equivalent
876 int i;
877 for (i = *ba; i < n; i++)
878 memset(&(*b)[i], 0, sizeof(bam1_t));
879
880 *b = bnew;
881 *ba = n;
882
883 return 0;
884 }
885
886 // We have b[0]..b[bn-1] entries all from the same template (qname)
887 typedef struct {
888 bam1_t *b;
889 int n, ba; // number used and number allocated
890 int b_next; // b[b_next] for start of next set, -1 if unset
891 int eof; // marker for having seen eof
892 } bam_set;
893
894 // Fetches a new batch of BAM records all containing the same name.
895 // NB: we cache the last (non-matching) name in b[n], so we can use it to
896 // start the next batch.
897 // Returns the number of records on success,
898 // <0 on failure or EOF (sam_read1 return vals)
899 static int next_template(samFile *in, sam_hdr_t *header, bam_set *bs,
900 int sanitize_flags) {
901 int result;
902
903 if (bs->eof)
904 return -1;
905
906 // First time through, prime the template name
907 if (bs->b_next < 0) {
908 if (grow_b_array(&bs->b, &bs->ba, 1) < 0)
909 return -2;
910 result = sam_read1(in, header, &bs->b[0]);
911 if (result < 0)
912 return result;
913 if (bam_sanitize(header, &bs->b[0], sanitize_flags) < 0)
914 return -2;
915 } else {
916 // Otherwise use the previous template name read
917 bam1_t btmp = bs->b[0];
918 bs->b[0] = bs->b[bs->b_next];
919 bs->b[bs->b_next] = btmp; // For ->{,l_,m_}data
920 }
921 bs->n = 1;
922
923 // Now keep reading until we find a read that mismatches or we hit eof.
924 char *name = bam_get_qname(&bs->b[0]);
925 for (;;) {
926 if (grow_b_array(&bs->b, &bs->ba, bs->n+1) < 0)
927 return -2;
928
929 result = sam_read1(in, header, &bs->b[bs->n]);
930 if (result < -1)
931 return result;
932
933 if (result < 0) {
934 bs->eof = 1;
935 bs->b_next = -1;
936 break;
937 } else {
938 if (bam_sanitize(header, &bs->b[bs->n], sanitize_flags) < 0)
939 return -2;
940
941 bs->b_next = bs->n;
942 if (strcmp(name, bam_get_qname(&bs->b[bs->n])) != 0)
943 break;
944 }
945
946 bs->n++;
947 }
948
949 return bs->n;
950 }
951
952 // currently, this function ONLY works if each read has one hit
953 //
954 // Returns 0 on success,
955 // >0 on failure
956 static int bam_mating_core(samFile *in, samFile *out, int remove_reads,
957 int proper_pair_check, int add_ct,
958 int do_mate_scoring, char *arg_list, int no_pg,
959 int sanitize_flags, int base_mods)
960 {
961 sam_hdr_t *header;
962 int result, n;
963 kstring_t str = KS_INITIALIZE;
964 bam_set bs = {NULL, 0, 0, -1, 0};
965
966 header = sam_hdr_read(in);
967 if (header == NULL) {
968 fprintf(stderr, "[bam_mating_core] ERROR: Couldn't read header\n");
969 return 1;
970 }
971
972 // Accept unknown, unsorted, or queryname sort order, but error on coordinate sorted.
973 if (!sam_hdr_find_tag_hd(header, "SO", &str) && str.s && !strcmp(str.s, "coordinate")) {
974 fprintf(stderr, "[bam_mating_core] ERROR: Coordinate sorted, require grouped/sorted by queryname.\n");
975 goto fail;
976 }
977 ks_free(&str);
978
979 if (!no_pg && sam_hdr_add_pg(header, "samtools",
980 "VN", samtools_version(),
981 arg_list ? "CL": NULL,
982 arg_list ? arg_list : NULL,
983 NULL))
984 goto fail;
985
986 if (sam_hdr_write(out, header) < 0) goto write_fail;
987
988 // Iterate template by template fetching bs->n records at a time
989 while ((result = next_template(in, header, &bs, sanitize_flags)) >= 0) {
990 bam1_t *cur = NULL, *pre = NULL, *rnum[2] = {NULL, NULL};
991 int prev = -1, curr = -1;
992 hts_pos_t pre_end = 0, cur_end = 0;
993
994 // Find and fix up primary alignments
995 MM_state state[2];
996 for (n = 0; n < bs.n; n++) {
997 int is_r2 = (bs.b[n].core.flag & BAM_FREAD2) != 0;
998 if (bs.b[n].core.flag & (BAM_FSECONDARY | BAM_FSUPPLEMENTARY))
999 continue;
1000
1001 if (base_mods)
1002 if (fix_MM(NULL, &bs.b[n], &state[is_r2]) < 0)
1003 goto fail;
1004
1005 if (!pre) {
1006 pre = &bs.b[prev = n];
1007 rnum[(pre->core.flag & BAM_FREAD2) != 0] = pre;
1008
1009 pre_end = (pre->core.flag & BAM_FUNMAP) == 0
1010 ? bam_endpos(pre) : 0;
1011 continue;
1012 }
1013
1014 // Note, more than 2 primary alignments will use 'curr' as last
1015 cur = &bs.b[curr = n];
1016 rnum[(cur->core.flag & BAM_FREAD2) != 0] = cur;
1017 cur_end = (cur->core.flag & BAM_FUNMAP) == 0
1018 ? bam_endpos(cur) : 0;
1019
1020 pre->core.flag |= BAM_FPAIRED;
1021 cur->core.flag |= BAM_FPAIRED;
1022 if (sync_mate(pre, cur))
1023 goto fail;
1024
1025 // If safe set TLEN/ISIZE
1026 if (pre->core.tid == cur->core.tid
1027 && !(cur->core.flag & (BAM_FUNMAP | BAM_FMUNMAP))
1028 && !(pre->core.flag & (BAM_FUNMAP | BAM_FMUNMAP))) {
1029 hts_pos_t cur5, pre5;
1030 cur5 = (cur->core.flag & BAM_FREVERSE)
1031 ? cur_end
1032 : cur->core.pos;
1033 pre5 = (pre->core.flag & BAM_FREVERSE)
1034 ? pre_end
1035 : pre->core.pos;
1036 cur->core.isize = pre5 - cur5;
1037 pre->core.isize = cur5 - pre5;
1038 } else {
1039 cur->core.isize = pre->core.isize = 0;
1040 }
1041
1042 if (add_ct)
1043 bam_template_cigar(pre, cur, &str);
1044
1045 // TODO: Add code to properly check if read is in a proper
1046 // pair based on ISIZE distribution
1047 if (proper_pair_check && !plausibly_properly_paired(pre,cur)) {
1048 pre->core.flag &= ~BAM_FPROPER_PAIR;
1049 cur->core.flag &= ~BAM_FPROPER_PAIR;
1050 }
1051
1052 if (do_mate_scoring) {
1053 if ((add_mate_score(pre, cur) == -1) ||
1054 (add_mate_score(cur, pre) == -1)) {
1055 fprintf(stderr, "[bam_mating_core] ERROR: "
1056 "unable to add mate score.\n");
1057 goto fail;
1058 }
1059 }
1060
1061 // If we have to remove reads make sure we do it in a way that
1062 // doesn't create orphans with bad flags
1063 if (remove_reads) {
1064 if (pre->core.flag&BAM_FUNMAP)
1065 cur->core.flag &=
1066 ~(BAM_FMREVERSE|BAM_FPROPER_PAIR);
1067 if (cur->core.flag&BAM_FUNMAP)
1068 pre->core.flag &=
1069 ~(BAM_FMREVERSE|BAM_FPROPER_PAIR);
1070 }
1071 }
1072
1073 // Handle unpaired primary data
1074 if (!cur && pre) {
1075 pre->core.mtid = -1;
1076 pre->core.mpos = -1;
1077 pre->core.isize = 0;
1078 pre->core.flag &= ~(BAM_FMREVERSE|BAM_FPROPER_PAIR);
1079 }
1080
1081 // Now process secondary and supplementary alignments
1082 for (n = 0; n < bs.n; n++) {
1083 if (!(bs.b[n].core.flag & (BAM_FSECONDARY|BAM_FSUPPLEMENTARY))) {
1084 // primary
1085 continue;
1086 }
1087
1088 // Secondary or supplementary
1089 int is_r2 = (bs.b[n].core.flag & BAM_FREAD2) != 0;
1090 bam1_t *primary = rnum[is_r2];
1091 if (primary) {
1092 if (base_mods)
1093 fix_MM(primary, &bs.b[n], &state[is_r2]);
1094 } else {
1095 // Record with base modifications but no known primary
1096 //fprintf(stderr, "Unpaired secondary or supplementary\n");
1097 if (base_mods)
1098 fix_MM(NULL, &bs.b[n], NULL);
1099 }
1100 }
1101
1102 // Finally having curated everything, write out all records in their
1103 // original ordering
1104 for (n = 0; n < bs.n; n++) {
1105 bam1_t *cur = &bs.b[n];
1106 // We may remove unmapped and secondary alignments
1107 if (remove_reads && (cur->core.flag & (BAM_FSECONDARY|BAM_FUNMAP)))
1108 continue;
1109
1110 if (sam_write1(out, header, cur) < 0)
1111 goto write_fail;
1112 }
1113 }
1114 if (result < -1)
1115 goto read_fail;
1116
1117 sam_hdr_destroy(header);
1118
1119 for (n = 0; n < bs.ba; n++)
1120 free(bs.b[n].data);
1121 free(bs.b);
1122 ks_free(&str);
1123 return 0;
1124
1125 read_fail:
1126 print_error("fixmate", "Couldn't read from input file");
1127 goto fail;
1128
1129 write_fail:
1130 print_error_errno("fixmate", "Couldn't write to output file");
1131 fail:
1132 sam_hdr_destroy(header);
1133 for (n = 0; n < bs.ba; n++)
1134 free(bs.b[n].data);
1135 free(bs.b);
1136 ks_free(&str);
1137 return 1;
1138 }
1139
1140 void usage(FILE* where)
1141 {
1142 fprintf(where,
1143 "Usage: samtools fixmate <in.nameSrt.bam> <out.nameSrt.bam>\n"
1144 "Options:\n"
1145 " -r Remove unmapped reads and secondary alignments\n"
1146 " -p Disable FR proper pair check\n"
1147 " -c Add template cigar ct tag\n"
1148 " -m Add mate score tag\n"
1149 " -u Uncompressed output\n"
1150 " -z, --sanitize FLAG[,FLAG]\n"
1151 " Sanitize alignment fields [defaults to all types]\n"
1152 " -M Fix base modification tags (MM/ML/MN)\n"
1153 " --no-PG do not add a PG line\n");
1154
1155 sam_global_opt_help(where, "-.O..@-.");
1156
1157 fprintf(where,
1158 "\n"
1159 "As elsewhere in samtools, use '-' as the filename for stdin/stdout. The input\n"
1160 "file must be grouped by read name (e.g. sorted by name). Coordinated sorted\n"
1161 "input is not accepted.\n");
1162 }
1163
1164 int bam_mating(int argc, char *argv[])
1165 {
1166 htsThreadPool p = {NULL, 0};
1167 samFile *in = NULL, *out = NULL;
1168 int c, remove_reads = 0, proper_pair_check = 1, add_ct = 0, res = 1,
1169 mate_score = 0, no_pg = 0, sanitize_flags = FIX_ALL, base_mods = 0;
1170 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
1171 char wmode[4] = {'w', 'b', 0, 0};
1172 static const struct option lopts[] = {
1173 SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
1174 {"no-PG", no_argument, NULL, 1},
1175 { NULL, 0, NULL, 0 }
1176 };
1177 char *arg_list = NULL;
1178
1179 // parse args
1180 if (argc == 1) { usage(stdout); return 0; }
1181 while ((c = getopt_long(argc, argv, "rpcmMO:@:uz:", lopts, NULL)) >= 0) {
1182 switch (c) {
1183 case 'r': remove_reads = 1; break;
1184 case 'p': proper_pair_check = 0; break;
1185 case 'c': add_ct = 1; break;
1186 case 'm': mate_score = 1; break;
1187 case 'M': base_mods = 1; break;
1188 case 'u': wmode[2] = '0'; break;
1189 case 1: no_pg = 1; break;
1190 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
1191 /* else fall-through */
1192 case '?': usage(stderr); goto fail;
1193 case 'z':
1194 if ((sanitize_flags = bam_sanitize_options(optarg)) < 0)
1195 exit(1);
1196 break;
1197 }
1198 }
1199 if (optind+1 >= argc) { usage(stderr); goto fail; }
1200
1201 if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1)))
1202 goto fail;
1203
1204 // init
1205 if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) {
1206 print_error_errno("fixmate", "cannot open input file");
1207 goto fail;
1208 }
1209 sam_open_mode(wmode+1, argv[optind+1], NULL);
1210 if ((out = sam_open_format(argv[optind+1], wmode, &ga.out)) == NULL) {
1211 print_error_errno("fixmate", "cannot open output file");
1212 goto fail;
1213 }
1214
1215 if (ga.nthreads > 0) {
1216 if (!(p.pool = hts_tpool_init(ga.nthreads))) {
1217 fprintf(stderr, "Error creating thread pool\n");
1218 goto fail;
1219 }
1220 hts_set_opt(in, HTS_OPT_THREAD_POOL, &p);
1221 hts_set_opt(out, HTS_OPT_THREAD_POOL, &p);
1222 }
1223
1224 // run
1225 res = bam_mating_core(in, out, remove_reads, proper_pair_check, add_ct,
1226 mate_score, arg_list, no_pg, sanitize_flags,
1227 base_mods);
1228
1229 // cleanup
1230 sam_close(in);
1231 if (sam_close(out) < 0) {
1232 fprintf(stderr, "[bam_mating] error while closing output file\n");
1233 res = 1;
1234 }
1235
1236 if (p.pool) hts_tpool_destroy(p.pool);
1237 free(arg_list);
1238 sam_global_args_free(&ga);
1239 return res;
1240
1241 fail:
1242 if (in) sam_close(in);
1243 if (out) sam_close(out);
1244 if (p.pool) hts_tpool_destroy(p.pool);
1245 free(arg_list);
1246 sam_global_args_free(&ga);
1247 return 1;
1248 }
1249
1250