-
Notifications
You must be signed in to change notification settings - Fork 3
/
bam2bam.c
2309 lines (2045 loc) · 89 KB
/
bam2bam.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Combine aln, samse, sampe into one workflow. We steal the workhorse
* functions from the other subprograms, then wrap them in new top-level
* functions. Comes with a command line that combines all the other
* options, maybe even some more.
*/
static const int chunksize = 0x100000;
static const int loudness = 0;
static const int ring_size = 0x80000;
static const int timeout = 90;
#include "bamlite.h"
#include "bwtaln.h"
#include "bwase.h"
#include "bwape.h"
#include "khash.h"
#include "main.h"
#include "bgzf.h"
#include "utils.h"
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/utsname.h>
#include <zmq.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <zlib.h>
static const int the_hwm = 64;
static const int the_linger = 2000;
KHASH_MAP_INIT_INT64(64, poslist_t)
struct option longopts[] = {
{ "num-diff", 1, 0, 'n' },
{ "max-gap-open", 1, 0, 'o' },
{ "max-gap-extensions", 1, 0, 'e' },
{ "indel-near-end", 1, 0, 'i' },
{ "deletion-occurences", 1, 0, 'd' },
{ "seed-length", 1, 0, 'l' },
{ "seed-mismatches", 1, 0, 'k' },
{ "queue-size", 1, 0, 'm' },
{ "num-threads", 1, 0, 't' },
{ "mismatch-penalty", 1, 0, 'M' },
{ "gap-open-penalty", 1, 0, 'O' },
{ "gap-extension-penalty", 1, 0, 'E' },
{ "max-best-hits", 1, 0, 'R' },
{ "trim-quality", 1, 0, 'q' },
{ "log-gap-penalty", 0, 0, 'L' },
{ "non-iterative", 0, 0, 'N' },
{ "barcode-length", 1, 0, 'B' },
{ "output", 1, 0, 'f' },
{ "only-aligned", 0, 0, 128 },
{ "drop-aligned", 0, 0, 133 },
{ "debug-bam", 0, 0, 129 },
{ "broken-input", 0, 0, 130 },
{ "skip-duplicates", 0, 0, 131 },
{ "temp-dir", 1, 0, 132 },
{ "max-insert-size", 1, 0, 'a' },
{ "max-occurences", 1, 0, 'C' },
{ "max-occurences-se", 1, 0, 'D' },
{ "max-hits", 1, 0, 'h' },
{ "max-discordant-hits", 1, 0, 'H' },
{ "chimeric-rate", 1, 0, 'c' },
{ "disable-sw", 1, 0, 's' },
{ "disable-isize-estimate", 1, 0, 'A' },
{ "listen-port", 1, 0, 'p' },
{ 0,0,0,0 }
} ;
struct option workeropts[] = {
{ "num-threads", 1, 0, 't' },
{ "host", 1, 0, 'h' },
{ "port", 1, 0, 'p' },
{ "timeout", 1, 0, 'T' },
{ 0,0,0,0 }
} ;
// Yes, global variables. Not very nice, but we'll only load one genome
// and passing it everywhere gets old after a while.
static bwt_t *bwt[2] = {0,0};
static bntseq_t *bns = 0;
static bntseq_t *ntbns = 0;
static ubyte_t *pac = 0;
static bwtint_t genome_length = 0;
static gap_opt_t *gap_opt = 0;
static pe_opt_t *pe_opt = 0;
static int only_aligned = 0;
static int debug_bam = 0;
static int broken_input = 0;
static int drop_aligned = 0;
static int max_run_time = 90;
static int skip_duplicates = 0;
static void *zmq_context = 0;
static int listen_port = 0;
static isize_info_t null_ii = {0} ;
static khash_t(isize_infos) * volatile g_iinfos = 0;
static uint8_t revcom1[256] ;
static void init_revcom1()
{
int i,j;
for(i=0 ; i!=256; ++i)
{
j=0 ;
if(i&0x1) j|=0x80 ;
if(i&0x2) j|=0x40 ;
if(i&0x4) j|=0x20 ;
if(i&0x8) j|=0x10 ;
if(i&0x10) j|=0x8 ;
if(i&0x20) j|=0x4 ;
if(i&0x40) j|=0x2 ;
if(i&0x80) j|=0x1 ;
revcom1[i] = j ;
}
}
static volatile int s_interrupted = 0;
static void s_signal_handler (int signal_value)
{
s_interrupted = 1;
}
static void s_catch_signals (void)
{
struct sigaction action;
action.sa_handler = s_signal_handler;
action.sa_flags = 0;
sigemptyset (&action.sa_mask);
sigaction (SIGINT, &action, NULL);
sigaction (SIGTERM, &action, NULL);
}
int zcheck_at( int rc, int testterm, int status, const char *label, int line, char *format, ... )
{
va_list ap;
if (rc != -1) return 0;
if (testterm && (zmq_errno() == ETERM || zmq_errno() == EINTR)) return 1;
fprintf( stderr, "[%s:%d] ", label, line );
va_start(ap,format);
vfprintf( stderr, format, ap );
va_end(ap);
fprintf( stderr, "%s%s\n", zmq_errno()?": ":"", zmq_strerror(zmq_errno()) );
if (status) exit(status) ;
return 0;
}
#define zcheck(rc, status, ...) (void)zcheck_at(rc,0,status,__FUNCTION__,__LINE__,__VA_ARGS__)
#define zterm(rc, status, ...) if(zcheck_at(rc,1,status,__FUNCTION__,__LINE__,__VA_ARGS__))
// We take the old header, remove the lines we generate ourselves, and
// incorporate the rest verbatim. More specifically, HD is added, PG is added
// and linked to the previous one using PG-PP, SQ and HD lines are removed.
int32_t bwa_print_header_text( char* buf, int32_t len, bntseq_t *bns,
const char* oldhdr, const char *pptag, const char* myid, int argc, char *argv[], char *version )
{
int i;
int32_t c = snprintf( buf, len, "@HD\tVN:1.4\n@PG\tID:%s%s%s\tPN:bwa\tVN:%s%s",
myid, pptag?"\tPP:":"", pptag?pptag:"", version,
argc?"\tCL:":"" );
for (i = 0; i < argc ; ++i)
c += snprintf( buf+c, len>c?len-c:0, "%s%c", argv[i], i==argc-1?'\n':' ' );
for (i = 0; i < bns->n_seqs; ++i)
c += snprintf( buf+c, len>c?len-c:0, "@SQ\tSN:%s\tLN:%d\n", bns->anns[i].name, bns->anns[i].len);
while (*oldhdr) {
// check for an interesting header: HD and SQ are uninteresting
int interesting = 1 ;
if( oldhdr[0] == '@' && oldhdr[1] && oldhdr[2] ) {
if( oldhdr[1] == 'S' && oldhdr[2] == 'Q' ) interesting = 0 ;
if( oldhdr[1] == 'H' && oldhdr[2] == 'D' ) interesting = 0 ;
}
// scan old header, copy only interesting lines
while( *oldhdr && *oldhdr != '\n' ) {
if( interesting ) {
if( c < len ) buf[c] = *oldhdr ;
++c;
}
++oldhdr;
}
if( interesting ) {
if( c < len ) buf[c] = '\n' ;
++c;
}
if( *oldhdr ) ++oldhdr;
}
return c;
}
KHASH_SET_INIT_STR(words)
// Generate useful program id and pp-tag. We scan the PG lines of the
// header looking for one that is present and not linked to (the first
// one is fine, there should be only one). Then we try our program id
// ("bwa"), and if that's already present, we append numbers until it
// isn't anymore.
//
// Returns two strings in (*pp) and (*id), both of which must be
// free()d.
void find_pp_tag( const char* h, char** pp, char** id )
{
const char *he, *k ;
int r, n;
khint_t iter;
kh_words_t *present = kh_init_words() ;
kh_words_t *linked = kh_init_words() ;
*pp=0;
while( *h ) {
if( h[0] == '@' && h[1] == 'P' && h[2] == 'G' ) {
while( *h && *h != '\n' ) {
if( ( (h[0] == 'I' && h[1] == 'D')
|| (h[0] == 'P' && h[1] == 'P') )
&& h[2] == ':' )
{
h += 3 ;
he = h ;
while( *he && *he != '\n' && *he != '\t' ) ++he ;
k = strndup(h, he-h) ;
kh_put_words(h[-3]=='I' ? present : linked, k, &r) ;
h=he ;
}
while( *h && *h != '\n' && *h != '\t' ) ++h ;
if( *h == '\t' ) ++h ;
}
}
while( *h && *h != '\n' ) ++h ;
if( *h ) ++h ;
}
for (iter = kh_begin(present); iter != kh_end(present); ++iter) {
if (kh_exist(present, iter)) {
khint_t j = kh_get(words, linked, kh_key(present, iter)) ;
if( j == kh_end(linked) || !kh_exist(linked,j) ) {
*pp = strdup( kh_key(present, iter) ) ;
break ;
}
}
}
char myid[50] = "bwa" ;
for( n = 1; 1 ; ++n ) {
khint_t j = kh_get(words, present, myid) ;
if( j == kh_end(present) || !kh_exist(present,j) ) {
*id = strdup( myid ) ;
break ;
}
snprintf( myid, 50, "bwa-%d", n ) ;
}
for (iter = kh_begin(linked); iter != kh_end(linked); ++iter)
if (kh_exist(linked, iter))
free((void*)kh_key(linked,iter)) ;
for (iter = kh_begin(present); iter != kh_end(present); ++iter)
if (kh_exist(present, iter))
free((void*)kh_key(present,iter)) ;
kh_destroy_words( linked ) ;
kh_destroy_words( present ) ;
}
int bwa_print_bam_header( BGZF* output, bntseq_t *bns,
char* oldhdr, int argc, char *argv[],
char* version)
{
#define DO(x) if(r>=0) { int r1 = x; if(r1>=0) r+=r1; else r=r1; } else {}
int i, r=0;
char magic[4] = { 'B', 'A', 'M', 1 } ;
char *pptag, *myid ;
find_pp_tag( oldhdr, &pptag, &myid ) ;
int32_t h_len = bwa_print_header_text( 0, 0, bns, oldhdr, pptag, myid, argc, argv, version );
char *buf = malloc( h_len+1 ) ;
bwa_print_header_text( buf, h_len+1, bns, oldhdr, pptag, myid, argc, argv, version );
DO( bgzf_write( output, magic, 4 ) ) ;
DO( bgzf_write( output, &h_len, 4 ) ) ;
DO( bgzf_write( output, buf, h_len ) ) ;
DO( bgzf_write( output, &bns->n_seqs, 4 ) ) ;
for (i = 0; i < bns->n_seqs; ++i)
{
int32_t nlen = 1+strlen( bns->anns[i].name ) ;
DO( bgzf_write( output, &nlen, 4 ) ) ;
DO( bgzf_write( output, bns->anns[i].name, nlen ) ) ;
DO( bgzf_write( output, &bns->anns[i].len, 4 ) ) ;
}
free(buf) ;
free(pptag) ;
free(myid) ;
return r ;
}
int bwa_print_bam1( BGZF* output, bam1_t *b )
{
uint32_t blocksize = sizeof(bam1_core_t) + b->data_len ;
uint32_t y = (int)b->core.bin << 16 | (int)b->core.qual << 8 | (int)b->core.l_qname;
uint32_t z = (int)b->core.flag << 16 | (int)b->core.n_cigar;
int r = bgzf_write( output, &blocksize, 4);
DO( bgzf_write( output, &b->core.tid, 4));
DO( bgzf_write( output, &b->core.pos, 4));
DO( bgzf_write( output, &y, 4 ));
DO( bgzf_write( output, &z, 4 ));
DO( bgzf_write( output, &b->core.l_qseq, 4));
DO( bgzf_write( output, &b->core.mtid, 4));
DO( bgzf_write( output, &b->core.mpos, 4));
DO( bgzf_write( output, &b->core.isize, 4));
DO( bgzf_write( output, b->data, b->data_len));
return r;
}
#undef DO
static inline int bam_reg2bin(uint32_t beg, uint32_t end)
{
--end;
if (beg>>14 == end>>14) return 4681 + (beg>>14);
if (beg>>17 == end>>17) return 585 + (beg>>17);
if (beg>>20 == end>>20) return 73 + (beg>>20);
if (beg>>23 == end>>23) return 9 + (beg>>23);
if (beg>>26 == end>>26) return 1 + (beg>>26);
return 0;
}
static void revcom_bam1( bam1_t *b )
{
uint8_t *p,*q;
// flip flag
b->core.flag ^= SAM_FSR;
// revcom sequence (incl. up to one nybble of padding)
for(p=bam1_seq(b), q=bam1_seq(b) + (b->core.l_qseq+1) / 2 - 1; p<q ; ++p,--q)
{
uint8_t x = *q ; *q = revcom1[*p] ; *p = revcom1[x] ;
}
if(p==q) *p = revcom1[*q] ;
// shift by one nybble if necessary
if(b->core.l_qseq & 1) {
for(p=bam1_seq(b), q=bam1_seq(b) + (b->core.l_qseq+1) / 2 - 1; p<q ; ++p)
*p = (p[0] & 0xf) << 4 | (p[1] & 0xf0) >> 4 ;
*p = (p[0] & 0xf) << 4 ;
}
// reverse quality
for(p=bam1_qual(b), q=bam1_qual(b) + b->core.l_qseq -1; p<q ; ++p,--q)
{
uint8_t x = *q ; *q = *p ; *p = x ;
}
}
// Make room for at least n more bytes.
static void bam_realloc( int n, bam1_t *b )
{
if( b->m_data - b->data_len < n ) {
b->m_data = b->data_len+n ;
kroundup32(b->m_data) ;
b->data = realloc( b->data, b->m_data ) ;
}
}
// Add a tag with an int content. Right now, always encode as unsigned
// int, need to add the other tags if time permits.
static void bam_push_int( bam1_t *b, char u, char v, int x )
{
bam_realloc( 7, b );
b->data[b->data_len + 0] = u;
b->data[b->data_len + 1] = v;
b->data[b->data_len + 2] = 'i';
*(uint32_t*)(b->data + b->data_len + 3) = x;
b->data_len += 7;
}
static void bam_push_char( bam1_t *b, char u, char v, char c )
{
bam_realloc( 4, b );
b->data[b->data_len + 0] = u;
b->data[b->data_len + 1] = v;
b->data[b->data_len + 2] = 'A';
b->data[b->data_len + 3] = c;
b->data_len += 4;
}
static void bam_push_string( bam1_t *b, char u, char v, char *s )
{
int len = strlen(s) ;
bam_realloc( 4+len, b );
b->data[b->data_len + 0] = u;
b->data[b->data_len + 1] = v;
b->data[b->data_len + 2] = 'Z';
strcpy((char*)b->data + b->data_len + 3, s) ;
b->data_len += 4+len;
}
static void bam_resize_cigar( bam1_t *b, int n_cigar )
{
bam_realloc( 4*(n_cigar - b->core.n_cigar), b ) ;
memmove( bam1_cigar(b) + n_cigar, bam1_cigar(b) + b->core.n_cigar,
(b->data + b->data_len) - (uint8_t*)(bam1_cigar(b) + b->core.n_cigar) ) ;
b->data_len += 4*(n_cigar - b->core.n_cigar) ;
b->core.n_cigar = n_cigar ;
}
// The old record must be cleaned (remove the alignment), then the new
// alignment gets spliced in. Alignment related tagged fields must also be
// overwritten or removed. Specifically:
//
// - refID, pos, bin, mapq must be set
// - next_refID, next_pos, tlen must be set
// - cigar must be generated or cleared
// - seq/qual may need to be reverse-complemented
// - some flags must be cleared: proper pair, unmapped, mate unmapped,
// reversed, mate reversed, secondary alignment
// - tags must be copied, but those we generate must be removed and
// regenerated: XC, NM, XN, SM, AM, X0, X1, XM, XO, XG, XA, YQ, XT, MD
void bwa_update_bam1(bam1_t *out, const bntseq_t *bns, bwa_seq_t *p, const bwa_seq_t *mate, int mode, int max_top2)
{
if (p->clip_len < p->full_len) bam_push_int( out, 'X', 'C', p->clip_len );
if (p->max_entries && debug_bam) bam_push_int( out, 'Y', 'Q', p->max_entries );
if (p->type != BWA_TYPE_NO_MATCH || (mate && mate->type != BWA_TYPE_NO_MATCH)) {
int seqid, am = 0, nn, j;
if (p->type == BWA_TYPE_NO_MATCH) {
p->pos = mate->pos;
p->strand = mate->strand;
p->extra_flag |= SAM_FSU;
j = 1;
} else j = pos_end(p) - p->pos; // j is the length of the reference in the alignment
// reversed now but originally wasn't or not reversed now but was originally?
// Note that this also inverts SAM_FSR if necessary,
if (p->strand != ((out->core.flag & SAM_FSR) != 0) ) revcom_bam1( out ) ;
out->core.flag &= ~( SAM_FPP | SAM_FSU | SAM_FMU | SAM_FSC | SAM_FMR ) ;
out->core.flag |= p->extra_flag;
// get seqid
nn = bns_coor_pac2real(bns, p->pos, j, &seqid);
if (p->type != BWA_TYPE_NO_MATCH && p->pos + j - bns->anns[seqid].offset > bns->anns[seqid].len)
{
out->core.flag |= SAM_FSU; // flag UNMAP and not PROPERLY PAIRED as this alignment
out->core.flag &= ~SAM_FPP; // bridges two adjacent reference sequences
p->mapQ = 0;
}
// update other flags in output record
out->core.tid = seqid ;
out->core.pos = p->pos - bns->anns[seqid].offset ;
out->core.bin = bam_reg2bin( p->pos - bns->anns[seqid].offset, pos_end(p) - bns->anns[seqid].offset ) ;
out->core.qual = p->mapQ ;
if (p->cigar) {
bam_resize_cigar( out, p->n_cigar ) ;
for (j = 0; j != p->n_cigar; ++j)
bam1_cigar(out)[j] = __cigar_len(p->cigar[j]) << 4 | "\000\001\002\004"[__cigar_op(p->cigar[j])] ;
} else if (p->type == BWA_TYPE_NO_MATCH) {
bam_resize_cigar( out, 0 ) ;
} else {
bam_resize_cigar( out, 1 ) ;
*bam1_cigar(out) = p->len << 4 ;
}
if (mate && mate->type != BWA_TYPE_NO_MATCH) {
int m_seqid, m_j;
am = mate->seQ < p->seQ? mate->seQ : p->seQ; // smaller single-end mapping quality
// redundant calculation here, but should not matter too much
// also, add up the nn values so self and mate get the same
// XN field
nn += bns_coor_pac2real(bns, mate->pos, mate->len, &m_seqid);
m_j = pos_end(mate) - mate->pos; // m_j is the length of the reference in the alignment
if( mate->pos + m_j - bns->anns[m_seqid].offset > bns->anns[m_seqid].len ) {
out->core.flag |= SAM_FMU; // flag MUNMAP and not PROPERLY PAIRED as the mate's alignment
out->core.flag &= ~SAM_FPP; // bridges two adjacent reference sequences
}
if (mate->strand) out->core.flag |= SAM_FMR;
out->core.mtid = m_seqid ;
out->core.mpos = mate->pos - bns->anns[m_seqid].offset ;
if (p->type == BWA_TYPE_NO_MATCH) out->core.isize = 0;
else out->core.isize = (seqid == m_seqid)? pos_5(mate) - pos_5(p) : 0;
} else if (mate) {
out->core.flag |= SAM_FMU;
out->core.flag &= ~SAM_FPP;
out->core.mtid = seqid ;
out->core.mpos = p->pos - bns->anns[seqid].offset ;
out->core.isize = 0;
} else {
out->core.mtid = -1 ;
out->core.mpos = -1 ;
out->core.isize = 0;
}
if (p->type != BWA_TYPE_NO_MATCH) {
int i;
// calculate XT tag
char XT = "NURM"[p->type];
if (nn > 10) XT = 'N';
// print tags
bam_push_char( out, 'X', 'T', XT ) ;
if( mode & BWA_MODE_COMPREAD ) bam_push_int( out, 'N', 'M', p->nm ) ;
else bam_push_int( out, 'C', 'M', p->nm ) ;
if (nn) bam_push_int( out, 'X', 'N', nn ) ;
if (mate) {
bam_push_int( out, 'S', 'M', p->seQ ) ;
bam_push_int( out, 'A', 'M', am ) ;
}
if (p->type != BWA_TYPE_MATESW) { // X0 and X1 are not available for this type of alignment
bam_push_int( out, 'X', '0', p->c1 ) ;
if (p->c1 <= max_top2)
bam_push_int( out, 'X', '1', p->c2 ) ;
}
bam_push_int( out, 'X', 'M', p->n_mm ) ;
bam_push_int( out, 'X', 'O', p->n_gapo ) ;
bam_push_int( out, 'X', 'G', p->n_gapo+p->n_gape ) ;
if (p->md) bam_push_string( out, 'M', 'D', p->md ) ;
// print multiple hits
if (p->n_multi) for(;;) {
char* outp = (char*)out->data + out->data_len ;
char* pe = (char*)out->data + out->m_data ;
#define mysnprintf(...) outp+=snprintf(outp,pe>outp?pe-outp:0,__VA_ARGS__)
mysnprintf("XAZ");
for (i = 0; i < p->n_multi; ++i) {
bwt_multi1_t *q = p->multi + i;
int k;
j = pos_end_multi(q, p->len) - q->pos;
bns_coor_pac2real(bns, q->pos, j, &seqid);
mysnprintf("%s,%c%d,", bns->anns[seqid].name, q->strand? '-' : '+',
(int)(q->pos - bns->anns[seqid].offset + 1));
if (q->cigar) {
for (k = 0; k < q->n_cigar; ++k)
mysnprintf("%d%c", __cigar_len(q->cigar[k]), "MIDS"[__cigar_op(q->cigar[k])]);
} else mysnprintf("%dM", p->len);
mysnprintf(",%d;", q->gap + q->mm);
}
if(outp<pe) *outp=0;
outp++;
#undef mysnprintf
if(outp<=pe) {
out->data_len = outp - (char*)out->data;
break;
}
out->m_data = outp - (char*)out->data;
kroundup32(out->m_data) ;
out->data = realloc( out->data, out->m_data ) ;
}
}
} else { // this read has no match
out->core.tid = -1 ;
out->core.pos = -1 ;
out->core.bin = 0 ;
out->core.qual = 0 ;
out->core.mtid = -1 ;
out->core.mpos = -1 ;
out->core.isize = 0 ;
out->core.flag &= ~( SAM_FPP | SAM_FMU | SAM_FSC ) ;
out->core.flag |= SAM_FSU ;
if (mate && mate->type == BWA_TYPE_NO_MATCH) out->core.flag |= SAM_FMU;
bam_resize_cigar( out, 0 ) ;
// if the mate has an XN tag, we need to reproduce it here
if (mate && mate->type != BWA_TYPE_NO_MATCH) {
int m_seqid, nn ;
nn = bns_coor_pac2real(bns, mate->pos, mate->len, &m_seqid);
if (nn) bam_push_int( out, 'X', 'N', nn ) ;
}
}
}
static int unique(bam_pair_t *p)
{
if( skip_duplicates ) {
switch (p->kind) {
case eof_marker: return 0;
case singleton: return !(p->bam_rec[0].core.flag & SAM_FDP) ;
case proper_pair: return !(p->bam_rec[0].core.flag & SAM_FDP)
&& !(p->bam_rec[1].core.flag & SAM_FDP) ;
}
}
return 1;
}
static void aln_singleton( bam_pair_t *raw )
{
// If we already have alignments (could come from sai file or
// because the firs phase has already run), we skip the alignment.
// (This point shouldn't actually be reached in that case.)
if(raw->phase == pristine) {
if(unique(raw)) {
bam1_to_seq(&raw->bam_rec[0], &raw->bwa_seq[0], 1, gap_opt->trim_qual);
bwa_cal_sa_reg_gap(bwt, 1, &raw->bwa_seq[0], gap_opt);
}
raw->phase = aligned ;
}
}
static void posn_singleton( bam_pair_t *raw )
{
int j ;
if( raw->phase == aligned ) {
if(unique(raw)) {
// from bwa_sai2sam_se_core
bwa_seq_t *p = &raw->bwa_seq[0] ;
bwa_aln2seq_core(p->n_aln, p->aln, p, 1, pe_opt->max_occ_se );
// from bwa_cal_pac_pos
bwa_cal_pac_pos_core(bwt[0], bwt[1], p, gap_opt->max_diff, gap_opt->fnr);
for (j = 0; j < p->n_multi; ++j) {
bwt_multi1_t *q = raw->bwa_seq[0].multi + j;
if (q->strand) q->pos = bwt_sa(bwt[0], q->pos);
else q->pos = bwt[1]->seq_len - (bwt_sa(bwt[1], q->pos) + p->len);
}
}
raw->phase = positioned ;
}
}
static void finish_singleton( bam_pair_t *raw )
{
if( raw->phase == positioned ) {
if(unique(raw)) {
bwa_seq_t *p = &raw->bwa_seq[0] ;
if( !p->seq ) bam1_to_seq(&raw->bam_rec[0], p, 1, gap_opt->trim_qual);
bwa_refine_gapped(bns, 1, p, pac, ntbns);
bwa_update_bam1(&raw->bam_rec[0], bns, p, 0, gap_opt->mode, gap_opt->max_top2);
bwa_free_read_seq1(p);
}
raw->phase = finished ;
}
}
// First stage of paired end alignment: this computes the arrays 'aln1'
// and 'aln2', the two positions, strands and single map qualities.
// pos, strand, mapQ are stored directly into the bam record.
static void aln_pair( bam_pair_t *raw )
{
int j ;
if( raw->phase == pristine ) {
if(unique(raw)) {
for( j = 0 ; j != 2 ; ++j ) {
bam1_to_seq(&raw->bam_rec[j], &raw->bwa_seq[j], 1, gap_opt->trim_qual);
// BEGIN from bwa_sai2sam_pe_core
// BEGIN from bwa_cal_pac_pos_pe
// note that seqs is not an array of two arrays anymore!!
// also note that we don't track this
// cnt_chg... whatever it was good
// for.
// cnt_chg = bwa_cal_pac_pos_pe(seqs, &ii, &last_ii);
bwa_cal_sa_reg_gap(bwt, 1, &raw->bwa_seq[j], gap_opt);
}
}
raw->phase = aligned ;
}
}
static void posn_pair( bam_pair_t *raw )
{
int j ;
if( raw->phase == aligned ) {
if(unique(raw)) {
for( j = 0 ; j != 2 ; ++j ) {
// SE part. Almost, but not quite the
// same as for singletons. (*sigh*)
raw->bwa_seq[j].n_multi = 0 ;
// generate SE alignment and mapping quality
bwa_aln2seq(raw->bwa_seq[j].n_aln, raw->bwa_seq[j].aln, &raw->bwa_seq[j]);
// Computes pos, seQ, mapQ. need to store only those to avoid
// repeated computation!
bwa_cal_pac_pos_core(bwt[0], bwt[1], &raw->bwa_seq[j], gap_opt->max_diff, gap_opt->fnr);
}
}
raw->phase = positioned ;
}
}
static void finish_pair(
bam_pair_t *raw, khash_t(isize_infos) *iinfos,
uint64_t n_tot[2], uint64_t n_mapped[2], kh_64_t *my_hash )
{
if( raw->phase != positioned ) return ;
if( unique(raw) ) {
bwa_seq_t *p[2] = { raw->bwa_seq, raw->bwa_seq+1 } ;
pe_data_t d;
int j;
khiter_t it = kh_get(isize_infos, iinfos, bam_get_rg(raw->bam_rec)) ;
isize_info_t *ii = it == kh_end(iinfos) ? &null_ii : &kh_val(iinfos,it) ;
memset(&d, 0, sizeof(pe_data_t));
for (j = 0; j < 2; ++j)
{
if( !raw->bwa_seq[j].seq ) bam1_to_seq(&raw->bam_rec[j], &raw->bwa_seq[j], 1, gap_opt->trim_qual);
d.aln[j].a = p[j]->aln; // cheapting, but we do not really need to copy here
d.aln[j].n = p[j]->n_aln;
}
if ((p[0]->type == BWA_TYPE_UNIQUE || p[0]->type == BWA_TYPE_REPEAT)
&& (p[1]->type == BWA_TYPE_UNIQUE || p[1]->type == BWA_TYPE_REPEAT))
{ // only when both ends mapped
uint64_t x;
int j, k;
long long n_occ[2];
for (j = 0; j < 2; ++j) {
n_occ[j] = 0;
for (k = 0; k < d.aln[j].n; ++k)
n_occ[j] += d.aln[j].a[k].l - d.aln[j].a[k].k + 1;
}
if (n_occ[0] <= pe_opt->max_occ && n_occ[1] <= pe_opt->max_occ) {
d.arr.n = 0;
for (j = 0; j < 2; ++j) {
for (k = 0; k < d.aln[j].n; ++k) {
bwt_aln1_t *r = d.aln[j].a + k;
bwtint_t l;
if (r->l - r->k + 1 >= MIN_HASH_WIDTH) { // then check hash table
uint64_t key = (uint64_t)r->k<<32 | r->l;
int ret;
khint_t iter = kh_put(64, my_hash, key, &ret);
if (ret) { // not in the hash table; ret must equal 1 as we never remove elements
poslist_t *z = &kh_val(my_hash, iter);
z->n = r->l - r->k + 1;
z->a = (bwtint_t*)malloc(sizeof(bwtint_t) * z->n);
for (l = r->k; l <= r->l; ++l)
z->a[l - r->k] = r->a? bwt_sa(bwt[0], l) : bwt[1]->seq_len - (bwt_sa(bwt[1], l) + p[j]->len);
}
for (l = 0; l < kh_val(my_hash, iter).n; ++l) {
x = kh_val(my_hash, iter).a[l];
x = x<<32 | k<<1 | j;
kv_push(uint64_t, d.arr, x);
}
} else { // then calculate on the fly
for (l = r->k; l <= r->l; ++l) {
x = r->a? bwt_sa(bwt[0], l) : bwt[1]->seq_len - (bwt_sa(bwt[1], l) + p[j]->len);
x = x<<32 | k<<1 | j;
kv_push(uint64_t, d.arr, x);
}
}
}
}
pairing(p, &d, pe_opt, gap_opt->s_mm, ii);
}
}
if (pe_opt->N_multi || pe_opt->n_multi) {
for (j = 0; j < 2; ++j) {
if (p[j]->type != BWA_TYPE_NO_MATCH) {
int k;
if (!(p[j]->extra_flag&SAM_FPP) && p[1-j]->type != BWA_TYPE_NO_MATCH) {
bwa_aln2seq_core(
d.aln[j].n, d.aln[j].a, p[j], 0,
p[j]->c1+p[j]->c2-1 > pe_opt->N_multi ?
pe_opt->n_multi : pe_opt->N_multi );
}
else
bwa_aln2seq_core(d.aln[j].n, d.aln[j].a, p[j], 0, pe_opt->n_multi);
for (k = 0; k < p[j]->n_multi; ++k) {
bwt_multi1_t *q = p[j]->multi + k;
q->pos = q->strand? bwt_sa(bwt[0], q->pos) : bwt[1]->seq_len - (bwt_sa(bwt[1], q->pos) + p[j]->len);
}
}
}
}
kv_destroy(d.arr);
kv_destroy(d.pos[0]); kv_destroy(d.pos[1]);
// END from bwa_cal_pac_pos_pe
bwa_paired_sw1(bns, pac, p, pe_opt, ii, n_tot, n_mapped);
// END from bwa_sai2sam_pe_core
bwa_refine_gapped(bns, 1, p[0], pac, ntbns);
bwa_refine_gapped(bns, 1, p[1], pac, ntbns);
// For PE reads, stock BWA would have concatenated their
// barcodes. We don't, for once because we don't identify
// barcodes, but also because the idea feels wrong.
bwa_update_bam1( &raw->bam_rec[0], bns, &raw->bwa_seq[0], &raw->bwa_seq[1], gap_opt->mode, gap_opt->max_top2);
bwa_update_bam1( &raw->bam_rec[1], bns, &raw->bwa_seq[1], &raw->bwa_seq[0], gap_opt->mode, gap_opt->max_top2);
bwa_free_read_seq1(&raw->bwa_seq[1]);
bwa_free_read_seq1(&raw->bwa_seq[0]);
}
raw->phase = finished ;
}
static inline double tdiff( struct timeval* tv1, struct timeval *tv2 )
{
return (double)(tv2->tv_sec-tv1->tv_sec) + 0.000001 * (double)(tv2->tv_usec-tv1->tv_usec) ;
}
/* XXX This is creating difficulties in a cluster environment.
*
* We want the genome index to live in shared memory, in case the
* cluster scheduler starts up more than one instance on a single node.
* So we need mmap(). We also want to have the genome index on a
* network file system, to avoid silly duplication.
*
* The genome index on NFS already causes substantial traffic, combined
* with mmap() it seems to get a lot worse. The way out could be a
* "shared memory object", which is filled explicitly and then mmapped,
* maybe combined with a multicast protocol for distribution. But then
* we need to dispose of the shared memory object after some timeout.
*
* So, here's the clean idea: Operate on a named shared memory object
* ("index") and two named semaphores ("ready", "alive"). To initialize
* the genome index, grab "ready", mmap "index" and put back "ready".
* At regular intervals, put "alive", when done, unmap "index" (but do
* not unlink anything).
*
* If the three don't exist, create them, and fork a process to
* initialize them, then proceed as above. The child loads the genome
* index, then puts "ready". It then does a timed wait on "alive". If
* it runs into a timeout, it unlinks everything and exits.
*
* To be implemented when I feel like it.
*/
void init_genome_index( const char* prefix, int touch )
{
struct timeval tv, tv1 ;
gettimeofday( &tv, 0 ) ;
char *str = (char*)calloc(strlen(prefix) + 10, 1);
bwase_initialize();
init_revcom1();
fprintf(stderr, "[init_genome_index] loading index... ");
strcpy(str, prefix); strcat(str, ".bwt"); bwt[0] = bwt_restore_bwt(str,touch);
strcpy(str, prefix); strcat(str, ".rbwt"); bwt[1] = bwt_restore_bwt(str,touch);
strcpy(str, prefix); strcat(str, ".sa"); bwt_restore_sa(str, bwt[0],touch);
strcpy(str, prefix); strcat(str, ".rsa"); bwt_restore_sa(str, bwt[1],touch);
free(str);
// if (!(gap_opt.mode & BWA_MODE_COMPREAD)) { // in color space; initialize ntpac
// pe_opt->type = BWA_PET_SOLID;
// ntbns = bwa_open_nt(prefix);
// }
pac = bwt_restore_pac( bns,touch ) ;
gettimeofday( &tv1, 0 ) ;
fprintf(stderr, "%.2f sec\n", tdiff(&tv, &tv1));
genome_length = bwt[0]->seq_len ;
}
void init_genome_params( const char* prefix )
{
bwtint_t foo[5] ;
char *fn = alloca(strlen(prefix) + 10);
strcpy(fn, prefix); strcat(fn, ".bwt");
FILE *fp = xopen(fn, "rb");
err_fread(foo, sizeof(bwtint_t), 5, fp);
genome_length = foo[4] ;
fclose(fp) ;
}
void pair_aln(bam_pair_t *p)
{
switch (p->kind) {
case eof_marker: break ;
case singleton: aln_singleton(p) ; break ;
case proper_pair: aln_pair(p) ; break ;
}
}
void pair_posn(bam_pair_t *p)
{
switch (p->kind) {
case eof_marker: break ;
case singleton: posn_singleton(p) ; break ;
case proper_pair: posn_pair(p) ; break ;
}
}
void pair_finish(
bam_pair_t *p, khash_t(isize_infos) *iinfos,
uint64_t n_tot[2], uint64_t n_mapped[2], kh_64_t *my_hash )
{
switch (p->kind) {
case eof_marker: break ;
case singleton: finish_singleton(p) ; break ;
case proper_pair: finish_pair(p,iinfos,n_tot,n_mapped,my_hash) ; break ;
}
}
void pair_print_bam(BGZF *output, bam_pair_t *p)
{
int i ;
// If "only aligned" is requested and at least one mate is unmapped,
// we skip the output. (Conserves time and space where we don't
// need to pass through the unaligned sequences.)
if( only_aligned )
for( i = 0 ; i != p->kind ; ++i )
if( p->bam_rec[i].core.flag & SAM_FSU )
return ;
for( i = 0 ; i != p->kind ; ++i )
bwa_print_bam1(output, &p->bam_rec[i]);
}
inline void put_int( unsigned char **p, int x )
{
(*p)[0] = x >> 0 & 0xff ;
(*p)[1] = x >> 8 & 0xff ;
(*p)[2] = x >> 16 & 0xff ;
(*p)[3] = x >> 24 & 0xff ;
*p += 4 ;
}
inline void put_long( unsigned char **p, uint64_t x )
{
put_int( p, x >> 0 & 0xffffffff ) ;
put_int( p, x >> 32 & 0xffffffff ) ;
}
inline void put_block( unsigned char **p, void *q, size_t s )
{
memcpy( *p, q, s ) ;
*p += s ;
}
/**
* Serializes a bam_pair_t, no matter what phase it is in.
* We only serialize the valid fields, depending on phase.
*/
void msg_init_from_pair(zmq_msg_t *m, bam_pair_t *p)
{
// recno, kind, phase, 0-2 bam_recs w/ data_len
int rc, i, len = 10 ;
for( i = 0 ; i != p->kind ; ++i ) {
len += sizeof( bam1_core_t ) + 4 + p->bam_rec[i].data_len ;
switch( p->phase ) {
case pristine: break ;
case finished: break ;
case positioned: len += 38 + p->bwa_seq[i].n_multi * sizeof(bwt_multi1_t) ;
// fallthrough!
case aligned: len += 8 + p->bwa_seq[i].n_aln * sizeof(bwt_aln1_t) ;
break ;
}
}
rc = zmq_msg_init_size(m, len) ;
xassert (rc == 0, "fail to init message");
unsigned char *q = zmq_msg_data(m);
put_long( &q, p->recno ) ;
*q++ = p->kind ;
*q++ = p->phase ;
for( i = 0 ; i != p->kind ; ++i ) {
put_block( &q, &p->bam_rec[i].core, sizeof( bam1_core_t ) ) ;
put_int( &q, p->bam_rec[i].data_len ) ;
put_block( &q, p->bam_rec[i].data, p->bam_rec[i].data_len ) ;
switch( p->phase ) {
case pristine: break ;
case finished: break ;
case positioned: *q++ = p->bwa_seq[i].strand << 4 | p->bwa_seq[i].type ;
*q++ = p->bwa_seq[i].n_mm ;
*q++ = p->bwa_seq[i].n_gapo ;
*q++ = p->bwa_seq[i].n_gape ;
*q++ = p->bwa_seq[i].seQ ;
*q++ = p->bwa_seq[i].mapQ ;
put_int( &q, p->bwa_seq[i].len ) ;
put_int( &q, p->bwa_seq[i].clip_len ) ;
put_int( &q, p->bwa_seq[i].score ) ;
put_int( &q, p->bwa_seq[i].sa ) ;
put_int( &q, p->bwa_seq[i].c1 ) ;
put_int( &q, p->bwa_seq[i].c2 ) ;
put_int( &q, p->bwa_seq[i].pos ) ;
put_int( &q, p->bwa_seq[i].n_multi ) ;
put_block( &q, p->bwa_seq[i].multi, p->bwa_seq[i].n_multi * sizeof(bwt_multi1_t) ) ;
// fallthrough!
case aligned: put_int( &q, p->bwa_seq[i].max_entries ) ;
put_int( &q, p->bwa_seq[i].n_aln ) ;