-
Notifications
You must be signed in to change notification settings - Fork 67
/
BaseAligner.cpp
2710 lines (2296 loc) · 120 KB
/
BaseAligner.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
/*++
Module Name:
BaseAligner.cpp
Abstract:
Single-end aligner
Authors:
Bill Bolosky, August, 2011
Environment:
User mode service.
This class is NOT thread safe. It's the caller's responsibility to ensure that
at most one thread uses an instance at any time.
Revision History:
Adapted from Matei Zaharia's Scala implementation.
--*/
#include "stdafx.h"
#include "BaseAligner.h"
#include "Compat.h"
#include "LandauVishkin.h"
#include "BigAlloc.h"
#include "mapq.h"
#include "SeedSequencer.h"
#include "exit.h"
#include "AlignerOptions.h"
#include "Error.h"
using std::min;
// #define TRACE_ALIGNER 1
#define EXACT_DISJOINT_MISS_COUNT 1
#ifdef TRACE_ALIGNER // If you turn this on, then stdout writing won't work.
#define TRACE printf
#else
#define TRACE(...) {}
#endif
BaseAligner::BaseAligner(
GenomeIndex *i_genomeIndex,
unsigned i_maxHitsToConsider,
unsigned i_maxK,
unsigned i_maxReadSize,
unsigned i_maxSeedsToUseFromCommandLine,
double i_maxSeedCoverage,
unsigned i_minWeightToCheck,
unsigned i_extraSearchDepth,
bool i_noUkkonen,
bool i_noOrderedEvaluation,
bool i_noTruncation,
bool i_useAffineGap,
bool i_ignoreAlignmentAdjustmentsForOm,
bool i_altAwareness,
bool i_emitALTAlignments,
int i_maxScoreGapToPreferNonAltAlignment,
int i_maxSecondaryAlignmentsPerContig,
LandauVishkin<1>*i_landauVishkin,
LandauVishkin<-1>*i_reverseLandauVishkin,
unsigned i_matchReward,
unsigned i_subPenalty,
unsigned i_gapOpenPenalty,
unsigned i_gapExtendPenalty,
unsigned i_fivePrimeEndBonus,
unsigned i_threePrimeEndBonus,
AlignerStats *i_stats,
BigAllocator *allocator) :
genomeIndex(i_genomeIndex), maxHitsToConsider(i_maxHitsToConsider), maxK(i_maxK),
maxReadSize(i_maxReadSize), maxSeedsToUseFromCommandLine(i_maxSeedsToUseFromCommandLine),
maxSeedCoverage(i_maxSeedCoverage), readId(-1), extraSearchDepth(i_extraSearchDepth),
explorePopularSeeds(false), stopOnFirstHit(false), stats(i_stats),
noUkkonen(i_noUkkonen), noOrderedEvaluation(i_noOrderedEvaluation), noTruncation(i_noTruncation),
useAffineGap(i_useAffineGap), matchReward(i_matchReward), subPenalty(i_subPenalty),
gapOpenPenalty(i_gapOpenPenalty), gapExtendPenalty(i_gapExtendPenalty),
minWeightToCheck(max(1u, i_minWeightToCheck)), maxSecondaryAlignmentsPerContig(i_maxSecondaryAlignmentsPerContig),
alignmentAdjuster(i_genomeIndex->getGenome()), ignoreAlignmentAdjustmentsForOm(i_ignoreAlignmentAdjustmentsForOm),
altAwareness(i_altAwareness), emitALTAlignments(i_emitALTAlignments),
maxScoreGapToPreferNonAltAlignment(i_maxScoreGapToPreferNonAltAlignment)
/*++
Routine Description:
Constructor for the BaseAligner class. Aligners align reads against an indexed genome.
Arguments:
i_genomeIndex - The index against which to do the alignments
i_maxHitsToConsider - The maximum number of hits to use from a seed lookup. Any lookups that return more
than this are ignored.
i_maxK - The largest string difference to consider for any comparison.
i_maxReadSize - Bound on the number of bases in any read. There's no reason to make it tight, it just affects a little memory allocation.
i_maxSeedsToUse - The maximum number of seeds to use when aligning any read (not counting ones ignored because they resulted in too many
hits). Once we've looked up this many seeds, we just score what we've got.
i_maxSeedCoverage - The maximum number of seeds to use expressed as readSize/seedSize
i_extraSearchDepth - How deeply beyond bestScore do we search?
i_noUkkonen - Don't use Ukkonen's algorithm (i.e., don't reduce the max edit distance depth as we score candidates)
i_noOrderedEvaluation-Don't order evaluating the reads by the hit count in order to drive down the max edit distance more quickly
i_noTruncation - Don't truncate searches based on count of disjoint seed misses
i_useAffineGap - Use affine gap scoring for seed extension
i_ignoreAlignmentAdjustmentsForOm - When a read score is adjusted because of soft clipping for being near the end of a contig, don't use the adjusted score when computing what to keep for -om
i_maxSecondaryAlignmentsPerContig - Maximum secondary alignments per contig; -1 means don't limit this
i_landauVishkin - an externally supplied LandauVishkin string edit distance object. This is useful if we're expecting repeated computations and use the LV cache.
i_reverseLandauVishkin - the same for the reverse direction.
i_matchReward - affine gap score for a match
i_subPenalty - affine gap score for a substitution
i_gapOpenPenalty - affine gap cost for opening a gap (indel)
i_gapExtendPenalty - affine gap cost for extending a gap (indel)
i_altAwareness - treat reads mapped to ALT contigs differently than normal ones
i_stats - an object into which we report out statistics
allocator - an allocator that's used to allocate our local memory. This is useful for TLB optimization. If this is supplied, the caller
is responsible for deallocation, we'll not deallocate any dynamic memory in our destructor.
--*/
{
hadBigAllocator = allocator != NULL;
nHashTableLookups = 0;
nLocationsScored = 0;
nHitsIgnoredBecauseOfTooHighPopularity = 0;
nReadsIgnoredBecauseOfTooManyNs = 0;
nIndelsMerged = 0;
genome = genomeIndex->getGenome();
seedLen = genomeIndex->getSeedLength();
doesGenomeIndexHave64BitLocations = genomeIndex->doesGenomeIndexHave64BitLocations();
probDistance = new ProbabilityDistance(SNP_PROB, GAP_OPEN_PROB, GAP_EXTEND_PROB); // Match Mason
if ((i_landauVishkin == NULL) != (i_reverseLandauVishkin == NULL)) {
WriteErrorMessage("Must supply both or neither of forward & reverse Landau-Vishkin objects. You tried exactly one.\n");
soft_exit(1);
}
if (i_subPenalty > (i_gapOpenPenalty + i_gapExtendPenalty)) {
WriteErrorMessage("Substitutions may be penalized too high to be seen in alignments. Make sure subPenalty < gapOpen + gapExtend\n");
soft_exit(1);
}
if (i_landauVishkin == NULL) {
if (allocator) {
landauVishkin = new (allocator) LandauVishkin<>;
reverseLandauVishkin = new (allocator) LandauVishkin<-1>;
} else {
landauVishkin = new LandauVishkin<>;
reverseLandauVishkin = new LandauVishkin<-1>;
}
ownLandauVishkin = true;
} else {
landauVishkin = i_landauVishkin;
reverseLandauVishkin = i_reverseLandauVishkin;
ownLandauVishkin = false;
}
if (allocator) {
// affineGap = new (allocator) AffineGap<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty);
// reverseAffineGap = new (allocator) AffineGap<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty);
affineGap = new (allocator) AffineGapVectorized<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty, i_fivePrimeEndBonus, i_threePrimeEndBonus);
reverseAffineGap = new (allocator) AffineGapVectorized<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty, i_fivePrimeEndBonus, i_threePrimeEndBonus);
} else {
// affineGap = new AffineGap<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty);
// reverseAffineGap = new AffineGap<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty);
affineGap = new AffineGapVectorized<>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty, i_fivePrimeEndBonus, i_threePrimeEndBonus); // This is a bad idea, it'll result in false sharing in the single-end aligner. Use BigAlloc().
reverseAffineGap = new AffineGapVectorized<-1>(i_matchReward, i_subPenalty, i_gapOpenPenalty, i_gapExtendPenalty, i_fivePrimeEndBonus, i_threePrimeEndBonus);
}
unsigned maxSeedsToUse;
if (0 != maxSeedsToUseFromCommandLine) {
maxSeedsToUse = maxSeedsToUseFromCommandLine;
} else {
maxSeedsToUse = (int)(maxSeedCoverage * maxReadSize / genomeIndex->getSeedLength());
}
numWeightLists = maxSeedsToUse + 1;
candidateHashTablesSize = (maxHitsToConsider * maxSeedsToUse * 3)/2; // *1.5 for hash table slack
hashTableElementPoolSize = maxHitsToConsider * maxSeedsToUse * 2 ; // *2 for RC
if (allocator) {
rcReadData = (char *)allocator->allocate(sizeof(char) * maxReadSize * 2); // The *2 is to allocte space for the quality string
} else {
rcReadData = (char *)BigAlloc(sizeof(char) * maxReadSize * 2); // The *2 is to allocte space for the quality string
}
rcReadQuality = rcReadData + maxReadSize;
if (allocator) {
reversedRead[FORWARD] = (char *)allocator->allocate(sizeof(char) * maxReadSize * 4 + 2 * MAX_K); // Times 4 to also hold RC version and genome data (+2MAX_K is for genome data)
} else {
reversedRead[FORWARD] = (char *)BigAlloc(sizeof(char) * maxReadSize * 4 + 2 * MAX_K); // Times 4 to also hold RC version and genome data (+2MAX_K is for genome data)
}
// treat everything but ACTG like N
for (unsigned i = 0; i < 256; i++) {
nTable[i] = 1;
rcTranslationTable[i] = 'N';
}
reversedRead[RC] = reversedRead[FORWARD] + maxReadSize;
rcTranslationTable['A'] = 'T';
rcTranslationTable['G'] = 'C';
rcTranslationTable['C'] = 'G';
rcTranslationTable['T'] = 'A';
rcTranslationTable['N'] = 'N';
memset(nTable, 0, sizeof(nTable));
nTable['N'] = 1;
if (allocator) {
seedUsed = (BYTE *)allocator->allocate((sizeof(BYTE) * ((_int64)maxReadSize + 7 + 128) / 8)); // +128 to make sure it extends at both
} else {
seedUsed = (BYTE *)BigAlloc((sizeof(BYTE) * ((_int64)maxReadSize + 7 + 128) / 8)); // +128 to make sure it extends at both
}
seedUsedAsAllocated = seedUsed; // Save the pointer for the delete.
seedUsed += 8; // This moves the pointer up an _int64, so we now have the appropriate before buffer.
nUsedHashTableElements = 0;
if (allocator) {
candidateHashTable[FORWARD] = (HashTableAnchor *)allocator->allocate(sizeof(HashTableAnchor) * candidateHashTablesSize);
candidateHashTable[RC] = (HashTableAnchor *)allocator->allocate(sizeof(HashTableAnchor) * candidateHashTablesSize);
weightLists = (HashTableElement *)allocator->allocate(sizeof(HashTableElement) * numWeightLists);
hashTableElementPool = (HashTableElement *)allocator->allocate(sizeof(HashTableElement) * hashTableElementPoolSize); // Allocate last, because it's biggest and usually unused. This puts all of the commonly used stuff into one large page.
hitCountByExtraSearchDepth = (unsigned *)allocator->allocate(sizeof(*hitCountByExtraSearchDepth) * extraSearchDepth);
if (maxSecondaryAlignmentsPerContig > 0) {
hitsPerContigCounts = (HitsPerContigCounts *)allocator->allocate(sizeof(*hitsPerContigCounts) * genome->getNumContigs());
memset(hitsPerContigCounts, 0, sizeof(*hitsPerContigCounts) * genome->getNumContigs());
} else {
hitsPerContigCounts = NULL;
}
} else {
candidateHashTable[FORWARD] = (HashTableAnchor *)BigAlloc(sizeof(HashTableAnchor) * candidateHashTablesSize);
candidateHashTable[RC] = (HashTableAnchor *)BigAlloc(sizeof(HashTableAnchor) * candidateHashTablesSize);
weightLists = (HashTableElement *)BigAlloc(sizeof(HashTableElement) * numWeightLists);
hashTableElementPool = (HashTableElement *)BigAlloc(sizeof(HashTableElement) * hashTableElementPoolSize);
hitCountByExtraSearchDepth = (unsigned *)BigAlloc(sizeof(*hitCountByExtraSearchDepth) * extraSearchDepth);
if (maxSecondaryAlignmentsPerContig > 0) {
hitsPerContigCounts = (HitsPerContigCounts *)BigAlloc(sizeof(*hitsPerContigCounts) * genome->getNumContigs());
memset(hitsPerContigCounts, 0, sizeof(*hitsPerContigCounts) * genome->getNumContigs());
} else {
hitsPerContigCounts = NULL;
}
}
for (unsigned i = 0; i < hashTableElementPoolSize; i++) {
hashTableElementPool[i].init();
}
for (unsigned i = 0; i < maxSeedsToUse + 1; i++) {
weightLists[i].init();
}
for (Direction rc = 0; rc < NUM_DIRECTIONS; rc++) {
memset(candidateHashTable[rc],0,sizeof(HashTableAnchor) * candidateHashTablesSize);
}
hashTableEpoch = 0;
} // BaseAligner::BaseAligner
#ifdef _DEBUG
bool _DumpAlignments = false;
#endif // _DEBUG
bool
BaseAligner::AlignRead(
Read* inputRead,
SingleAlignmentResult* primaryResult,
SingleAlignmentResult* firstALTResult,
int maxEditDistanceForSecondaryResults,
_int64 secondaryResultBufferSize,
_int64* nSecondaryResults,
_int64 maxSecondaryResults,
SingleAlignmentResult* secondaryResults, // The caller passes in a buffer of secondaryResultBufferSize and it's filled in by AlignRead()
_int64 maxCandidatesForAffineGapBufferSize,
_int64* nCandidatesForAffineGap,
SingleAlignmentResult* candidatesForAffineGap, // Alignment candidates that need to be rescored using affine gap
bool useHamming
)
/*++
Routine Description:
Align a particular read, possibly constraining the search around a given location.
Arguments:
read - the read to align
primaryResult - the best alignment result found
maxEditDistanceForSecondaryResults - How much worse than the primary result should we look?
secondaryResultBufferSize - the size of the secondaryResults buffer. If provided, it must be at least maxK * maxSeeds * 2.
nRescondaryResults - returns the number of secondary results found
maxSecondaryResults - limit the number of secondary results to this
secondaryResults - returns the secondary results
Return Value:
true if there was enough space in secondaryResults, false otherwise
--*/
{
#if _DEBUG
const size_t genomeLocationBufferSize = 200;
char genomeLocationBuffer[genomeLocationBufferSize];
#endif // _DEBUG
bool overflowedSecondaryResultsBuffer = false;
memset(hitCountByExtraSearchDepth, 0, sizeof(*hitCountByExtraSearchDepth) * extraSearchDepth);
if (NULL != nSecondaryResults) {
*nSecondaryResults = 0;
}
firstPassSeedsNotSkipped[FORWARD] = firstPassSeedsNotSkipped[RC] = 0;
highestWeightListChecked = 0;
scoresForAllAlignments.bestScore = scoresForNonAltAlignments.bestScore = TooBigScoreValue;
unsigned maxSeedsToUse;
if (0 != maxSeedsToUseFromCommandLine) {
maxSeedsToUse = maxSeedsToUseFromCommandLine;
} else {
maxSeedsToUse = (int)(NUM_DIRECTIONS * maxSeedCoverage * inputRead->getDataLength() / genomeIndex->getSeedLength());
}
primaryResult->location = InvalidGenomeLocation; // Value to return if we don't find a location.
primaryResult->direction = FORWARD; // So we deterministically print the read forward in this case.
primaryResult->score = UnusedScoreValue;
primaryResult->status = NotFound;
primaryResult->clippingForReadAdjustment = 0;
primaryResult->usedAffineGapScoring = false;
primaryResult->basesClippedBefore = 0;
primaryResult->basesClippedAfter = 0;
primaryResult->agScore = 0;
primaryResult->seedOffset = 0;
primaryResult->supplementary = false;
unsigned lookupsThisRun = 0;
popularSeedsSkipped = 0;
nAddedToHashTable = 0;
//
// A bitvector for used seeds, indexed on the starting location of the seed within the read.
//
if (inputRead->getDataLength() > maxReadSize) {
WriteErrorMessage("BaseAligner:: got too big read (%d > %d)\n"
"Increase MAX_READ_LENGTH at the beginning of Read.h and recompile\n", inputRead->getDataLength(), maxReadSize);
soft_exit(1);
}
if ((int)inputRead->getDataLength() < seedLen) {
//
// Too short to have any seeds, it's hopeless.
// No need to finalize secondary results, since we don't have any.
//
return true;
}
#ifdef TRACE_ALIGNER
printf("Aligning read '%.*s':\n%.*s\n%.*s\n", inputRead->getIdLength(), inputRead->getId(), inputRead->getDataLength(), inputRead->getData(),
inputRead->getDataLength(), inputRead->getQuality());
#endif
#ifdef _DEBUG
if (_DumpAlignments) {
printf("BaseAligner: aligning read ID '%.*s', data '%.*s' %s\n", inputRead->getIdLength(), inputRead->getId(), inputRead->getDataLength(), inputRead->getData(), useHamming ? "Hamming" : "");
}
#endif // _DEBUG
//
// Clear out the seed used array.
//
memset(seedUsed, 0, (inputRead->getDataLength() + 7) / 8);
unsigned readLen = inputRead->getDataLength();
const char* readData = inputRead->getData();
const char* readQuality = inputRead->getQuality();
unsigned countOfNs = 0;
for (unsigned i = 0; i < readLen; i++) {
char baseByte = readData[i];
char complement = rcTranslationTable[baseByte];
rcReadData[readLen - i - 1] = complement;
rcReadQuality[readLen - i - 1] = readQuality[i];
reversedRead[FORWARD][readLen - i - 1] = baseByte;
reversedRead[RC][i] = complement;
countOfNs += nTable[baseByte];
}
if (countOfNs > maxK) {
nReadsIgnoredBecauseOfTooManyNs++;
// No need to finalize secondary results, since we don't have any.
return true;
}
#if 1
//
// The bad aligner works by finding one seed in the middle of the read, scoring a few hits (from both forward and RC) and taking the best one.
// If the seed has an N in it, then we don't align the read.
//
Read reverseComplimentRead;
Read* read[NUM_DIRECTIONS];
read[FORWARD] = inputRead;
read[RC] = &reverseComplimentRead;
read[RC]->init(NULL, 0, rcReadData, rcReadQuality, readLen);
_int64 nHits[NUM_DIRECTIONS]; // Number of times this seed hits in the genome
const GenomeLocation* hits[NUM_DIRECTIONS]; // The actual hits (of size nHits)
GenomeLocation singletonHits[NUM_DIRECTIONS]; // Storage for single hits (this is required for 64 bit genome indices, since they might use fewer than 8 bytes internally)
const unsigned* hits32[NUM_DIRECTIONS];
firstALTResult->status = NotFound; // We don't do ALTs. We're a bad aligner.
int seedLocation = readLen / 2 - seedLen / 2;
if (seedLocation < 0 || seedLocation + seedLen >= readLen) {
// Couldn't fit the seed
return true;
}
if (!Seed::DoesTextRepresentASeed(read[FORWARD]->getData() + seedLocation, seedLen)) {
//
// There's an N or something. Give up on the read.
//
return true;
}
Seed seed(read[FORWARD]->getData() + seedLocation, seedLen);
if (doesGenomeIndexHave64BitLocations) {
genomeIndex->lookupSeed(seed, &nHits[FORWARD], &hits[FORWARD], &nHits[RC], &hits[RC], &singletonHits[FORWARD], &singletonHits[RC]);
} else {
genomeIndex->lookupSeed32(seed, &nHits[FORWARD], &hits32[FORWARD], &nHits[RC], &hits32[RC]);
}
//
// Start scoring hits, alternating between forward and rc. Start from the highest hit in the array because the SNAP index
// is sorted backwards (don't ask), meaning that the later hits have the lower GenomeOffsets, which in turn are more likely
// to be in primary contigs than in other stuff.
//
// Ignore ALTs altogether.
//
int nHitsConsidered = 0;
bool lookForwardNext = true;
int bestScore = maxK + 1;
int secondBestScore = maxK + 2;
int secondBestCount = 0;
GenomeLocation bestAlignmentLocation = InvalidGenomeLocation;
int bestAlignmentDirection = FORWARD;
_int64 nextHitToConsider[NUM_DIRECTIONS] = { nHits[FORWARD] - 1, nHits[RC] - 1 };
int nextDirectionToConsider = FORWARD;
if (nextHitToConsider[FORWARD] + nextHitToConsider[RC] > maxSeedsToUse) {
//
// Too many hits. Skip this read.
//
return true;
}
while (nHitsConsidered < maxSeedsToUse) {
if (nextHitToConsider[FORWARD] < 0 && nextHitToConsider[RC] < 0) {
break;
}
//
// If we're out of one direction, switch back to the other.
//
if (nextHitToConsider[nextDirectionToConsider] == -1) {
nextDirectionToConsider = 1 - nextDirectionToConsider;
continue;
}
GenomeLocation locationToScore = (doesGenomeIndexHave64BitLocations ? hits[nextDirectionToConsider][nextHitToConsider[nextDirectionToConsider]] : hits32[nextDirectionToConsider][nextHitToConsider[nextDirectionToConsider]]) - seedLocation;
nextHitToConsider[nextDirectionToConsider]--;
if (genome->isGenomeLocationALT(locationToScore)) {
nextHitToConsider[nextDirectionToConsider]--;
continue;
}
Read* readToScore = read[nextDirectionToConsider];
const char* referenceData = genome->getSubstring(locationToScore, readToScore->getDataLength() + maxK);
if (NULL == referenceData) {
//
// Ran off the end of a contig.
//
nextHitToConsider[nextDirectionToConsider]--;
nextDirectionToConsider = 1 - nextDirectionToConsider;
continue;
}
int score = landauVishkin->computeEditDistance(referenceData, readToScore->getDataLength() + maxK, readToScore->getData(), readToScore->getDataLength(), bestScore + 1);
nHitsConsidered++;
if (score == ScoreAboveLimit) {
nextHitToConsider[nextDirectionToConsider]--;
nextDirectionToConsider = 1 - nextDirectionToConsider;
continue;
}
if (score < bestScore) {
if (secondBestScore == bestScore) {
secondBestCount++;
} else {
secondBestCount = 1;
}
secondBestScore = bestScore;
bestScore = score;
bestAlignmentLocation = locationToScore;
bestAlignmentDirection = nextDirectionToConsider;
} else if (score < secondBestScore) {
secondBestCount = 1;
secondBestScore = score;
} else if (score == secondBestScore) {
secondBestCount++;
}
nextHitToConsider[nextDirectionToConsider]--;
nextDirectionToConsider = 1 - nextDirectionToConsider;
} // while we might still be scoring something
if (bestScore > maxK) {
//
// Didn't align.
//
return true;
}
primaryResult->location = bestAlignmentLocation;
primaryResult->direction = bestAlignmentDirection;
primaryResult->score = bestScore;
primaryResult->mapq = (bestScore == secondBestScore) ? 0 : ((bestScore + 1 < secondBestScore) ? 70 : computeMAPQ(1, 1 - .01 * secondBestCount, bestScore, 0));
if (primaryResult->mapq >= MAPQ_LIMIT_FOR_SINGLE_HIT) {
primaryResult->status = SingleHit;
} else {
primaryResult->status = MultipleHits;
}
return true;
#else 1
//
// Block off any seeds that would contain an N.
//
if (countOfNs > 0) {
int minSeedToConsiderNing = 0; // In English, any word can be verbed. Including, apparently, "N."
for (int i = 0; i < (int) readLen; i++) {
if (BASE_VALUE[readData[i]] > 3) {
int limit = __min(i + seedLen - 1, readLen-1);
for (int j = __max(minSeedToConsiderNing, i - (int) seedLen + 1); j <= limit; j++) {
SetSeedUsed(j);
}
minSeedToConsiderNing = limit+1;
if (minSeedToConsiderNing >= (int) readLen)
break;
}
}
}
Read reverseComplimentRead;
Read *read[NUM_DIRECTIONS];
read[FORWARD] = inputRead;
read[RC] = &reverseComplimentRead;
read[RC]->init(NULL, 0, rcReadData, rcReadQuality, readLen);
clearCandidates();
//
// Initialize the bases table, which represents which bases we've checked.
// We have readSize - seeds size + 1 possible seeds.
//
unsigned nPossibleSeeds = readLen - seedLen + 1;
TRACE("nPossibleSeeds: %d\n", nPossibleSeeds);
unsigned nextSeedToTest = 0;
wrapCount = 0;
lowestPossibleScoreOfAnyUnseenLocation[FORWARD] = lowestPossibleScoreOfAnyUnseenLocation[RC] = 0;
currRoundLowestPossibleScoreOfAnyUnseenLocation[FORWARD] = currRoundLowestPossibleScoreOfAnyUnseenLocation[RC] = 0;
mostSeedsContainingAnyParticularBase[FORWARD] = mostSeedsContainingAnyParticularBase[RC] = 1; // Instead of tracking this for real, we're just conservative and use wrapCount+1. It's faster.
scoresForAllAlignments.init();
if (altAwareness) {
scoresForNonAltAlignments.init();
}
nSeedsApplied[FORWARD] = nSeedsApplied[RC] = 0;
lvScores = 0;
lvScoresAfterBestFound = 0;
while (nSeedsApplied[FORWARD] + nSeedsApplied[RC] < maxSeedsToUse) {
//
// Choose the next seed to use. Choose the first one that isn't used
//
if (nextSeedToTest >= nPossibleSeeds) {
//
// We're wrapping. We want to space the seeds out as much as possible, so if we had
// a seed length of 20 we'd want to take 0, 10, 5, 15, 2, 7, 12, 17. To make the computation
// fast, we use use a table lookup.
//
wrapCount++;
if (wrapCount >= seedLen) {
//
// We tried all possible seeds without matching or even getting enough seeds to
// exceed our seed count. Do the best we can with what we have.
//
#ifdef TRACE_ALIGNER
printf("Calling score with force=true because we wrapped around enough\n");
#endif
score(
true,
read,
primaryResult,
firstALTResult,
maxEditDistanceForSecondaryResults,
secondaryResultBufferSize,
nSecondaryResults,
secondaryResults,
&overflowedSecondaryResultsBuffer,
maxCandidatesForAffineGapBufferSize,
nCandidatesForAffineGap,
candidatesForAffineGap,
useHamming);
#ifdef _DEBUG
if (_DumpAlignments) printf("Final result score %d MAPQ %d (%e probability of best candidate, %e probability of all candidates, non ALT-aware) at %s:%llu\n\n",
primaryResult->score, primaryResult->mapq, scoresForAllAlignments.probabilityOfBestCandidate, scoresForAllAlignments.probabilityOfAllCandidates,
genome->getContigAtLocation(primaryResult->location)->name, primaryResult->location - genome->getContigAtLocation(primaryResult->location)->beginningLocation);
#endif // _DEBUG
if (overflowedSecondaryResultsBuffer) {
return false;
}
finalizeSecondaryResults(read[FORWARD], primaryResult, nSecondaryResults, secondaryResults, maxSecondaryResults, maxEditDistanceForSecondaryResults, primaryResult->score);
return true;
}
nextSeedToTest = GetWrappedNextSeedToTest(seedLen, wrapCount);
mostSeedsContainingAnyParticularBase[FORWARD] = mostSeedsContainingAnyParticularBase[RC] = wrapCount + 1;
currRoundLowestPossibleScoreOfAnyUnseenLocation[FORWARD] = currRoundLowestPossibleScoreOfAnyUnseenLocation[RC] = 0;
}
while (nextSeedToTest < nPossibleSeeds && IsSeedUsed(nextSeedToTest)) {
//
// This seed is already used. Try the next one.
//
TRACE("Skipping due to IsSeedUsed\n");
nextSeedToTest++;
}
if (nextSeedToTest >= nPossibleSeeds) {
//
// Unusable seeds have pushed us past the end of the read. Go back around the outer loop so we wrap properly.
//
TRACE("Eek, we're past the end of the read\n");
continue;
}
SetSeedUsed(nextSeedToTest);
if (!Seed::DoesTextRepresentASeed(read[FORWARD]->getData() + nextSeedToTest, seedLen)) {
continue;
}
Seed seed(read[FORWARD]->getData() + nextSeedToTest, seedLen);
_int64 nHits[NUM_DIRECTIONS]; // Number of times this seed hits in the genome
const GenomeLocation *hits[NUM_DIRECTIONS]; // The actual hits (of size nHits)
GenomeLocation singletonHits[NUM_DIRECTIONS]; // Storage for single hits (this is required for 64 bit genome indices, since they might use fewer than 8 bytes internally)
const unsigned *hits32[NUM_DIRECTIONS];
if (doesGenomeIndexHave64BitLocations) {
genomeIndex->lookupSeed(seed, &nHits[FORWARD], &hits[FORWARD], &nHits[RC], &hits[RC], &singletonHits[FORWARD], &singletonHits[RC]);
} else {
genomeIndex->lookupSeed32(seed, &nHits[FORWARD], &hits32[FORWARD], &nHits[RC], &hits32[RC]);
}
nHashTableLookups++;
lookupsThisRun++;
#ifdef _DEBUG
if (_DumpAlignments) {
printf("\tSeed offset %2d, %4lld hits, %4lld rcHits.", nextSeedToTest, nHits[0], nHits[1]);
for (int rc = 0; rc < 2; rc++) {
for (unsigned i = 0; i < __min(nHits[rc], 2); i++) {
printf(" %sHit at %s.", rc == 1 ? "RC " : "", genome->genomeLocationInStringForm(doesGenomeIndexHave64BitLocations ? hits[rc][i].location : (_int64)hits32[rc][i], genomeLocationBuffer, genomeLocationBufferSize));
}
}
printf("\n");
}
#endif // _DEUBG
#ifdef TRACE_ALIGNER
printf("Looked up seed %.*s (offset %d): hits=%u, rchits=%u\n",
seedLen, inputRead->getData() + nextSeedToTest, nextSeedToTest, nHits[0], nHits[1]);
for (int rc = 0; rc < 2; rc++) {
if (nHits[rc] <= maxHitsToConsider) {
printf("%sHits:", rc == 1 ? "RC " : "");
for (unsigned i = 0; i < nHits[rc]; i++)
printf(" %9llu", doesGenomeIndexHave64BitLocations ? hits[rc][i].location : (_int64)hits32[rc][i]);
printf("\n");
}
}
#endif
bool appliedEitherSeed = false;
for (Direction direction = 0; direction < NUM_DIRECTIONS; direction++) {
if (nHits[direction] > maxHitsToConsider && !explorePopularSeeds) {
//
// This seed is matching too many places. Just pretend we never looked and keep going.
//
nHitsIgnoredBecauseOfTooHighPopularity++;
popularSeedsSkipped++;
} else {
if (0 == wrapCount) {
firstPassSeedsNotSkipped[direction]++;
}
//
// Update the candidates list with any hits from this seed. If lowest possible score of any unseen location is
// more than best_score + confDiff then we know that if this location is newly seen then its location won't ever be a
// winner, and we can ignore it.
//
unsigned offset;
if (direction == FORWARD) {
offset = nextSeedToTest;
} else {
//
// The RC seed is at offset ReadSize - SeedSize - seed offset in the RC seed.
//
// To see why, imagine that you had a read that looked like 0123456 (where the digits
// represented some particular bases, and digit' is the base's complement). Then the
// RC of that read is 6'5'4'3'2'1'. So, when we look up the hits for the seed at
// offset 0 in the forward read (i.e. 012 assuming a seed size of 3) then the index
// will also return the results for the seed's reverse complement, i.e., 2'1'0'.
// This happens as the last seed in the RC read.
//
offset = readLen - seedLen - nextSeedToTest;
}
const unsigned prefetchDepth = 6;
//
// We keep prefetches outstanding prefetchDepth ahead of where we are. Start by launching the first
// prefetchDepth of them, and then each time we process a hit launch the prefetch for prefetchDepth farther
// along, assuming it exists.
//
if (doAlignerPrefetch) {
_int64 prefetchLimit = __min(prefetchDepth, __min(nHits[direction], (_int64)maxHitsToConsider));
for (int prefetchIndex = 0; prefetchIndex < prefetchLimit; prefetchIndex++) {
if (doesGenomeIndexHave64BitLocations) {
prefetchHashTableBucket(GenomeLocationAsInt64(hits[direction][prefetchIndex]) - offset, direction);
}
else {
prefetchHashTableBucket(hits32[direction][prefetchIndex] - offset, direction);
}
}
}
_int64 limit = min(nHits[direction], (_int64)maxHitsToConsider);
for (unsigned i = 0; i < limit; i++) {
//
// Find the genome location where the beginning of the read would hit, given a match on this seed.
//
GenomeLocation genomeLocationOfThisHit;
if (doesGenomeIndexHave64BitLocations) {
genomeLocationOfThisHit = hits[direction][i] - offset;
} else {
genomeLocationOfThisHit = hits32[direction][i] - offset;
}
Candidate *candidate = NULL;
HashTableElement *hashTableElement;
findCandidate(genomeLocationOfThisHit, direction, &candidate, &hashTableElement);
bool candidateIsALT = altAwareness && genome->isGenomeLocationALT(genomeLocationOfThisHit);
if (NULL != hashTableElement) {
if (!noOrderedEvaluation) { // If noOrderedEvaluation, just leave them all on the one-hit weight list so they get evaluated in whatever order
incrementWeight(hashTableElement);
}
candidate->seedOffset = offset;
_ASSERT((unsigned)candidate->seedOffset <= readLen - seedLen);
} else if (lowestPossibleScoreOfAnyUnseenLocation[direction] <= scoreLimit(candidateIsALT) || noTruncation) {
_ASSERT(offset <= readLen - seedLen);
allocateNewCandidate(genomeLocationOfThisHit, direction, lowestPossibleScoreOfAnyUnseenLocation[direction],
offset, &candidate, &hashTableElement);
nAddedToHashTable++;
}
if (doAlignerPrefetch && (_int64)i + prefetchDepth < limit) {
if (doesGenomeIndexHave64BitLocations) {
prefetchHashTableBucket(GenomeLocationAsInt64(hits[direction][i + prefetchDepth]) - offset, direction);
}
else {
prefetchHashTableBucket(hits32[direction][i + prefetchDepth] - offset, direction);
}
}
}
nSeedsApplied[direction]++;
currRoundLowestPossibleScoreOfAnyUnseenLocation[direction]++;
appliedEitherSeed = true;
} // not too popular
} // directions
#if 1
nextSeedToTest += seedLen;
#else // 0
//
// If we don't have enough seeds left to reach the end of the read, space out the seeds more-or-less evenly.
//
if ((maxSeedsToUse - (nSeedsApplied[FORWARD] + nSeedsApplied[RC]) + 1) * seedLen + nextSeedToTest < nPossibleSeeds) {
_ASSERT((nPossibleSeeds + nextSeedToTest) / (maxSeedsToUse - (nSeedsApplied[FORWARD] + nSeedsApplied[RC]) + 1) > seedLen);
nextSeedToTest += (nPossibleSeeds + nextSeedToTest) / (maxSeedsToUse - (nSeedsApplied[FORWARD] + nSeedsApplied[RC]) + 1);
} else {
nextSeedToTest += seedLen;
}
#endif // 0
if (appliedEitherSeed) {
//
// And finally, try scoring.
//
if (score(
false,
read,
primaryResult,
firstALTResult,
maxEditDistanceForSecondaryResults,
secondaryResultBufferSize,
nSecondaryResults,
secondaryResults,
&overflowedSecondaryResultsBuffer,
maxCandidatesForAffineGapBufferSize,
nCandidatesForAffineGap,
candidatesForAffineGap,
useHamming)) {
#ifdef _DEBUG
if (_DumpAlignments) printf("Final result score %d MAPQ %d at %s:%llu\n", primaryResult->score, primaryResult->mapq,
genome->getContigAtLocation(primaryResult->location)->name, primaryResult->location - genome->getContigAtLocation(primaryResult->location)->beginningLocation);
#endif // _DEBUG
if (overflowedSecondaryResultsBuffer) {
return false;
}
finalizeSecondaryResults(read[FORWARD], primaryResult, nSecondaryResults, secondaryResults, maxSecondaryResults, maxEditDistanceForSecondaryResults, primaryResult->score);
return true;
} // If score says we have a difinitive answer
} // If we applied a seed, and so something's changed.
} // While we're still applying seeds
//
// Do the best with what we've got.
//
#ifdef TRACE_ALIGNER
printf("Calling score with force=true because we ran out of seeds\n");
#endif
score(
true,
read,
primaryResult,
firstALTResult,
maxEditDistanceForSecondaryResults,
secondaryResultBufferSize,
nSecondaryResults,
secondaryResults,
&overflowedSecondaryResultsBuffer,
maxCandidatesForAffineGapBufferSize,
nCandidatesForAffineGap,
candidatesForAffineGap,
useHamming);
#ifdef _DEBUG
if (_DumpAlignments) printf("Final result score %d MAPQ %d (%e probability of best candidate, %e probability of all candidates non ALT-aware) at %s:%llu\n",
primaryResult->score, primaryResult->mapq, scoresForAllAlignments.probabilityOfBestCandidate, scoresForAllAlignments.probabilityOfAllCandidates,
genome->getContigAtLocation(primaryResult->location)->name, primaryResult->location - genome->getContigAtLocation(primaryResult->location)->beginningLocation);
if (_DumpAlignments && firstALTResult->status != NotFound) printf("Emitting ALT result score %d MAPQ %d at %llu\n",
firstALTResult->score, firstALTResult->mapq, firstALTResult->location.location);
#endif // _DEBUG
if (overflowedSecondaryResultsBuffer) {
return false;
}
finalizeSecondaryResults(read[FORWARD], primaryResult, nSecondaryResults, secondaryResults, maxSecondaryResults, maxEditDistanceForSecondaryResults, primaryResult->score);
return true;
#endif // 1
}
void
BaseAligner::scoreLocationWithAffineGap(
Read* reads[NUM_DIRECTIONS],
Direction direction,
GenomeLocation genomeLocation,
unsigned seedOffset,
int scoreLimit,
int* score,
double* matchProbability,
int* genomeLocationOffset,
int* basesClippedBefore,
int* basesClippedAfter,
int* agScore
)
{
Read* readToScore = reads[direction];
unsigned readDataLength = readToScore->getDataLength();
GenomeDistance genomeDataLength = (GenomeDistance)readDataLength + MAX_K; // Leave extra space in case the read has deletions
const char* data = genome->getSubstring(genomeLocation, genomeDataLength);
*genomeLocationOffset = 0;
if (NULL == data) {
*score = ScoreAboveLimit;
*matchProbability = 0;
*genomeLocationOffset = 0;
*agScore = ScoreAboveLimit;
return;
}
*basesClippedBefore = 0;
*basesClippedAfter = 0;
double matchProb1 = 1.0, matchProb2 = 1.0;
int score1 = 0, score2 = 0; // edit distance
// First, do the forward direction from where the seed aligns to past of it
int readLen = readToScore->getDataLength();
int tailStart = seedOffset + seedLen;
int agScore1 = seedLen, agScore2 = 0; // affine gap scores
_ASSERT(!memcmp(data + seedOffset, readToScore->getData() + seedOffset, seedLen)); // that the seed actually matches
int textLen;
if (genomeDataLength - tailStart > INT32_MAX) {
textLen = INT32_MAX;
}
else {
textLen = (int)(genomeDataLength - tailStart);
}
if (tailStart != readLen) {
int patternLen = readLen - tailStart;
//
// Try banded affine-gap when pattern is long and band needed is small
//
if (patternLen >= (3 * (2 * (int)scoreLimit + 1))) {
agScore1 = affineGap->computeScoreBanded(data + tailStart,
textLen,
readToScore->getData() + tailStart,
readToScore->getQuality() + tailStart,
readLen - tailStart,
scoreLimit,
readLen,
direction,
NULL,
basesClippedAfter,
&score1,
&matchProb1,
true);
}
else {
agScore1 = affineGap->computeScore(data + tailStart,
textLen,
readToScore->getData() + tailStart,
readToScore->getQuality() + tailStart,
readLen - tailStart,
scoreLimit,