forked from samtools/samtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bam_sort.c
3811 lines (3392 loc) · 131 KB
/
bam_sort.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
/* bam_sort.c -- sorting and merging.
Copyright (C) 2008-2023 Genome Research Ltd.
Portions copyright (C) 2009-2012 Broad Institute.
Author: Heng Li <[email protected]>
Author: Martin Pollard <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. */
#include <config.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <getopt.h>
#include <assert.h>
#include <pthread.h>
#include <inttypes.h>
#include "htslib/ksort.h"
#include "htslib/hts_os.h"
#include "htslib/khash.h"
#include "htslib/klist.h"
#include "htslib/kstring.h"
#include "htslib/sam.h"
#include "htslib/hts_endian.h"
#include "htslib/cram.h"
#include "htslib/thread_pool.h"
#include "sam_opts.h"
#include "samtools.h"
#include "bedidx.h"
#include "bam.h"
//#define DEBUG_MINHASH
#define BAM_BLOCK_SIZE 2*1024*1024
#define MAX_TMP_FILES 64
// Struct which contains the sorting key for TemplateCoordinate sort.
typedef struct {
int tid1;
int tid2;
hts_pos_t pos1;
hts_pos_t pos2;
bool neg1;
bool neg2;
const char *library;
char *mid;
char *name;
bool is_upper_of_pair;
} template_coordinate_key_t;
// Struct to store fixed buffers of template coordinate keys
typedef struct {
size_t n; // the # of keys stored
size_t m; // the # of buffers allocated
size_t buffer_size; // # the fixed size of each buffer
template_coordinate_key_t **buffers; // the list of buffers
} template_coordinate_keys_t;
// Gets the idx'th key; does not OOB check
static template_coordinate_key_t* template_coordinate_keys_get(template_coordinate_keys_t *keys, size_t idx) {
size_t buffer_idx = idx / keys->buffer_size; // the index of the buffer to retrieve in buffer
size_t buffer_offset = idx % keys->buffer_size; // the offset into the given buffer to retrieve
//assert(buffer_idx < keys->m);
//assert(buffer_offset < keys->buffer_size);
return &keys->buffers[buffer_idx][buffer_offset];
}
// Rellocates the buffers to hold at least max_k entries
static int template_coordinate_keys_realloc(template_coordinate_keys_t *keys, int max_k) {
size_t cur_m = keys->m;
keys->m += 0x100;
//assert(keys->m > cur_m);
//assert(keys->m * keys->buffer_size >= max_k);
if ((keys->buffers = realloc(keys->buffers, keys->m * sizeof(template_coordinate_key_t*))) == NULL) {
print_error("sort", "couldn't reallocate memory for template coordinate key buffers");
return -1;
}
// allocate space for new buffers
int j;
for (j = cur_m; j < keys->m; ++j) {
if ((keys->buffers[j]= malloc(sizeof(template_coordinate_key_t) * keys->buffer_size)) == NULL) {
print_error("sort", "couldn't allocate memory for template coordinate key buffer");
return -1;
}
}
return 0;
}
// Struct which contains the a record, and the pointer to the sort tag (if any) or
// a combined ref / position / strand.
// Used to speed up sorts (coordinate, by-tag, and template-coordinate).
typedef struct bam1_tag {
bam1_t *bam_record;
union {
const uint8_t *tag;
uint8_t pos_tid[12];
template_coordinate_key_t *key;
} u;
} bam1_tag;
/* Minimum memory required in megabytes before sort will attempt to run. This
is to prevent accidents where failing to use the -m option correctly results
in the creation of a temporary file for each read in the input file.
Don't forget to update the man page if you change this. */
const size_t SORT_MIN_MEGS_PER_THREAD = 1;
/* Default per-thread memory for sort. Must be >= SORT_MIN_MEGS_PER_THREAD.
Don't forget to update the man page if you change this. */
const size_t SORT_DEFAULT_MEGS_PER_THREAD = 768;
#if !defined(__DARWIN_C_LEVEL) || __DARWIN_C_LEVEL < 900000L
#define NEED_MEMSET_PATTERN4
#endif
#ifdef NEED_MEMSET_PATTERN4
void memset_pattern4(void *target, const void *pattern, size_t size) {
uint32_t* target_iter = target;
size_t loops = size/4;
size_t i;
for (i = 0; i < loops; ++i) {
memcpy(target_iter, pattern, 4);
++target_iter;
}
if (size%4 != 0)
memcpy(target_iter, pattern, size%4);
}
#endif
KHASH_INIT(c2c, char*, char*, 1, kh_str_hash_func, kh_str_hash_equal)
KHASH_INIT(cset, char*, char, 0, kh_str_hash_func, kh_str_hash_equal)
KHASH_MAP_INIT_STR(c2i, int)
KHASH_MAP_INIT_STR(const_c2c, char *)
#define hdrln_free_char(p)
KLIST_INIT(hdrln, char*, hdrln_free_char)
static template_coordinate_key_t* template_coordinate_key(bam1_t *b, template_coordinate_key_t *key, sam_hdr_t *hdr, khash_t(const_c2c) *lib_lookup);
typedef enum {Coordinate, QueryName, TagCoordinate, TagQueryName, MinHash, TemplateCoordinate} SamOrder;
static SamOrder g_sam_order = Coordinate;
static int natural_sort = 1; // not ASCII, but alphanumeric: a12b > a7b
static char g_sort_tag[2] = {0,0};
#define is_digit(c) ((c)<='9' && (c)>='0')
static int strnum_cmp(const char *_a, const char *_b)
{
if (!natural_sort)
return strcmp(_a,_b);
const unsigned char *a = (const unsigned char*)_a, *b = (const unsigned char*)_b;
const unsigned char *pa = a, *pb = b;
while (*pa && *pb) {
if (!is_digit(*pa) || !is_digit(*pb)) {
if (*pa != *pb)
return (int)*pa - (int)*pb;
++pa; ++pb;
} else {
// skip leading zeros
while (*pa == '0') ++pa;
while (*pb == '0') ++pb;
// skip matching digits
while (is_digit(*pa) && *pa == *pb)
pa++, pb++;
// Now mismatching, so see which ends the number sooner
int diff = (int)*pa - (int)*pb;
while (is_digit(*pa) && is_digit(*pb))
pa++, pb++;
if (is_digit(*pa))
return 1; // pa still going, so larger
else if (is_digit(*pb))
return -1; // pb still going, so larger
else if (diff)
return diff; // same length, so earlier diff
}
}
return *pa? 1 : *pb? -1 : 0;
}
#define HEAP_EMPTY (UINT64_MAX >> 1)
typedef struct {
int i;
uint32_t tid;
uint64_t pos:63, rev:1, idx;
bam1_tag entry;
} heap1_t;
static inline int bam1_cmp_by_tag(const bam1_tag a, const bam1_tag b);
static inline int bam1_cmp_by_minhash(const bam1_tag a, const bam1_tag b);
static inline int bam1_cmp_template_coordinate(const bam1_tag a, const bam1_tag b);
static khash_t(const_c2c) * lookup_libraries(sam_hdr_t *header);
static void lib_lookup_destroy(khash_t(const_c2c) *lib_lookup);
// Function to compare reads in the heap and determine which one is < the other
// Note, unlike the bam1_cmp_by_X functions which return <0, 0, >0 this
// is strictly 0 or 1 only.
static inline int heap_lt(const heap1_t a, const heap1_t b)
{
if (!a.entry.bam_record)
return 1;
if (!b.entry.bam_record)
return 0;
int t, fa, fb;
switch (g_sam_order) {
case Coordinate:
if (a.tid != b.tid) return a.tid > b.tid;
if (a.pos != b.pos) return a.pos > b.pos;
if (a.rev != b.rev) return a.rev > b.rev;
break;
case QueryName:
t = strnum_cmp(bam_get_qname(a.entry.bam_record), bam_get_qname(b.entry.bam_record));
if (t != 0) return t > 0;
fa = a.entry.bam_record->core.flag & 0xc0;
fb = b.entry.bam_record->core.flag & 0xc0;
if (fa != fb) return fa > fb;
break;
case TagQueryName:
case TagCoordinate:
t = bam1_cmp_by_tag(a.entry, b.entry);
if (t != 0) return t > 0;
break;
case MinHash:
t = bam1_cmp_by_minhash(a.entry, b.entry);
if (t != 0) return t > 0;
break;
case TemplateCoordinate:
t = bam1_cmp_template_coordinate(a.entry, b.entry);
if (t != 0) return t > 0;
break;
default:
print_error("heap_lt", "unknown sort order: %d", g_sam_order);
break;
}
// This compares by position in the input file(s)
if (a.i != b.i) return a.i > b.i;
return a.idx > b.idx;
}
KSORT_INIT(heap, heap1_t, heap_lt)
typedef struct merged_header {
sam_hdr_t *hdr;
kstring_t out_rg;
kstring_t out_pg;
kstring_t out_co;
char **target_name;
uint32_t *target_len;
size_t n_targets;
size_t targets_sz;
khash_t(c2i) *sq_tids;
khash_t(cset) *rg_ids;
khash_t(cset) *pg_ids;
bool have_hd;
} merged_header_t;
typedef struct trans_tbl {
int32_t n_targets;
int* tid_trans;
kh_c2c_t* rg_trans;
kh_c2c_t* pg_trans;
bool lost_coord_sort;
} trans_tbl_t;
static void trans_tbl_destroy(trans_tbl_t *tbl) {
khiter_t iter;
free(tbl->tid_trans);
/*
* The values for the tbl->rg_trans and tbl->pg_trans hashes are pointers
* to keys in the rg_ids and pg_ids sets of the merged_header_t, so
* they should not be freed here.
*
* The keys are unique to each hash entry, so they do have to go.
*/
for (iter = kh_begin(tbl->rg_trans); iter != kh_end(tbl->rg_trans); ++iter) {
if (kh_exist(tbl->rg_trans, iter)) {
free(kh_key(tbl->rg_trans, iter));
}
}
for (iter = kh_begin(tbl->pg_trans); iter != kh_end(tbl->pg_trans); ++iter) {
if (kh_exist(tbl->pg_trans, iter)) {
free(kh_key(tbl->pg_trans, iter));
}
}
kh_destroy(c2c,tbl->rg_trans);
kh_destroy(c2c,tbl->pg_trans);
}
/*
* Create a merged_header_t struct.
*/
static merged_header_t * init_merged_header() {
merged_header_t *merged_hdr;
merged_hdr = calloc(1, sizeof(*merged_hdr));
if (merged_hdr == NULL) return NULL;
merged_hdr->hdr = sam_hdr_init();
if (!merged_hdr->hdr) goto fail;
merged_hdr->targets_sz = 16;
merged_hdr->target_name = malloc(merged_hdr->targets_sz
* sizeof(*merged_hdr->target_name));
if (NULL == merged_hdr->target_name) goto fail;
merged_hdr->target_len = malloc(merged_hdr->targets_sz
* sizeof(*merged_hdr->target_len));
if (NULL == merged_hdr->target_len) goto fail;
merged_hdr->sq_tids = kh_init(c2i);
if (merged_hdr->sq_tids == NULL) goto fail;
merged_hdr->rg_ids = kh_init(cset);
if (merged_hdr->rg_ids == NULL) goto fail;
merged_hdr->pg_ids = kh_init(cset);
if (merged_hdr->pg_ids == NULL) goto fail;
return merged_hdr;
fail:
perror("[init_merged_header]");
kh_destroy(cset, merged_hdr->pg_ids);
kh_destroy(cset, merged_hdr->rg_ids);
kh_destroy(c2i, merged_hdr->sq_tids);
free(merged_hdr->target_name);
free(merged_hdr->target_len);
sam_hdr_destroy(merged_hdr->hdr);
free(merged_hdr);
return NULL;
}
/* Some handy kstring manipulating functions */
// Append char range to kstring
static inline int range_to_ks(const char *src, int from, int to,
kstring_t *dest) {
return kputsn(src + from, to - from, dest) != to - from;
}
// Append a kstring to a kstring
static inline int ks_to_ks(kstring_t *src, kstring_t *dest) {
return kputsn(ks_str(src), ks_len(src), dest) != ks_len(src);
}
/*
* Generate a unique ID by appending a random suffix to a given prefix.
* existing_ids is the set of IDs that are already in use.
* If always_add_suffix is true, the suffix will always be included.
* If false, prefix will be returned unchanged if it isn't in existing_ids.
*/
static int gen_unique_id(char *prefix, khash_t(cset) *existing_ids,
bool always_add_suffix, kstring_t *dest) {
khiter_t iter;
if (!always_add_suffix) {
// Try prefix on its own first
iter = kh_get(cset, existing_ids, prefix);
if (iter == kh_end(existing_ids)) { // prefix isn't used yet
dest->l = 0;
if (kputs(prefix, dest) == EOF) return -1;
return 0;
}
}
do {
dest->l = 0;
ksprintf(dest, "%s-%0lX", prefix, lrand48());
iter = kh_get(cset, existing_ids, ks_str(dest));
} while (iter != kh_end(existing_ids));
return 0;
}
/*
* Add the @HD line to the new header
* In practice the @HD line will come from the first input header.
*/
static int trans_tbl_add_hd(merged_header_t* merged_hdr,
sam_hdr_t *translate) {
kstring_t hd_line = { 0, 0, NULL };
int res;
// TODO: handle case when @HD needs merging.
if (merged_hdr->have_hd) return 0;
res = sam_hdr_find_hd(translate, &hd_line);
if (res < -1) {
print_error("merge", "failed to get @HD line from header");
return -1;
}
if (res < 0) // Not found
return 0;
if (sam_hdr_add_lines(merged_hdr->hdr, hd_line.s, hd_line.l) < 0) {
print_error("merge", "failed to add @HD line to new header");
free(hd_line.s);
return -1;
}
free(hd_line.s);
merged_hdr->have_hd = true;
return 0;
}
/*
* Add @SQ records to the translation table.
*
* Go through the target list for the input header. Any new targets found
* are added to the output header target list. At the same time, a mapping
* from the input to output target ids is stored in tbl.
*
* If any new targets are found, the header text is scanned to find the
* corresponding @SQ records. They are then copied into the
* merged_hdr->out_text kstring (which will eventually become the
* output header text).
*
* Returns 0 on success, -1 on failure.
*/
static int trans_tbl_add_sq(merged_header_t* merged_hdr, sam_hdr_t *translate,
trans_tbl_t* tbl) {
int32_t i;
int min_tid = -1, res;
kstring_t sq_line = { 0, 0, NULL }, sq_sn = { 0, 0, NULL };
// Fill in the tid part of the translation table, adding new targets
// to the merged header as we go.
for (i = 0; i < sam_hdr_nref(translate); ++i) {
int trans_tid;
sq_sn.l = 0;
res = sam_hdr_find_tag_pos(translate, "SQ", i, "SN", &sq_sn);
if (res < 0) {
print_error("merge", "failed to get @SQ SN #%d from header", i + 1);
goto fail;
}
trans_tid = sam_hdr_name2tid(merged_hdr->hdr, sq_sn.s);
if (trans_tid < -1) {
print_error("merge", "failed to lookup ref");
goto fail;
}
if (trans_tid < 0) {
// Append missing entries to out_hdr
sq_line.l = 0;
res = sam_hdr_find_line_id(translate, "SQ", "SN", sq_sn.s, &sq_line);
if (res < 0) {
print_error("merge", "failed to get @SQ SN:%s from header", sq_sn.s);
goto fail;
}
trans_tid = sam_hdr_nref(merged_hdr->hdr);
res = sam_hdr_add_lines(merged_hdr->hdr, sq_line.s, sq_line.l);
if (res < 0) {
print_error("merge", "failed to add @SQ SN:%s to new header", sq_sn.s);
goto fail;
}
}
tbl->tid_trans[i] = trans_tid;
if (tbl->tid_trans[i] > min_tid) {
min_tid = tbl->tid_trans[i];
} else {
tbl->lost_coord_sort = true;
}
}
free(sq_line.s);
free(sq_sn.s);
return 0;
fail:
free(sq_line.s);
free(sq_sn.s);
return -1;
}
/*
* Common code for setting up RG and PG record ID tag translation.
*
* is_rg is true for RG translation, false for PG.
* translate is the input bam header
* merge is true if tags with the same ID are to be merged.
* known_ids is the set of IDs already in the output header.
* id_map is the translation map from input header IDs to output header IDs
* If override is set, it will be used to replace the existing ID (RG only)
*
* known_ids and id_map have entries for the new IDs added to them.
*
* Return value is a linked list of header lines with the translated IDs,
* or NULL if something went wrong (probably out of memory).
*
*/
static klist_t(hdrln) * trans_rg_pg(bool is_rg, sam_hdr_t *translate,
bool merge, khash_t(cset)* known_ids,
khash_t(c2c)* id_map, char *override) {
khiter_t iter;
int num_ids, i;
const char *rec_type = is_rg ? "RG" : "PG";
klist_t(hdrln) *hdr_lines;
hdr_lines = kl_init(hdrln);
// Search through translate's header
num_ids = sam_hdr_count_lines(translate, rec_type);
if (num_ids < 0)
goto fail;
for (i = 0; i < num_ids; i++) {
kstring_t orig_id = { 0, 0, NULL }; // ID in original header
kstring_t transformed_id = { 0, 0, NULL }; // ID in output header
char *map_value; // Value to store in id_map
bool id_changed; // Have we changed the ID?
bool not_found_in_output; // ID isn't in the output header (yet)
if (sam_hdr_find_tag_pos(translate, rec_type, i, "ID", &orig_id) < 0)
goto fail;
// is our matched ID in our output ID set already?
iter = kh_get(cset, known_ids, ks_str(&orig_id));
not_found_in_output = (iter == kh_end(known_ids));
if (override) {
// Override original ID (RG only)
#ifdef OVERRIDE_DOES_NOT_MERGE
if (gen_unique_id(override, known_ids, false, &transformed_id))
goto memfail;
not_found_in_output = true; // As ID now unique
#else
if (kputs(override, &transformed_id) == EOF) goto memfail;
// Know about override already?
iter = kh_get(cset, known_ids, ks_str(&transformed_id));
not_found_in_output = (iter == kh_end(known_ids));
#endif
id_changed = true;
} else {
if ( not_found_in_output || merge) {
// Not in there or merging so can add it as 1-1 mapping
if (ks_to_ks(&orig_id, &transformed_id)) goto memfail;
id_changed = false;
} else {
// It's in there so we need to transform it by appending
// a random number to the id
if (gen_unique_id(ks_str(&orig_id), known_ids,
true, &transformed_id))
goto memfail;
id_changed = true;
not_found_in_output = true; // As ID now unique
}
}
// Does this line need to go into our output header?
if (not_found_in_output) {
// Take matched line and replace ID with transformed_id
kstring_t new_hdr_line = { 0, 0, NULL };
if (sam_hdr_find_line_id(translate, rec_type,
"ID", ks_str(&orig_id), &new_hdr_line) < 0){
goto fail;
}
if (id_changed) {
char *idp = strstr(ks_str(&new_hdr_line), "\tID:"), *id_end;
ptrdiff_t id_offset, id_len;
if (!idp) {
print_error("merge", "failed to find ID in \"%s\"\n",
ks_str(&new_hdr_line));
goto fail;
}
idp += 4;
for (id_end = idp; *id_end >= '\n'; id_end++) {}
id_offset = idp - new_hdr_line.s;
id_len = id_end - idp;
if (id_len < transformed_id.l) {
if (ks_resize(&new_hdr_line, new_hdr_line.l
+ transformed_id.l - id_len + 1/*nul*/))
goto fail;
}
if (id_len != transformed_id.l) {
memmove(new_hdr_line.s + id_offset + transformed_id.l,
new_hdr_line.s + id_offset + id_len,
new_hdr_line.l - id_offset - id_len + 1);
}
memcpy(new_hdr_line.s + id_offset, transformed_id.s,
transformed_id.l);
}
// append line to output linked list
char** ln = kl_pushp(hdrln, hdr_lines);
*ln = ks_release(&new_hdr_line); // Give away to linked list
// Need to add it to known_ids set
int in_there = 0;
iter = kh_put(cset, known_ids, ks_str(&transformed_id), &in_there);
if (in_there < 0) goto memfail;
assert(in_there > 0); // Should not already be in the map
map_value = ks_release(&transformed_id);
} else {
// Use existing string in id_map
assert(kh_exist(known_ids, iter));
map_value = kh_key(known_ids, iter);
free(ks_release(&transformed_id));
}
// Insert it into our translation map
int in_there = 0;
iter = kh_put(c2c, id_map, ks_release(&orig_id), &in_there);
kh_value(id_map, iter) = map_value;
}
// If there are no RG lines in the file and we are overriding add one
if (is_rg && override && hdr_lines->size == 0) {
kstring_t new_id = {0, 0, NULL};
kstring_t line = {0, 0, NULL};
kstring_t empty = {0, 0, NULL};
int in_there = 0;
char** ln;
// Get the new ID
if (gen_unique_id(override, known_ids, false, &new_id))
goto memfail;
// Make into a header line and add to linked list
ksprintf(&line, "@RG\tID:%s", ks_str(&new_id));
ln = kl_pushp(hdrln, hdr_lines);
*ln = ks_release(&line);
// Put into known_ids set
iter = kh_put(cset, known_ids, ks_str(&new_id), &in_there);
if (in_there < 0) goto memfail;
assert(in_there > 0); // Should be a new entry
// Put into translation map (key is empty string)
if (kputs("", &empty) == EOF) goto memfail;
iter = kh_put(c2c, id_map, ks_release(&empty), &in_there);
if (in_there < 0) goto memfail;
assert(in_there > 0); // Should be a new entry
kh_value(id_map, iter) = ks_release(&new_id);
}
return hdr_lines;
memfail:
perror(__func__);
fail:
if (hdr_lines) kl_destroy(hdrln, hdr_lines);
return NULL;
}
/*
* Common code for completing RG and PG record translation.
*
* Input is a list of header lines, and the mapping from input to
* output @PG record IDs.
*
* RG and PG records can contain tags that cross-reference to other @PG
* records. This fixes the tags to contain the new IDs before adding
* them to the output header text.
*/
static int finish_rg_pg(bool is_rg, klist_t(hdrln) *hdr_lines,
khash_t(c2c)* pg_map, kstring_t *out_text) {
const char *search = is_rg ? "\tPG:" : "\tPP:";
khiter_t idx;
char *line = NULL;
while ((kl_shift(hdrln, hdr_lines, &line)) == 0) {
char *id = strstr(line, search); // Look for tag to fix
int pos1 = 0, pos2 = 0;
char *new_id = NULL;
if (id) {
// Found a tag. Look up the value in the translation map
// to see what it should be changed to in the output file.
char *end, tmp;
id += 4; // Point to value
end = strchr(id, '\t'); // Find end of tag
if (!end) end = id + strlen(id);
tmp = *end;
*end = '\0'; // Temporarily get the value on its own.
// Look-up in translation table
idx = kh_get(c2c, pg_map, id);
if (idx == kh_end(pg_map)) {
// Not found, warn.
fprintf(stderr, "[W::%s] Tag %s%s not found in @PG records\n",
__func__, search + 1, id);
} else {
// Remember new id and splice points on original string
new_id = kh_value(pg_map, idx);
pos1 = id - line;
pos2 = end - line;
}
*end = tmp; // Restore string
}
// Copy line to output:
// line[0..pos1), new_id (if not NULL), line[pos2..end), '\n'
if (pos1 && range_to_ks(line, 0, pos1, out_text)) goto memfail;
if (new_id && kputs(new_id, out_text) == EOF) goto memfail;
if (kputs(line + pos2, out_text) == EOF) goto memfail;
if (kputc('\n', out_text) == EOF) goto memfail;
free(line); // No longer needed
line = NULL;
}
return 0;
memfail:
perror(__func__);
free(line); // Prevent leakage as no longer on list
return -1;
}
/*
* Build the translation table for an input *am file. This stores mappings
* which allow IDs to be converted from those used in the input file
* to the ones which will be used in the output. The mappings are for:
* Reference sequence IDs (for @SQ records)
* @RG record ID tags
* @PG record ID tags
*
* At the same time, new header text is built up by copying records
* from the input bam file. This will eventually become the header for
* the output file. When copied, the ID tags for @RG and @PG records
* are replaced with their values. The @PG PP: and @RG PG: tags
* are also modified if necessary.
*
* merged_hdr holds state on the output header (which IDs are present, etc.)
* translate is the input header
* tbl is the translation table that gets filled in.
* merge_rg controls merging of @RG records
* merge_pg controls merging of @PG records
* If rg_override is not NULL, it will be used to replace the existing @RG ID
*
* Returns 0 on success, -1 on failure.
*/
static int trans_tbl_init(merged_header_t* merged_hdr, sam_hdr_t* translate,
trans_tbl_t* tbl, bool merge_rg, bool merge_pg,
bool copy_co, char* rg_override)
{
kstring_t lines = { 0, 0, NULL };
klist_t(hdrln) *rg_list = NULL;
klist_t(hdrln) *pg_list = NULL;
tbl->n_targets = sam_hdr_nref(translate);
tbl->rg_trans = tbl->pg_trans = NULL;
tbl->tid_trans = (int*)calloc(tbl->n_targets ? tbl->n_targets : 1,
sizeof(int));
if (tbl->tid_trans == NULL) goto memfail;
tbl->rg_trans = kh_init(c2c);
if (tbl->rg_trans == NULL) goto memfail;
tbl->pg_trans = kh_init(c2c);
if (tbl->pg_trans == NULL) goto memfail;
tbl->lost_coord_sort = false;
// Get the @HD record (if not there already).
if (trans_tbl_add_hd(merged_hdr, translate)) goto fail;
// Fill in map and add header lines for @SQ records
if (trans_tbl_add_sq(merged_hdr, translate, tbl)) goto fail;
// Get translated header lines and fill in map for @RG records
rg_list = trans_rg_pg(true, translate, merge_rg, merged_hdr->rg_ids,
tbl->rg_trans, rg_override);
if (!rg_list) goto fail;
// Get translated header lines and fill in map for @PG records
pg_list = trans_rg_pg(false, translate, merge_pg, merged_hdr->pg_ids,
tbl->pg_trans, NULL);
if (!pg_list) goto fail;
// Fix-up PG: tags in the new @RG records and add to output
if (finish_rg_pg(true, rg_list, tbl->pg_trans, &merged_hdr->out_rg))
goto fail;
// Fix-up PP: tags in the new @PG records and add to output
lines.l = 0;
if (finish_rg_pg(false, pg_list, tbl->pg_trans, &merged_hdr->out_pg))
goto fail;
kl_destroy(hdrln, rg_list); rg_list = NULL;
kl_destroy(hdrln, pg_list); pg_list = NULL;
if (copy_co) {
// Just append @CO headers without translation
int num_co = sam_hdr_count_lines(translate, "CO"), i;
if (num_co < 0)
goto fail;
for (i = 0; i < num_co; i++) {
if (sam_hdr_find_line_pos(translate, "CO", i, &lines) < 0)
goto fail;
if (ks_to_ks(&lines, &merged_hdr->out_co))
goto fail;
if (kputc('\n', &merged_hdr->out_co) < 0)
goto fail;
}
}
free(lines.s);
return 0;
memfail:
perror(__func__);
fail:
trans_tbl_destroy(tbl);
if (rg_list) kl_destroy(hdrln, rg_list);
if (pg_list) kl_destroy(hdrln, pg_list);
free(lines.s);
return -1;
}
static int finish_merged_header(merged_header_t *merged_hdr) {
if (sam_hdr_add_lines(merged_hdr->hdr, ks_c_str(&merged_hdr->out_rg),
ks_len(&merged_hdr->out_rg)) < 0)
return -1;
if (sam_hdr_add_lines(merged_hdr->hdr, ks_c_str(&merged_hdr->out_pg),
ks_len(&merged_hdr->out_pg)) < 0)
return -1;
if (sam_hdr_add_lines(merged_hdr->hdr, ks_c_str(&merged_hdr->out_co),
ks_len(&merged_hdr->out_co)) < 0)
return -1;
return 0;
}
/*
* Free a merged_header_t struct and all associated data.
*
* Note that the keys to the rg_ids and pg_ids sets are also used as
* values in the translation tables. This function should therefore not
* be called until the translation tables are no longer needed.
*/
static void free_merged_header(merged_header_t *merged_hdr) {
size_t i;
khiter_t iter;
if (!merged_hdr) return;
free(ks_release(&merged_hdr->out_rg));
free(ks_release(&merged_hdr->out_pg));
free(ks_release(&merged_hdr->out_co));
if (merged_hdr->target_name) {
for (i = 0; i < merged_hdr->n_targets; i++) {
free(merged_hdr->target_name[i]);
}
free(merged_hdr->target_name);
}
free(merged_hdr->target_len);
kh_destroy(c2i, merged_hdr->sq_tids);
if (merged_hdr->rg_ids) {
for (iter = kh_begin(merged_hdr->rg_ids);
iter != kh_end(merged_hdr->rg_ids); ++iter) {
if (kh_exist(merged_hdr->rg_ids, iter))
free(kh_key(merged_hdr->rg_ids, iter));
}
kh_destroy(cset, merged_hdr->rg_ids);
}
if (merged_hdr->pg_ids) {
for (iter = kh_begin(merged_hdr->pg_ids);
iter != kh_end(merged_hdr->pg_ids); ++iter) {
if (kh_exist(merged_hdr->pg_ids, iter))
free(kh_key(merged_hdr->pg_ids, iter));
}
kh_destroy(cset, merged_hdr->pg_ids);
}
free(merged_hdr);
}
static void bam_translate(bam1_t* b, trans_tbl_t* tbl)
{
// Update target id if not unmapped tid
if ( b->core.tid >= 0 ) { b->core.tid = tbl->tid_trans[b->core.tid]; }
if ( b->core.mtid >= 0 ) { b->core.mtid = tbl->tid_trans[b->core.mtid]; }
// If we have a RG update it
uint8_t *rg = bam_aux_get(b, "RG");
if (rg) {
char* decoded_rg = bam_aux2Z(rg);
khiter_t k = kh_get(c2c, tbl->rg_trans, decoded_rg);
if (k != kh_end(tbl->rg_trans)) {
char* translate_rg = kh_value(tbl->rg_trans,k);
bam_aux_del(b, rg);
if (translate_rg) {
bam_aux_append(b, "RG", 'Z', strlen(translate_rg) + 1,
(uint8_t*)translate_rg);
}
} else {
char *tmp = strdup(decoded_rg);
fprintf(stderr,
"[bam_translate] RG tag \"%s\" on read \"%s\" encountered "
"with no corresponding entry in header, tag lost. "
"Unknown tags are only reported once per input file for "
"each tag ID.\n",
decoded_rg, bam_get_qname(b));
bam_aux_del(b, rg);
// Prevent future whinges
if (tmp) {
int in_there = 0;
k = kh_put(c2c, tbl->rg_trans, tmp, &in_there);
if (in_there > 0) kh_value(tbl->rg_trans, k) = NULL;
}
}
}
// If we have a PG update it
uint8_t *pg = bam_aux_get(b, "PG");
if (pg) {
char* decoded_pg = bam_aux2Z(pg);
khiter_t k = kh_get(c2c, tbl->pg_trans, decoded_pg);
if (k != kh_end(tbl->pg_trans)) {
char* translate_pg = kh_value(tbl->pg_trans,k);
bam_aux_del(b, pg);
if (translate_pg) {
bam_aux_append(b, "PG", 'Z', strlen(translate_pg) + 1,
(uint8_t*)translate_pg);
}
} else {
char *tmp = strdup(decoded_pg);
fprintf(stderr,
"[bam_translate] PG tag \"%s\" on read \"%s\" encountered "
"with no corresponding entry in header, tag lost. "
"Unknown tags are only reported once per input file for "
"each tag ID.\n",
decoded_pg, bam_get_qname(b));
bam_aux_del(b, pg);
// Prevent future whinges
if (tmp) {
int in_there = 0;
k = kh_put(c2c, tbl->pg_trans, tmp, &in_there);
if (in_there > 0) kh_value(tbl->pg_trans, k) = NULL;
}
}
}
}
int* rtrans_build(int n, int n_targets, trans_tbl_t* translation_tbl)
{
// Create reverse translation table for tids
int* rtrans = (int*)malloc(sizeof(int32_t)*n*n_targets);
const int32_t NOTID = INT32_MIN;
if (!rtrans) return NULL;
memset_pattern4((void*)rtrans, &NOTID, sizeof(int32_t)*n*n_targets);
int i;
for (i = 0; i < n; ++i) {