-
Notifications
You must be signed in to change notification settings - Fork 30
/
samblaster.cpp
1919 lines (1733 loc) · 70.8 KB
/
samblaster.cpp
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
/* -*- mode: C++ ; indent-tabs-mode: nil ; c-file-style: "stroustrup" -*-
Project: samblaster
Fast mark duplicates in read-ID grouped SAM file.
Also, optionally pull discordants, splitters, and/or unmappend/clipped reads.
Author: Greg Faust ([email protected])
Date: October 2013
Cite: SAMBLASTER: fast duplicate marking and structural variant read extraction
GG Faust, IM Hall
Bioinformatics 30 (17), 2503-2505
https://academic.oup.com/bioinformatics/article/30/17/2503/2748175
File: samblaster.cpp code file for the main routine and most of the other code.
License Information:
Copyright 2013-2020 Gregory G. Faust
Licensed under the MIT license (the "License");
You may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
*/
// This define is needed for portable definition of PRIu64
#define __STDC_FORMAT_MACROS
#include <stdlib.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <map>
#include "sbhash.h"
// Rename common integer types.
// I like having these shorter name.
typedef uint64_t UINT64;
typedef uint32_t UINT32;
typedef int32_t INT32;
// Some helper routines.
// mempcpy is a GNU extension and not available everywhere.
#ifndef _GNU_SOURCE
inline void *mempcpy(void *dest, const void *src, size_t n)
{
return (char*) memcpy(dest, src, n) + n;
}
#endif
inline bool streq(const char * s1, const char * s2) __attribute__((always_inline));
inline bool streq(const char * s1, const char * s2)
{
return (strcmp(s1, s2) == 0);
}
inline bool substr_of(const char * s1, const char * s2) __attribute__((always_inline));
inline bool substr_of(const char * s1, const char * s2)
{
return (strstr(s1, s2) != NULL);
}
// Declare error handling routines defined below.
void fatalError(const char * errorStr);
void fsError(const char * filename);
///////////////////////////////////////////////////////////////////////////////
// Runtime Statistics
///////////////////////////////////////////////////////////////////////////////
// Stuff needed for timings.
// To turn timing off, set the below to 0.
#define TIMING 1
#if TIMING
// A convenience function for outputing time is seconds in a more useful metric.
void fprintTimeSeconds (FILE * out, double seconds, int precision)
{
double totalseconds = seconds;
int hours = seconds/3600.;
if (hours > 0)
{
seconds -= hours * 3600;
fprintf(out, "%dH", hours);
}
int minutes = seconds/60.;
if (minutes > 0)
{
seconds -= minutes * 60;
fprintf(out, "%dM", minutes);
}
if (hours + minutes > 0)
{
fprintf(out, "%.0fS", seconds);
fprintf(out, "(%.*fS)", precision, totalseconds);
}
else fprintf(out, "%.*fS", precision, totalseconds);
}
void fprintTimeMicroSeconds (FILE * out, UINT64 microSeconds, int precision)
{
fprintTimeSeconds(out, ((double)microSeconds/1000000.0), precision);
}
inline UINT64 diffTVs (struct timeval * startTV, struct timeval * endTV)
{
return (((endTV->tv_sec - startTV->tv_sec) * 1000000) + (endTV->tv_usec - startTV->tv_usec));
}
#include <sys/times.h>
#include <sys/resource.h>
#include <time.h>
#endif // TIMING
///////////////////////////////////////////////////////////////////////////////
// Split Lines
///////////////////////////////////////////////////////////////////////////////
// The structure to store "split" input lines, especially SAM lines.
// They form a singly linked list so that we can form groups of them,
// and also so that we can keep a freelist of them.
// Reference offsets (pos) can be negative or run off the end of a contig due to clipping.
// Therefore, we will use a padding strategy.
// The space allocated to each contig will be padded by twice the max read length.
// This leaves room for both offset underflow and overflow.
// And all offsets will be shifted higher by the max read length.
// This will eliminate negative offsets and "center" offsets within the offset range for the contig.
typedef INT32 pos_t;
// We need to pre-define these for the SAM specific fields.
typedef UINT64 sgn_t; // Type for signatures for offsets and lengths.
// And the type itself for the next pointer.
typedef struct splitLine splitLine_t;
splitLine_t * splitLineFreeList = NULL;
struct splitLine
{
// General fields for any split line.
splitLine_t * next;
char * buffer;
int bufLen;
size_t maxBufLen;
char **fields;
int numFields;
int maxFields;
bool split;
// Special SAM fields that we need to access as other than strings.
// It this were a class, these would be in a subclass.
int flag;
pos_t pos;
int seqNum;
pos_t binPos;
int binNum;
int SQO;
int EQO;
int sclip;
int eclip;
int rapos;
int raLen;
int qaLen;
bool CIGARprocessed;
bool discordant;
bool splitter;
bool unmappedClipped;
};
// Creator for splitLine
splitLine_t * makeSplitLine()
{
splitLine_t * line = (splitLine_t *)malloc(sizeof(splitLine_t));
line->bufLen = 0;
line->maxBufLen = 1000;
line->buffer = (char *)malloc(line->maxBufLen+1);
line->numFields = 0;
line->maxFields = 100;
line->fields = (char **)malloc(line->maxFields * sizeof(char *));
return line;
}
// Destructor for split line.
void deleteSplitLine(splitLine_t * line)
{
free(line->buffer);
free(line->fields);
free(line);
}
// Descructor for a list of splitLines
void cleanUpSplitLines()
{
splitLine_t * l = splitLineFreeList;
while (l != NULL)
{
splitLine_t * next = l->next;
deleteSplitLine(l);
l = next;
}
}
// Like descructor for splitLine except don't free memory.
// Instead, put the linked list of objects back on the free list.
void disposeSplitLines(splitLine_t * line)
{
// First find the last line in the list.
// Then get rid of them all.
splitLine_t * last = line;
for (splitLine_t * l = line->next; l!=NULL; l = l->next) last = l;
last->next = splitLineFreeList;
splitLineFreeList = line;
}
// Like constuctor, except take struct off free list if there is one.
splitLine_t * getSplitLine()
{
splitLine_t * line;
if (splitLineFreeList == NULL)
{
line = makeSplitLine();
}
else
{
line = splitLineFreeList;
splitLineFreeList = splitLineFreeList->next;
}
line->next = NULL;
line->CIGARprocessed = false;
// Mark these here so that the code for these doesn't have to stand on its head to do it.
line->discordant = false;
line->splitter = false;
line->unmappedClipped = false;
return line;
}
// Split the line into fields.
void splitSplitLine(splitLine_t * line, int maxSplits)
{
line->numFields = 0;
int fieldStart = 0;
// replace the newline with a tab so that it works like the rest of the fields.
line->buffer[line->bufLen-1] = '\t';
for (int i=0; i<line->bufLen; ++i)
{
if (line->buffer[i] == '\t')
{
line->fields[line->numFields] = line->buffer + fieldStart;
line->numFields += 1;
if (line->numFields == maxSplits) break;
line->buffer[i] = 0;
// Get ready for the next iteration.
fieldStart = i+1;
}
}
// replace the tab at the end of the line with a null char to terminate the final string.
line->buffer[line->bufLen-1] = 0;
line->split = true;
}
// Unsplit the fields back into a single string.
// This will mung the strings, so only call this when all processing on the line is done.
void unsplitSplitLine(splitLine_t * line)
{
// First make sure we are still split.
if (!line->split) return;
// First undo the splits.
// We will undo the splits backwards from the next field to avoid having to calculate strlen each time.
for (int i=1; i<line->numFields; ++i)
{
line->fields[i][-1] = '\t';
}
// Now put the newline back in.
line->buffer[line->bufLen-1] = '\n';
// Mark as no longer split.
line->split = false;
}
// Resize the buffer of a splitLine.
// Since the new buffer may not be in the same place, we need to first unsplit, resize, then resplit.
void resizeSplitLine(splitLine_t * line, int newsize)
{
// First unsplit it.
unsplitSplitLine(line);
// Resize the buffer, giving a little extra room.
line->maxBufLen = newsize + 50;
line->buffer = (char *)realloc(line->buffer, line->maxBufLen);
if (line->buffer == NULL)
{
fatalError("samblaster: Failed to reallocate to a larger read buffer size.\n");
}
// Now resplit the line.
splitSplitLine(line, line->numFields);
}
// Change a field into a value.
// This will be tough given how we output lines.
// So, we might have to try a few things.
// Start with simply expanding/contracting the string to put in the new value.
void changeFieldSplitLine(splitLine_t * line, int fnum, char * newValue)
{
// What we do will depend on the lengths of the two strings.
// So, start by calculaing these only once.
char * fp = line->fields[fnum];
int oldLen = strlen(fp);
int newLen = strlen(newValue);
// Now see if we need to first change the length of the whole line.
int move = newLen - oldLen;
if (move != 0)
{
// This should never happen, but to be robust we need to check.
// It is messy to fix it, as all the field ptrs will now be wrong.
if ((size_t)(line->bufLen + move) >= line->maxBufLen)
{
resizeSplitLine(line, line->bufLen + move);
fp = line->fields[fnum];
}
// Calculate the size of the tail that is still needed.
int distance = 1 + line->bufLen - (fp - line->buffer) - oldLen;
// Do the copy.
memmove(fp+newLen, fp+oldLen, distance);
// Correct the total length of the buffer.
line->bufLen += move;
// We need to correct the other ptrs as well.
for (int i=fnum+1; i<line->numFields; i++) line->fields[i] += move;
}
// Copy in the new value.
memcpy(fp, newValue, newLen);
}
void addTag(splitLine_t * line, const char * header, const char * val)
{
int hl = strlen(header);
int vl = strlen(val);
// Make sure everything will fit.
int newlen = line->bufLen + hl + vl;
if ((size_t)newlen >= line->maxBufLen)
{
resizeSplitLine(line, newlen);
}
// Copy over the header and the value.
char * ptr = line->buffer + line->bufLen - 1;
ptr = (char *)mempcpy(ptr, header, hl);
ptr = (char *)mempcpy(ptr, val, vl);
// Add the null terminator for the field, and for the record.
ptr[0] = 0;
ptr[1] = 0;
// Fix the buffer length.
line->bufLen = newlen;
}
#if 0
// This was originally written to test for mismatched MC tags between BWA MEM and samblaster.
// I keep it around, as some version of this would be useful if/when we add support for RGs and/or UMIs.
// Note that this conses up a string, so the caller will have to free it later to avoid a leak.
char * getTagVal (char * tags, char * tagID)
{
char * startptr = NULL;
char * endptr = NULL;
char * retval = NULL;
// Find the start and end of the tag field
startptr = strstr(tags, tagID);
if (startptr == NULL) return strdup("");
endptr = strchr(startptr, '\t');
if (endptr == NULL) endptr = strchr(startptr, 0);
// temporarily put a null in for the delimiter
char save = endptr [0];
endptr [0] = 0;
retval = strdup (startptr+strlen(tagID));
endptr [0] = save;
// Return the dupped string
return retval;
}
#endif
// Read a line from the file and split it.
splitLine_t * readLine(FILE * input)
{
splitLine_t * sline = getSplitLine();
sline->bufLen = getline(&sline->buffer, &sline->maxBufLen, input);
if (sline->bufLen < 1)
{
disposeSplitLines(sline);
return NULL;
}
splitSplitLine(sline, 12);
return sline;
}
inline void outputString(char * str, FILE * output)
{
// Do the error checking here so we don't have to do it elsewhere.
if (fputs(str, output) < 0)
{
fatalError("samblaster: Unable to write to output file.\n");
}
}
// Output the line.
inline void writeLine(splitLine_t * line, FILE * output)
{
unsplitSplitLine(line);
outputString(line->buffer, output);
}
// Check the first line of a file (e.g. input) for bam signature.
void checkBAMfile(splitLine_t * line)
{
// If the file is a bam file, we can't rely on fields.
// So, look at the underlying buffer for the line.
// First define the signature to look for.
int values[] = {31, -117, 8, 4, 66, 67, 2};
int offsets[] = {0, 1, 2, 3, 12, 13, 14};
int count = 7;
// Check for empty file or likely a sam file with a header.
// This is necessary, as the @HD line may not be long enough to check for the BAM signature.
if (line == NULL) fatalError("samblaster: Input file is empty. Exiting.\n");
if (line->buffer[0] == '@') return;
// If a SAM file has no header, an alignment row should easily be long enough.
if (line->bufLen <= offsets[count-1]) fatalError("samblaster: Input file is empty. Exiting.\n");
// Check for the BAM signature.
for (int i=0; i<count; i++)
{
if ((int)line->buffer[offsets[i]] != values[i]) return;
}
// If we are here, we almost certainly have a bamfile.
fatalError("samblaster: Input file appears to be in BAM format. SAM input is required. Exiting.\n");
}
///////////////////////////////////////////////////////////////////////////////
// SAM and signature set related structures.
///////////////////////////////////////////////////////////////////////////////
// Define SAM field offsets.
#define QNAME 0
#define FLAG 1
#define RNAME 2
#define POS 3
#define MAPQ 4
#define CIGAR 5
#define RNEXT 6
#define PNEXT 7
#define TLEN 8
#define SEQ 9
#define QUAL 10
#define TAGS 11
// Define SAM flag accessors.
#define MULTI_SEGS 0x1
#define FIRST_SEG 0x40
#define SECOND_SEG 0x80
inline bool checkFlag(splitLine_t * line, int bits) { return ((line->flag & bits) != 0); }
inline void setFlag(splitLine_t * line, int bits) { line->flag |= bits; }
inline bool isPaired(splitLine_t * line) { return checkFlag(line, MULTI_SEGS); }
inline bool isConcordant(splitLine_t * line) { return checkFlag(line, 0x2); }
inline bool isDiscordant(splitLine_t * line) { return !isConcordant(line); }
inline bool isUnmapped(splitLine_t * line) { return checkFlag(line, 0x4); }
inline bool isNextUnmapped(splitLine_t * line) { return checkFlag(line, 0x8); }
inline bool isNextMapped(splitLine_t * line) { return !isNextUnmapped(line); }
inline bool isMapped(splitLine_t * line) { return !isUnmapped(line); }
inline bool isReverseStrand(splitLine_t * line) { return checkFlag(line, 0x10); }
inline bool isForwardStrand(splitLine_t * line) { return !isReverseStrand(line); }
inline bool isFirstRead(splitLine_t * line) { return checkFlag(line, FIRST_SEG); }
inline bool isSecondRead(splitLine_t * line) { return checkFlag(line, SECOND_SEG); }
// These determine alignment type.
// Things may get more complicated than this once we have alternate contigs such as in build 38 of human genome.
inline bool isPrimaryAlignment(splitLine_t * line)
{ return !(checkFlag(line, 0x100) || checkFlag(line, 0x800)); }
// We have to hande secondard and complementary alignments differently depending on compatMode.
// So, we store which bits are being included in each.
int complementaryBits = 0x800;
inline bool isComplementaryAlignment(splitLine_t * line)
{ return checkFlag(line, complementaryBits); }
int secondaryBits = 0x100;
inline bool isSecondaryAlignment(splitLine_t * line)
{ return checkFlag(line, secondaryBits); }
inline bool isDuplicate(splitLine_t * line) { return checkFlag(line, 0x400); }
inline void setDuplicate(splitLine_t * line) { setFlag(line, 0x400); }
typedef hashTable_t sigSet_t;
inline int str2int (char * str)
{
return strtol(str, NULL, 0);
}
// Need to change this if pos is unsigned.
inline pos_t str2pos (char * str)
{
return strtol(str, NULL, 0);
}
// Temp buffer to use to form new flag field when marking dups.
char tempBuf[10];
inline void markDup(splitLine_t * line)
{
setDuplicate(line);
sprintf(tempBuf, "%d", line->flag);
changeFieldSplitLine(line, FLAG, tempBuf);
}
// Special version of write line that appends an id number to the output.
// Used to output splitters.
void writeSAMlineWithIdNum(splitLine_t * line, FILE * output)
{
// Unsplit the line.
unsplitSplitLine(line);
// Split it two ways to isolate the id field.
splitSplitLine(line, 2);
outputString(line->fields[0], output);
if (isPaired(line)) fprintf(output, "_%d\t", isFirstRead(line) ? 1 : 2);
else fprintf(output, "\t");
outputString(line->fields[1], output);
fprintf(output, "\n");
}
///////////////////////////////////////////////////////////////////////////////
// Sequence Map
///////////////////////////////////////////////////////////////////////////////
// We use a map instead of a hash map for sequence names.
// This is because the default hash function on char * hashes the ptr values.
// So, we would need to define our own hash on char * to get things to work properly.
// Not worth it for a structure holding so few members.
// Function needed to get char * map to work.
struct less_str
{
bool operator()(char const *a, char const *b) const
{
return strcmp(a, b) < 0;
}
};
// This stores the map between sequence names and sequence numbers.
typedef std::map<const char *, int, less_str> seqMap_t;
inline void addSeq(seqMap_t * seqs, char * item, int val)
{
(*seqs)[item] = val;
}
///////////////////////////////////////////////////////////////////////////////
// Struct for processing state
///////////////////////////////////////////////////////////////////////////////
struct state_struct
{
char * inputFileName;
FILE * inputFile;
char * outputFileName;
FILE * outputFile;
FILE * discordantFile;
char * discordantFileName;
FILE * splitterFile;
char * splitterFileName;
FILE * unmappedClippedFile;
char * unmappedClippedFileName;
sigSet_t * sigs;
seqMap_t seqs;
UINT32 * seqLens;
UINT64 * seqOffs;
splitLine_t ** splitterArray;
int splitterArrayMaxSize;
UINT32 sigArraySize;
int binCount;
int minNonOverlap;
int maxReadLength;
int maxSplitCount;
int minIndelSize;
int maxUnmappedBases;
int minClip;
int unmappedFastq;
bool acceptDups;
bool excludeDups;
bool removeDups;
bool addMateTags;
bool compatMode;
bool ignoreUnmated;
bool quiet;
};
typedef struct state_struct state_t;
state_t * makeState ()
{
state_t * s = new state_t();
s->inputFile = stdin;
s->inputFileName = (char *)"stdin";
s->outputFile = stdout;
s->outputFileName = (char *)"stdout";
s->discordantFile = NULL;
s->discordantFileName = (char *)"";
s->splitterFile = NULL;
s->splitterFileName = (char *)"";
s->unmappedClippedFile = NULL;
s->unmappedClippedFileName = (char *)"";
s->sigs = NULL;
s->minNonOverlap = 20;
s->maxSplitCount = 2;
s->minIndelSize = 50;
s->maxUnmappedBases = 50;
s->minClip = 20;
s->maxReadLength = 500;
s->acceptDups = false;
s->excludeDups = false;
s->removeDups = false;
s->addMateTags = false;
s->compatMode = false;
s->ignoreUnmated = false;
s->quiet = false;
// Start this as -1 to indicate we don't know yet.
// Once we are outputting our first line, we will decide.
s->unmappedFastq = -1;
// Used as a temporary location for ptrs to splitter for sort routine.
s->splitterArrayMaxSize = 1000;
s->splitterArray = (splitLine_t **)(malloc(s->splitterArrayMaxSize * sizeof(splitLine_t *)));
return s;
}
void deleteState(state_t * s)
{
free(s->splitterArray);
if (s->sigs != NULL)
{
// delete[] s->sigs;
for (UINT32 i=0; i<s->sigArraySize; i++) deleteHashTable(&(s->sigs[i]));
free (s->sigs);
}
for (seqMap_t::iterator iter = s->seqs.begin(); iter != s->seqs.end(); ++iter)
{
free((char *)(iter->first));
}
if (s->seqLens != NULL) free(s->seqLens);
if (s->seqOffs != NULL) free(s->seqOffs);
delete s;
}
///////////////////////////////////////////////////////////////////////////////
// Signatures
///////////////////////////////////////////////////////////////////////////////
// We now calculate signatures as offsets into a super contig that includes the entire genome.
// And partition it into equaly sized bins.
// This performs better on genomes with large numbers of small contigs,
// without performance degradation on more standard genomes.
// Thanks to https://github.com/carsonhh for the suggestion.
/////////////////////////////////////////////////////////////////////////////
template <bool orphan>
inline sgn_t calcSig(splitLine_t * first, splitLine_t * second)
{
UINT64 final;
if (orphan)
{
// For an orphan, we only use information fron the second read.
final = second->binPos;
}
else
{
// Total nonsense to get the compiler to actually work.
UINT64 t1 = first->binPos;
UINT64 t2 = t1 << 32;
final = t2 | second->binPos;
}
return (sgn_t)final;
}
template <bool orphan>
inline UINT32 calcSigArrOff(splitLine_t * first, splitLine_t * second, int binCount)
{
UINT32 s1, s2;
if (orphan)
{
// For orphans, we only use the binNum of the second, and treat it as if on the forward strand.
s1 = 0;
s2 = (second->binNum * 2);
}
else
{
s1 = (first->binNum * 2) + (isReverseStrand(first) ? 1 : 0);
s2 = (second->binNum * 2) + (isReverseStrand(second) ? 1 : 0);
}
return (UINT32)(s1 * binCount * 2) + s2;
}
///////////////////////////////////////////////////////////////////////////////
// Sequences
///////////////////////////////////////////////////////////////////////////////
inline int getSeqNum(splitLine_t * line, int field, state_t * state) __attribute__((always_inline));
inline int getSeqNum(splitLine_t * line, int field, state_t * state)
{
seqMap_t::iterator findret = state->seqs.find(line->fields[field]);
if (findret == state->seqs.end())
{
char * temp;
asprintf(&temp, "samblaster: Unable to find sequence '%s' in sequence map for readid %s\n", line->fields[field], line->fields[QNAME]);
fatalError(temp);
}
return findret->second;
}
///////////////////////////////////////////////////////////////////////////////
// Helpers to process CIGAR strings
///////////////////////////////////////////////////////////////////////////////
// This will parse a base 10 int, and change ptr to one char beyond the end of the number.
inline int parseNextInt(char **ptr)
{
int num = 0;
for (char curChar = (*ptr)[0]; curChar != 0; curChar = (++(*ptr))[0])
{
int digit = curChar - '0';
if (digit >= 0 && digit <= 9) num = num*10 + digit;
else break;
}
return num;
}
// This will the current char, and move the ptr ahead by one.
inline char parseNextOpCode(char **ptr)
{
return ((*ptr)++)[0];
}
// This just test for end of string.
inline bool moreCigarOps(char *ptr)
{
return (ptr[0] != 0);
}
void processCIGAR(splitLine_t * line)
{
if (line->CIGARprocessed) return;
char * cigar = line->fields[CIGAR];
line->raLen = 0;
line->qaLen = 0;
line->sclip = 0;
line->eclip = 0;
bool first = true;
while (moreCigarOps(cigar))
{
int opLen = parseNextInt(&cigar);
char opCode = parseNextOpCode(&cigar);
if (opCode == 'M' || opCode == '=' || opCode == 'X')
{
line->raLen += opLen;
line->qaLen += opLen;
first = false;
}
else if (opCode == 'S' || opCode == 'H')
{
if (first) line->sclip += opLen;
else line->eclip += opLen;
}
else if (opCode == 'D' || opCode == 'N')
{
line->raLen += opLen;
}
else if (opCode == 'I')
{
line->qaLen += opLen;
}
else
{
fprintf(stderr, "Unknown opcode '%c' in CIGAR string: '%s'\n", opCode, line->fields[CIGAR]);
}
}
line->rapos = str2pos(line->fields[POS]);
if (isForwardStrand(line))
{
line->pos = line->rapos - line->sclip;
line->SQO = line->sclip;
line->EQO = line->sclip + line->qaLen - 1;
}
else
{
line->pos = line->rapos + line->raLen + line->eclip - 1;
line->SQO = line->eclip;
line->EQO = line->eclip + line->qaLen - 1;
}
line->CIGARprocessed = true;
}
inline int getStartDiag(splitLine_t * line)
{
// SRO - SQO (not strand normalized)
// Simplify the following.
// return (str2pos(line->fields[POS])) - line->sclip;
return line->rapos - line->sclip;
}
inline int getEndDiag(splitLine_t * line)
{
// ERO - EQO (not strand normalized)
// Simplify the following
// return (line->rapos + line->raLen - 1) - (line->sclip + line->qaLen - 1)
return (line->rapos + line->raLen) - (line->sclip + line->qaLen);
}
///////////////////////////////////////////////////////////////////////////////
// Process SAM Blocks
///////////////////////////////////////////////////////////////////////////////
// This was historically 27 bits as that was large enough to hold any human chrom 1 offset.
// Now that we are using a synthetic genome representation, 27 has no special meaning.
// There are interesting space/time trade-offs between how large we make the
// synthetic chroms and how large the various hash tables become.
// If/when we handle RGs and/or UMIs, the signature scheme will change anyway.
// Therefore, leave at 27 for now to match space/time tradeoffs of earlier releases.
#define BIN_SHIFT ((UINT64)27) //bin window is 27 bits wide
#define BIN_MASK ((UINT64)((1 << BIN_SHIFT)-1)) //bin window is 27 bits wide
// This is apparently no longer called.
void outputSAMBlock(splitLine_t * block, FILE * output)
{
for (splitLine_t * line = block; line != NULL; line = line->next)
{
writeLine(line, output);
}
disposeSplitLines(block);
}
inline bool needSwap(splitLine_t * first, splitLine_t * second)
{
// Sort first by ref offset.
if (first->pos > second->pos) return true;
if (first->pos < second->pos) return false;
// Now by seq number.
if (first->seqNum > second->seqNum) return true;
if (first->seqNum < second->seqNum) return false;
// Now by strand.
// If they are both the same strand, it makes no difference which on is first.
if (isReverseStrand(first) == isReverseStrand(second)) return false;
if (isReverseStrand(first) && isForwardStrand(second)) return true;
return false;
}
inline void swapPtrs(splitLine_t ** first, splitLine_t ** second)
{
splitLine_t * temp = *first;
*first = *second;
*second = temp;
}
template <bool excludeSecondaries>
int fillTempLineArray(splitLine_t * block, state_t * state, int mask, bool flagValue);
void addMTs(splitLine_t * block, state_t * state, splitLine_t * first, splitLine_t * second)
{
if (!isMapped(first)) return;
int mask = (FIRST_SEG | SECOND_SEG);
// Get the list of reads that match the other read of the pair.
int count = fillTempLineArray<false>(block, state, second->flag & mask, true);
for (int i=0; i<count; ++i)
{
splitLine_t * line = state->splitterArray[i];
if (!substr_of(line->fields[TAGS], "MC:Z:")) addTag(line, " MC:Z:", first->fields[CIGAR]);
if (!substr_of(line->fields[TAGS], "MQ:i:")) addTag(line, " MQ:i:", first->fields[MAPQ]);
}
}
void brokenBlock(splitLine_t *block, int count)
{
char * temp;
asprintf(&temp, "samblaster: Can't find first and/or second of pair in sam block of length %d for id: %s\n%s%s:%s\n%s",
count, block->fields[QNAME], "samblaster: At location: ", block->fields[RNAME], block->fields[POS],
"samblaster: Are you sure the input is sorted by read ids?");
fatalError(temp);
}
// Some fields for statistics.
// In order to form a partition of all the reads (i.e. account for all ids)
// we need weird categories such as noPrimary, and unmapped orphans.
UINT64 idCount = 0;
UINT64 dupCount = 0;
UINT64 noPrimaryIdCount = 0;
UINT64 bothUnmappedIdCount = 0;
UINT64 unmappedOrphanIdCount = 0;
UINT64 mappedOrphanIdCount = 0;
UINT64 orphanDupCount = 0;
UINT64 bothMappedDupCount = 0;
UINT64 bothMappedIdCount = 0;
UINT64 discCount = 0;
UINT64 splitCount = 0;
UINT64 unmapClipCount = 0;
UINT64 unmatedCount = 0;
UINT64 readTooLongCount = 0;
INT32 readTooLongMax = 0;
// We also make the state (and timing info) global to aid error processing
state_t * state;
#ifdef TIMING
time_t startTime;
struct timeval startRUTime;
#endif
// The routines to do implement our padding strategy, as needed directly below.
inline int padLength(int length, state_t * state) __attribute__((always_inline));
inline int padLength(int length, state_t * state)
{
return length + (2 * state->maxReadLength);
}
inline int padPos(int pos, state_t * state) __attribute__((always_inline));
inline int padPos(int pos, state_t * state)
{
return pos + state->maxReadLength;
}
// This calculates the position of the read in the sequence array, and in the reference genome.
void prepareSigValues(splitLine_t * line, state_t * state, bool orphan)
{
// Calculate and store the reference sequence name and sequence relative position.
processCIGAR(line);
// Calculate the full query length, which is the aligned length plus clips.
int fullqlen = (line->sclip + line->qaLen + line->eclip);
// Make sure we don't have any problems with this read longer than our padding will handle.
if (fullqlen > state->maxReadLength)
{
// The read is longer than our padding will handle.
readTooLongCount += 1;
if (fullqlen > readTooLongMax) readTooLongMax = fullqlen;
// We should only ever miss the bins entirely if the read is longer than maxReadLength due to our padding of the reference.
if (line->binNum < 0 || line->binNum > state->binCount)
{
char * temp;
asprintf(&temp, "samblaster: Calculated read position falls outside the reference for read id: %s\n"
"samblaster: Consider rerunning with higher --maxReadLength.\n", line->fields[QNAME]);
fatalError(temp);
}
}
if (orphan && isReverseStrand(line))
{
// We want to treat this read as if it is on the forward strand.
line->pos = line->rapos - line->sclip;
}
// Now get the sequence number
line->seqNum = getSeqNum(line, RNAME, state);
// Calculate the genome relative position
// We need to do the read pos padding to handle negative calculated sequence position for the alignment.
UINT64 seqOff = state->seqOffs[line->seqNum];
int paddedPos = padPos(line->pos, state);
line->binNum = (seqOff + paddedPos) >> BIN_SHIFT;
line->binPos = (seqOff + paddedPos) & BIN_MASK;
}
// This is the main workhorse that determines if lines are dups or not.
void markDupsDiscordants(splitLine_t * block, state_t * state)
{
splitLine_t * first = NULL;
splitLine_t * second = NULL;
int count = 0;
for (splitLine_t * line = block; line != NULL; line = line->next)
{
count += 1;
// Do this conversion once and store the result.
line->flag = str2int(line->fields[FLAG]);
// We make our duplicate decisions based solely on primary alignments.
if (!isPrimaryAlignment(line)) continue;
// Allow unpaired reads to go through (as the second so that signature is correct).
// According to the SAM spec, this must be checked first.
if (!isPaired(line)) second = line;
// Figure out if this is the first half or second half of a pair.
else if (isFirstRead(line)) first = line;
else if (isSecondRead(line)) second = line;
}
// Figure out what type of "pair" we have.
// First get rid of the useless case of having no first AND no second.
if (first == NULL && second == NULL)
{
if (state->ignoreUnmated)