forked from samtools/samtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bam_sort.c
2468 lines (2181 loc) · 84 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-2016 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/stat.h>
#include <unistd.h>
#include <getopt.h>
#include <assert.h>
#include <pthread.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 "sam_opts.h"
#include "samtools.h"
// 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 tag and position sorts.
typedef struct bam1_tag {
bam1_t *bam_record;
union {
const uint8_t *tag;
uint64_t pos;
} 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)
#define hdrln_free_char(p)
KLIST_INIT(hdrln, char*, hdrln_free_char)
static int g_is_by_qname = 0;
static int g_is_by_tag = 0;
static char g_sort_tag[2] = {0,0};
static int strnum_cmp(const char *_a, const char *_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 (isdigit(*pa) && isdigit(*pb)) {
while (*pa == '0') ++pa;
while (*pb == '0') ++pb;
while (isdigit(*pa) && isdigit(*pb) && *pa == *pb) ++pa, ++pb;
if (isdigit(*pa) && isdigit(*pb)) {
int i = 0;
while (isdigit(pa[i]) && isdigit(pb[i])) ++i;
return isdigit(pa[i])? 1 : isdigit(pb[i])? -1 : (int)*pa - (int)*pb;
} else if (isdigit(*pa)) return 1;
else if (isdigit(*pb)) return -1;
else if (pa - a != pb - b) return pa - a < pb - b? 1 : -1;
} else {
if (*pa != *pb) return (int)*pa - (int)*pb;
++pa; ++pb;
}
}
return *pa? 1 : *pb? -1 : 0;
}
#define HEAP_EMPTY UINT64_MAX
typedef struct {
int i;
uint32_t rev;
uint64_t pos, idx;
bam1_tag entry;
} heap1_t;
static inline int bam1_cmp_by_tag(const bam1_tag a, const bam1_tag b);
// Function to compare reads in the heap and determine which one is < the other
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;
if (g_is_by_tag) {
int t;
t = bam1_cmp_by_tag(a.entry, b.entry);
if (t != 0) return t > 0;
} else if (g_is_by_qname) {
int t, fa, fb;
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;
} else {
if (a.pos != b.pos) return a.pos > b.pos;
if (a.rev != b.rev) return a.rev > b.rev;
}
// 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 {
kstring_t out_hd;
kstring_t out_sq;
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;
/* Something to look like a regmatch_t */
typedef struct hdr_match {
ptrdiff_t rm_so;
ptrdiff_t rm_eo;
} hdr_match_t;
/*
* Search for header lines of a particular record type.
*
* This replaces a regex search for something like /^@SQ.*\tSN:([^\t]+).*$/
* but is much quicker. The locations found are returned in *matches,
* which has a signature the same as that of a regmatch_t.
*
* rec is the record type to match (i.e. @HD, @SQ, @PG or @RG)
* tag is a tag type in the record to match (SN for @SQ, ID for @PG or @RG)
*
* The location of the record (if found) is returned in matches[0]
* If tag is not NULL, the record is searched for the presence of the
* given tag. If found, the location of the value is returned in matches[1].
* If the tag isn't found then the record is ignored and the search resumes
* on the next header line.
*
* For simplicity, some assumptions are made about rec and tag:
* rec should include the leading '@' sign and be three characters long.
* tag should be exactly two characters long.
* These are always string constants when this is called below, so we don't
* bother to check here.
*
* Returns 0 if a match was found, -1 if not.
*/
static int hdr_line_match(const char *text, const char *rec,
const char *tag, hdr_match_t *matches) {
const char *line_start, *line_end = text;
const char *tag_start, *tag_end;
for (;;) {
// Find record, ensure either at start of text or follows '\n'
line_start = strstr(line_end, rec);
while (line_start && line_start > text && *(line_start - 1) != '\n') {
line_start = strstr(line_start + 3, rec);
}
if (!line_start) return -1;
// Find end of header line
line_end = strchr(line_start, '\n');
if (!line_end) line_end = line_start + strlen(line_start);
matches[0].rm_so = line_start - text;
matches[0].rm_eo = line_end - text;
if (!tag) return 0; // Match found if not looking for tag.
for (tag_start = line_start + 3; tag_start < line_end; tag_start++) {
// Find possible tag start. Hacky but quick.
while (*tag_start > '\n') tag_start++;
// Check it
if (tag_start[0] == '\t'
&& strncmp(tag_start + 1, tag, 2) == 0
&& tag_start[3] == ':') {
// Found tag, record location and return.
tag_end = tag_start + 4;
while (*tag_end && *tag_end != '\t' && *tag_end != '\n')
++tag_end;
matches[1].rm_so = tag_start - text + 4;
matches[1].rm_eo = tag_end - text;
return 0;
}
}
// Couldn't find tag, try again from end of current record.
}
}
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->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);
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 header line match to kstring
static inline int match_to_ks(const char *src, const hdr_match_t *match,
kstring_t *dest) {
return range_to_ks(src, match->rm_so, match->rm_eo, dest);
}
// 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,
bam_hdr_t *translate) {
hdr_match_t match = {0, 0};
// TODO: handle case when @HD needs merging.
if (merged_hdr->have_hd) return 0;
if (hdr_line_match(translate->text, "@HD", NULL, &match) != 0) {
return 0;
}
if (match_to_ks(translate->text, &match, &merged_hdr->out_hd)) goto memfail;
if (kputc('\n', &merged_hdr->out_hd) == EOF) goto memfail;
merged_hdr->have_hd = true;
return 0;
memfail:
perror(__func__);
return -1;
}
static inline int grow_target_list(merged_header_t* merged_hdr) {
size_t new_size;
char **new_names;
uint32_t *new_len;
new_size = merged_hdr->targets_sz * 2;
new_names = realloc(merged_hdr->target_name, sizeof(*new_names) * new_size);
if (!new_names) goto fail;
merged_hdr->target_name = new_names;
new_len = realloc(merged_hdr->target_len, sizeof(*new_len) * new_size);
if (!new_len) goto fail;
merged_hdr->target_len = new_len;
merged_hdr->targets_sz = new_size;
return 0;
fail:
perror(__func__);
return -1;
}
/*
* 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, bam_hdr_t *translate,
trans_tbl_t* tbl) {
kstring_t *out_text = &merged_hdr->out_sq;
khash_t(c2i)* sq_tids = merged_hdr->sq_tids;
hdr_match_t *new_sq_matches = NULL;
char *text;
hdr_match_t matches[2];
int32_t i;
int32_t old_n_targets = merged_hdr->n_targets;
khiter_t iter;
int min_tid = -1;
// Fill in the tid part of the translation table, adding new targets
// to the merged header as we go.
for (i = 0; i < translate->n_targets; ++i) {
// Check if it's a new target.
iter = kh_get(c2i, sq_tids, translate->target_name[i]);
if (iter == kh_end(sq_tids)) {
int ret;
// Append missing entries to out_hdr
if (merged_hdr->n_targets == merged_hdr->targets_sz) {
if (grow_target_list(merged_hdr)) goto fail;
}
merged_hdr->target_name[merged_hdr->n_targets] = strdup(translate->target_name[i]);
if (merged_hdr->target_name[merged_hdr->n_targets] == NULL) goto memfail;
merged_hdr->target_len[merged_hdr->n_targets] = translate->target_len[i];
// Record the new identifier for reference below,
// and when building the ttable for other inputs.
iter = kh_put(c2i, sq_tids,
merged_hdr->target_name[merged_hdr->n_targets], &ret);
if (ret < 0) {
free(merged_hdr->target_name[merged_hdr->n_targets]);
goto memfail;
}
assert(ret > 0); // Should not be in hash already.
kh_value(sq_tids, iter) = merged_hdr->n_targets;
tbl->tid_trans[i] = merged_hdr->n_targets++;
} else {
tbl->tid_trans[i] = kh_value(sq_tids, iter);
}
if (tbl->tid_trans[i] > min_tid) {
min_tid = tbl->tid_trans[i];
} else {
tbl->lost_coord_sort = true;
}
}
if (merged_hdr->n_targets == old_n_targets)
return 0; // Everything done if no new targets.
// Otherwise, find @SQ lines in translate->text for all newly added targets.
new_sq_matches = malloc((merged_hdr->n_targets - old_n_targets)
* sizeof(*new_sq_matches));
if (new_sq_matches == NULL) goto memfail;
for (i = 0; i < merged_hdr->n_targets - old_n_targets; i++) {
new_sq_matches[i].rm_so = new_sq_matches[i].rm_eo = -1;
}
text = translate->text;
while (hdr_line_match(text, "@SQ", "SN", matches) == 0) {
// matches[0] is whole line, matches[1] is SN value.
// This is a bit disgusting, but avoids a copy...
char c = text[matches[1].rm_eo];
int idx;
text[matches[1].rm_eo] = '\0';
// Look up the SN value in the sq_tids hash.
iter = kh_get(c2i, sq_tids, text + matches[1].rm_so);
text[matches[1].rm_eo] = c; // restore text
if (iter == kh_end(sq_tids)) {
// Warn about this, but it's not really fatal.
fprintf(stderr, "[W::%s] @SQ SN (%.*s) found in text header but not binary header.\n",
__func__,
(int) (matches[1].rm_eo - matches[1].rm_so),
text + matches[1].rm_so);
text += matches[0].rm_eo;
continue; // Skip to next
}
idx = kh_value(sq_tids, iter);
if (idx >= old_n_targets) {
// is a new SQ, so record position so we can add it to out_text.
assert(idx < merged_hdr->n_targets);
ptrdiff_t off = text - translate->text;
new_sq_matches[idx - old_n_targets].rm_so = matches[0].rm_so + off;
new_sq_matches[idx - old_n_targets].rm_eo = matches[0].rm_eo + off;
}
// Carry on searching from end of current match
text += matches[0].rm_eo;
}
// Copy the @SQ headers found and recreate any missing from binary header.
for (i = 0; i < merged_hdr->n_targets - old_n_targets; i++) {
if (new_sq_matches[i].rm_so >= 0) {
if (match_to_ks(translate->text, &new_sq_matches[i], out_text))
goto memfail;
if (kputc('\n', out_text) == EOF) goto memfail;
} else {
if (kputs("@SQ\tSN:", out_text) == EOF ||
kputs(merged_hdr->target_name[i + old_n_targets], out_text) == EOF ||
kputs("\tLN:", out_text) == EOF ||
kputuw(merged_hdr->target_len[i + old_n_targets], out_text) == EOF ||
kputc('\n', out_text) == EOF) goto memfail;
}
}
free(new_sq_matches);
return 0;
memfail:
perror(__func__);
fail:
free(new_sq_matches);
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, bam_hdr_t *translate,
bool merge, khash_t(cset)* known_ids,
khash_t(c2c)* id_map, char *override) {
hdr_match_t matches[2];
khiter_t iter;
const char *text = translate->text;
const char *rec_type = is_rg ? "@RG" : "@PG";
klist_t(hdrln) *hdr_lines;
hdr_lines = kl_init(hdrln);
// Search through translate's header
while (hdr_line_match(text, rec_type, "ID", matches) == 0) {
// matches[0] is the whole @RG/PG line; matches[1] is the ID field value
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)
// Take a copy of the ID as we'll need it for a hash key.
if (match_to_ks(text, &matches[1], &orig_id)) goto memfail;
// 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 (!id_changed) { // Can just copy
if (match_to_ks(text, &matches[0], &new_hdr_line)) goto memfail;
} else { // Substitute new name for original
if (range_to_ks(text, matches[0].rm_so, matches[1].rm_so,
&new_hdr_line)) goto memfail;
if (ks_to_ks(&transformed_id, &new_hdr_line)) goto memfail;
if (range_to_ks(text, matches[1].rm_eo, matches[0].rm_eo,
&new_hdr_line)) goto memfail;
}
// 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;
text += matches[0].rm_eo; // next!
}
// If there are no RG lines in the file and we are overriding add one
if (is_rg && override && kl_begin(hdr_lines) == NULL) {
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__);
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, bam_hdr_t* translate,
trans_tbl_t* tbl, bool merge_rg, bool merge_pg,
bool copy_co, char* rg_override)
{
klist_t(hdrln) *rg_list = NULL;
klist_t(hdrln) *pg_list = NULL;
tbl->n_targets = translate->n_targets;
tbl->rg_trans = tbl->pg_trans = NULL;
tbl->tid_trans = (int*)calloc(translate->n_targets, 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);
// 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
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
const char *line, *end_pointer;
for (line = translate->text; *line; line = end_pointer + 1) {
end_pointer = strchr(line, '\n');
if (strncmp(line, "@CO", 3) == 0) {
if (end_pointer) {
if (kputsn(line, end_pointer - line + 1, &merged_hdr->out_co) == EOF)
goto memfail;
} else { // Last line with no trailing '\n'
if (kputs(line, &merged_hdr->out_co) == EOF) goto memfail;
if (kputc('\n', &merged_hdr->out_co) == EOF) goto memfail;
}
}
if (end_pointer == NULL) break;
}
}
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);
return -1;
}
static inline void move_kstr_to_text(char **text, kstring_t *ks) {
memcpy(*text, ks_str(ks), ks_len(ks));
*text += ks_len(ks);
**text = '\0';
free(ks_release(ks));
}
/*
* Populate a bam_hdr_t struct from data in a merged_header_t.
*/
static bam_hdr_t * finish_merged_header(merged_header_t *merged_hdr) {
size_t txt_sz;
char *text;
bam_hdr_t *hdr;
// Check output text size
txt_sz = (ks_len(&merged_hdr->out_hd)
+ ks_len(&merged_hdr->out_sq)
+ ks_len(&merged_hdr->out_rg)
+ ks_len(&merged_hdr->out_pg)
+ ks_len(&merged_hdr->out_co));
if (txt_sz >= INT32_MAX) {
fprintf(stderr, "[%s] Output header text too long\n", __func__);
return NULL;
}
// Allocate new header
hdr = bam_hdr_init();
if (hdr == NULL) goto memfail;
// Transfer targets arrays to new header
hdr->n_targets = merged_hdr->n_targets;
if (hdr->n_targets > 0) {
// Try to shrink targets arrays to correct size
hdr->target_name = realloc(merged_hdr->target_name,
hdr->n_targets * sizeof(char*));
if (!hdr->target_name) hdr->target_name = merged_hdr->target_name;
hdr->target_len = realloc(merged_hdr->target_len,
hdr->n_targets * sizeof(uint32_t));
if (!hdr->target_len) hdr->target_len = merged_hdr->target_len;
// These have either been freed by realloc() or, in the unlikely
// event that failed, have had their ownership transferred to hdr
merged_hdr->target_name = NULL;
merged_hdr->target_len = NULL;
}
else {
hdr->target_name = NULL;
hdr->target_len = NULL;
}
// Allocate text
text = hdr->text = malloc(txt_sz + 1);
if (!text) goto memfail;
// Put header text in order @HD, @SQ, @RG, @PG, @CO
move_kstr_to_text(&text, &merged_hdr->out_hd);
move_kstr_to_text(&text, &merged_hdr->out_sq);
move_kstr_to_text(&text, &merged_hdr->out_rg);
move_kstr_to_text(&text, &merged_hdr->out_pg);
move_kstr_to_text(&text, &merged_hdr->out_co);
hdr->l_text = txt_sz;
return hdr;
memfail:
perror(__func__);
bam_hdr_destroy(hdr);
return NULL;
}
/*
* 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_hd));
free(ks_release(&merged_hdr->out_sq));
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));