forked from GregoryFaust/samblaster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
samblaster.cpp
1542 lines (1397 loc) · 53.7 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
File: samblaster.cpp code file for the main routine and most of the other code.
License Information:
Copyright 2013-2015 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;
// 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(char * s1, const char * s2) __attribute__((always_inline));
inline bool streq(char * s1, const char * s2)
{
return (strcmp(s1, s2) ==0);
}
void fatalError(const char * errorStr)
{
fprintf(stderr, "%s\n", errorStr);
exit(1);
}
void fsError(const char * filename)
{
char * temp;
if (errno == ENOENT)
asprintf(&temp, "samblaster: File '%s' does not exist.\n", filename);
else
asprintf(&temp, "samblaster: File system error on %s: %d.\n", filename, errno);
fatalError(temp);
}
///////////////////////////////////////////////////////////////////////////////
// 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.
// We need to pre-define these for the SAM specific fields.
typedef UINT32 pos_t; // Type for reference offsets.
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;
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);
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.
// For now, punt.
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;
}
// 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);
}
///////////////////////////////////////////////////////////////////////////////
// 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);
}
inline pos_t str2pos (char * str)
{
return strtoul(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;
splitLine_t ** splitterArray;
int splitterArrayMaxSize;
UINT32 sigArraySize;
int minNonOverlap;
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->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));
}
delete s;
}
///////////////////////////////////////////////////////////////////////////////
// Signatures
///////////////////////////////////////////////////////////////////////////////
inline sgn_t calcSig(splitLine_t * first, splitLine_t * second)
{
// Total nonsense to get the compiler to actually work.
UINT64 t1 = first->pos;
UINT64 t2 = t1 << 32;
UINT64 final = t2 | second->pos;
return (sgn_t)final;
}
inline UINT32 calcSigArrOff(splitLine_t * first, splitLine_t * second, seqMap_t & seqs)
{
UINT32 s1 = (first->seqNum * 2) + (isReverseStrand(first) ? 1 : 0);
UINT32 s2 = (second->seqNum * 2) + (isReverseStrand(second) ? 1 : 0);
UINT32 retval = (s1 * seqs.size() * 2) + s2;
#ifdef DEBUG
fprintf(stderr, "1st %d %d -> %d 2nd %d %d -> %d count %lu result %d\n",
first->seqNum, isReverseStrand(first), s1, second->seqNum, isReverseStrand(second), s2, seqs.size(), retval);
#endif
return retval;
}
///////////////////////////////////////////////////////////////////////////////
// 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)
{
#ifdef DEBUG
seqMap_t::iterator findret = state->seqs.find(line->fields[field]);
if (findret == state->seqs.end())
{
char * temp;
asprintf(&temp, "Unable to find seq %s for readid %s in sequence map.\n", line->fields[field], line->fields[QNAME]);
fatalError(temp);
}
return findret->second;
#else
return state->seqs.find(line->fields[field])->second;
#endif
}
///////////////////////////////////////////////////////////////////////////////
// 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 calcOffsets(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 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;
}
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\n",
count, block->fields[QNAME], "samblaster: Are you sure the input is sorted by read ids?");
fatalError(temp);
}
// Some fields for statistics.
UINT64 idCount = 0;
UINT64 dupCount = 0;
UINT64 discCount = 0;
UINT64 splitCount = 0;
UINT64 unmapClipCount = 0;
UINT64 unmatedCount = 0;
// This is the main workhorse that determines if lines are dups or not.
template <bool excludeSecondaries>
int fillSplitterArray(splitLine_t * block, state_t * state, int mask, bool flagValue);
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.
bool orphan = false;
bool dummyFirst = false;
// First get rid of the useless case of having no first AND no second.
if (first == NULL && second == NULL) goto outOfHere;
// Now see if we have orphan with the unmapped read missing.
if (first == NULL || second == NULL)
{
// Get the NULL one in the first slot.
if (second == NULL) swapPtrs(&first, &second);
// If the only read says its paired, and it is unmapped or its mate is mapped, something is wrong.
if (isPaired(second) && (isUnmapped(second) || isNextMapped(second))) goto outOfHere;
// If the only read we have is unmapped, then it can't be a dup.
if (isUnmapped(second)) return;
// Now MAKE a dummy record for the first read, but don't put it into the block.
// That way we won't have to worry about it getting output, or when processing splitters etc.
// But, we will have to remember to dispose of it.
first = getSplitLine();
// Set the flag field to what it would have been.
// What if this "pair" is a singleton read?
first->flag = isFirstRead(second) ? 0x85 : 0x45;
orphan = true;
dummyFirst = true;
}
else
{
// Handle the addition of MC and MQ tags if requested.
if (state->addMateTags)
{
int mask = (FIRST_SEG | SECOND_SEG);
// Process the first of the pair.
// Get the list of reads that match the second of the pair.
int count = fillSplitterArray<false>(block, state, second->flag & mask, true);
for (int i=0; i<count; ++i)
{
splitLine_t * line = state->splitterArray[i];
addTag(line, " MC:Z:", first->fields[CIGAR]);
addTag(line, " MQ:i:", first->fields[MAPQ]);
}
// Process the second of the pair.
// Get the list of reads that match the first of the pair.
count = fillSplitterArray<false>(block, state, first->flag & mask, true);
for (int i=0; i<count; ++i)
{
splitLine_t * line = state->splitterArray[i];
addTag(line, " MC:Z:", second->fields[CIGAR]);
addTag(line, " MQ:i:", second->fields[MAPQ]);
}
}
// Never mark pairs as dups if both sides are unmapped.
if (isUnmapped(first) && isUnmapped(second)) return;
// We need to properly handle orphans to get the correct reference offsets and sequence numbers.
orphan = (isUnmapped(first) || isUnmapped(second));
// Orphan that needs to be swapped.
// We need the unmapped one in the first slot so that they won't all collide in the hash table.
if (isMapped(first) && isUnmapped(second))
{
swapPtrs(&first, &second);
}
}
// Now look for duplicates.
if (!state->acceptDups)
{
// Calculate and store the second position and sequence name.
calcOffsets(second);
second->seqNum = getSeqNum(second, RNAME, state);
if (orphan)
{
// We have an orphan, so we just zero out the pos and seqnum
first->pos = 0;
first->seqNum = 0;
}
else
{
// Not an orphan, so handle first on its own.
calcOffsets(first);
first->seqNum = getSeqNum(first, RNAME, state);
}
// The fact of which alignment is first or second in the template is not relevant for determining dups.
// Therefore, we normalize the pairs based on their characteristics.
// We have already swapped orphans.
// Otherwise, sort by pos, and if equal, sort by sequence num, then by strand.
if (!orphan && needSwap(first, second)) swapPtrs(&first, &second);
// Now find the signature of the pair.
sgn_t sig = calcSig(first, second);
// Calculate the offset into the signatures array.
UINT32 off = calcSigArrOff(first, second, state->seqs);
// Attempt insert into the sigs structure.
// The return value will tell us if it was already there.
bool insert = hashTableInsert(&(state->sigs[off]), sig);
// Check if the insertion actually happened.
if (!insert)
{
dupCount += 1;
// We always mark all or none of a block as dup.
for (splitLine_t * line = block; line != NULL; line = line->next)
{
markDup(line);
}
}
}
// If we have a dummy first, we can't have a discordant pair.
if (dummyFirst)
{
disposeSplitLines(first);
return;
}
// The first and second help us mark the discordants.
// Both sides mapped, but pair not properly aligned.
if (!orphan && isDiscordant(first))
{
first->discordant = true;
second->discordant = true;
}
return;
outOfHere:
if (state->ignoreUnmated) {unmatedCount += 1; return;}
else brokenBlock(block, count);
}
// Sort ascending in SQO.
int compQOs(const void * p1, const void * p2)
{
splitLine_t * l1 = (*(splitLine_t **)p1);
splitLine_t * l2 = (*(splitLine_t **)p2);
return (l1->SQO - l2->SQO);
}
template <bool excludeSecondaries>
int fillSplitterArray(splitLine_t * block, state_t * state, int mask, bool flagValue)
{
// Count the secondaries we have for this read (if any), and store their ptrs into an array.
int count = 0;
for (splitLine_t * line = block; line != NULL; line = line->next)
{
// For all the ones that are the current read of interest....
// Check if they are a primary or complementary alignment.
if (checkFlag(line, mask) == flagValue && !(excludeSecondaries && isSecondaryAlignment(line)))
{
// Add the ptr to this line to the sort array.
// If it won't fit, double the array size.
if (count >= state->splitterArrayMaxSize)
{
state->splitterArrayMaxSize *= 2;
state->splitterArray = (splitLine_t **)(realloc(state->splitterArray,
state->splitterArrayMaxSize * sizeof(splitLine_t *)));
}
state->splitterArray[count] = line;
count += 1;
}
}
return count;
}
void markSplitterUnmappedClipped(splitLine_t * block, state_t * state, int mask, bool flagValue)
{
// Count the secondaries we have for this read (if any), and store their ptrs into an array.
int count = fillSplitterArray<true>(block, state, mask, flagValue);
// We have the lines of interest in an array.
// Decide what to do next based on the number of reads.
if (count == 0) return;
if (count == 1)
{
if (state->unmappedClippedFile == NULL) return;
// Process unmapped or clipped.
splitLine_t * line = state->splitterArray[0];
// Unmapped or clipped alignments should be primary.
if (!isPrimaryAlignment(line)) return;
if (isUnmapped(line))
{
line->unmappedClipped = true;
}
else
{
// Process the CIGAR string.
// As this is expensive, we delay as long as possible.
calcOffsets(line);
if (line->sclip >= state->minClip || line->eclip >= state->minClip)
{
line->unmappedClipped = true;