Debian Codegraph @

samtools/bam_mate.c.pysam.c

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