forked from BioinformaticsArchive/blasr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Blasr.cpp
1496 lines (1348 loc) · 53.2 KB
/
Blasr.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
// Author: Mark Chaisson
#include "iblasr/BlasrMiscs.hpp"
#include "iblasr/BlasrUtils.hpp"
#include "iblasr/BlasrAlign.hpp"
#include "iblasr/RegisterBlasrOptions.h"
//#define USE_GOOGLE_PROFILER
#ifdef USE_GOOGLE_PROFILER
#include "gperftools/profiler.h"
#endif
using namespace std;
// Declare global structures that are shared between threads.
MappingSemaphores semaphores;
ostream *outFilePtr = NULL;
#ifdef USE_PBBAM
PacBio::BAM::BamWriter * bamWriterPtr = NULL;
#endif
HDFRegionTableReader *regionTableReader = NULL;
ReaderAgglomerate *reader = NULL;
const string GetMajorVersion() {
return "2.0.0";
}
const string GetVersion(void) {
string perforceVersionString("$Change$");
string version = GetMajorVersion();
if (perforceVersionString.size() > 12) {
version.insert(version.size(), ".");
version.insert(version.size(), perforceVersionString, 9, perforceVersionString.size() - 11);
}
return version;
}
/// Checks whether a smrtRead meets the following criteria
/// (1) is within the search holeNumber range specified by params.holeNumberRanges.
/// (2) its length greater than params.maxReadlength
/// (3) its read score (rq) is greater than params.minRawSubreadScore
/// (4) its qual is greater than params.minAvgQual.
/// Change stop to false if
/// HoleNumber of the smrtRead is greater than the search holeNumber range.
bool IsGoodRead(const SMRTSequence & smrtRead,
MappingParameters & params,
bool & stop)
{
if (params.holeNumberRangesStr.size() > 0 and
not params.holeNumberRanges.contains(smrtRead.HoleNumber())) {
// Stop processing once the specified zmw hole number is reached.
// Eventually this will change to just seek to hole number, and
// just align one read anyway.
if (smrtRead.HoleNumber() > params.holeNumberRanges.max()){
stop = true;
return false;
}
return false;
}
//
// Discard reads that are too small, or not labeled as having any
// useable/good sequence.
//
if (smrtRead.highQualityRegionScore < params.minRawSubreadScore or
(params.maxReadLength != 0 and smrtRead.length > UInt(params.maxReadLength)) or
(smrtRead.length < params.minReadLength)) {
return false;
}
if (smrtRead.qual.Empty() != false and smrtRead.GetAverageQuality() < params.minAvgQual) {
return false;
}
return true;
}
// Make primary intervals (which are intervals of subreads to align
// in the first round) from none BAM file using region table.
void MakePrimaryIntervals(RegionTable * regionTablePtr,
SMRTSequence & smrtRead,
vector<ReadInterval> & subreadIntervals,
vector<int> & subreadDirections,
int & bestSubreadIndex,
MappingParameters & params)
{
vector<ReadInterval> adapterIntervals;
//
// Determine endpoints of this subread in the main read.
//
if (params.useRegionTable == false) {
//
// When there is no region table, the subread is the entire
// read.
//
ReadInterval wholeRead(0, smrtRead.length);
// The set of subread intervals is just the entire read.
subreadIntervals.push_back(wholeRead);
}
else {
//
// Grab the subread & adapter intervals from the entire region table to
// iterate over.
//
assert(regionTablePtr->HasHoleNumber(smrtRead.HoleNumber()));
subreadIntervals = (*regionTablePtr)[smrtRead.HoleNumber()].SubreadIntervals(smrtRead.length, params.byAdapter);
adapterIntervals = (*regionTablePtr)[smrtRead.HoleNumber()].AdapterIntervals();
}
// The assumption is that neighboring subreads must have the opposite
// directions. So create directions for subread intervals with
// interleaved 0s and 1s.
CreateDirections(subreadDirections, subreadIntervals.size());
//
// Trim the boundaries of subread intervals so that only high quality
// regions are included in the intervals, not N's. Remove intervals
// and their corresponding dirctions, if they are shorter than the
// user specified minimum read length or do not intersect with hq
// region at all. Finally, return index of the (left-most) longest
// subread in the updated vector.
//
int longestSubreadIndex = GetHighQualitySubreadsIntervals(
subreadIntervals, // a vector of subread intervals.
subreadDirections, // a vector of subread directions.
smrtRead.lowQualityPrefix, // hq region start pos.
smrtRead.length - smrtRead.lowQualitySuffix, // hq end pos.
params.minSubreadLength); // minimum read length.
bestSubreadIndex = longestSubreadIndex;
if (params.concordantTemplate == "longestsubread") {
// Use the (left-most) longest full-pass subread as
// template for concordant mapping
int longestFullSubreadIndex = GetLongestFullSubreadIndex(
subreadIntervals, adapterIntervals);
if (longestFullSubreadIndex >= 0) {
bestSubreadIndex = longestFullSubreadIndex;
}
} else if (params.concordantTemplate == "typicalsubread") {
// Use the 'typical' full-pass subread as template for
// concordant mapping.
int typicalFullSubreadIndex = GetTypicalFullSubreadIndex(
subreadIntervals, adapterIntervals);
if (typicalFullSubreadIndex >= 0) {
bestSubreadIndex = typicalFullSubreadIndex;
}
} else if (params.concordantTemplate == "mediansubread") {
// Use the 'median-length' full-pass subread as template for
// concordant mapping.
int medianFullSubreadIndex = GetMedianLengthFullSubreadIndex(
subreadIntervals, adapterIntervals);
if (medianFullSubreadIndex >= 0) {
bestSubreadIndex = medianFullSubreadIndex;
}
} else {
assert(false);
}
}
// Make primary intervals (which are intervals of subreads to align
// in the first round) for BAM file, -concordant,
void MakePrimaryIntervals(vector<SMRTSequence> & subreads,
vector<ReadInterval> & subreadIntervals,
vector<int> & subreadDirections,
int & bestSubreadIndex,
MappingParameters & params)
{
MakeSubreadIntervals(subreads, subreadIntervals);
CreateDirections(subreadDirections, subreadIntervals.size());
bestSubreadIndex = GetIndexOfConcordantTemplate(subreadIntervals);
}
/// Scan the next read from input. This may either be a CCS read,
/// or regular read (though this may be aligned in whole, or by
/// subread).
/// \params[in] reader: FASTA/FASTQ/BAX.H5/CCS.H5/BAM file reader
/// \params[in] regionTablePtr: RGN.H5 region table pointer.
/// \params[in] params: mapping parameters.
/// \params[out] smrtRead: to save smrt sequence.
/// \params[out] ccsRead: to save ccs sequence.
/// \params[out] readIsCCS: read is CCSSequence.
/// \params[out] readGroupId: associated read group id
/// \params[out] associatedRandInt: random int associated with this zmw,
/// required to for generating deterministic random
/// alignments regardless of nproc.
/// \params[out] stop: whether or not stop mapping remaining reads.
/// \returns whether or not to skip mapping reads of this zmw.
bool FetchReads(ReaderAgglomerate * reader,
RegionTable * regionTablePtr,
SMRTSequence & smrtRead,
CCSSequence & ccsRead,
vector<SMRTSequence> & subreads,
MappingParameters & params,
bool & readIsCCS,
std::string & readGroupId,
int & associatedRandInt,
bool & stop)
{
if ((reader->GetFileType() != BAM and reader->GetFileType() != PBDATASET) or not params.concordant) {
if (reader->GetFileType() == HDFCCS ||
reader->GetFileType() == HDFCCSONLY) {
if (GetNextReadThroughSemaphore(*reader, params, ccsRead, readGroupId, associatedRandInt, semaphores) == false) {
stop = true;
return false;
}
else {
readIsCCS = true;
smrtRead.Copy(ccsRead);
ccsRead.SetQVScale(params.qvScaleType);
smrtRead.SetQVScale(params.qvScaleType);
}
assert(ccsRead.zmwData.holeNumber == smrtRead.zmwData.holeNumber and
ccsRead.zmwData.holeNumber == ccsRead.unrolledRead.zmwData.holeNumber);
} else {
if (GetNextReadThroughSemaphore(*reader, params, smrtRead, readGroupId, associatedRandInt, semaphores) == false) {
stop = true;
return false;
}
else {
smrtRead.SetQVScale(params.qvScaleType);
}
}
//
// Only normal (non-CCS) reads should be masked. Since CCS reads store the raw read, that is masked.
//
bool readHasGoodRegion = true;
if (params.useRegionTable and params.useHQRegionTable) {
if (readIsCCS) {
readHasGoodRegion = MaskRead(ccsRead.unrolledRead, ccsRead.unrolledRead.zmwData, *regionTablePtr);
}
else {
readHasGoodRegion = MaskRead(smrtRead, smrtRead.zmwData, *regionTablePtr);
}
//
// Store the high quality start and end of this read for masking purposes when printing.
//
int hqStart, hqEnd;
int score;
LookupHQRegion(smrtRead.zmwData.holeNumber, *regionTablePtr, hqStart, hqEnd, score);
smrtRead.lowQualityPrefix = hqStart;
smrtRead.lowQualitySuffix = smrtRead.length - hqEnd;
smrtRead.highQualityRegionScore = score;
}
else {
smrtRead.lowQualityPrefix = 0;
smrtRead.lowQualitySuffix = 0;
}
if (not IsGoodRead(smrtRead, params, stop) or stop) return false;
return readHasGoodRegion;
} else {
subreads.clear();
vector<SMRTSequence> reads;
if (GetNextReadThroughSemaphore(*reader, params, reads, readGroupId, associatedRandInt, semaphores) == false) {
stop = true;
return false;
}
for (const SMRTSequence & smrtRead: reads) {
if (IsGoodRead(smrtRead, params, stop)) {
subreads.push_back(smrtRead);
}
}
if (subreads.size() != 0) {
MakeVirtualRead(smrtRead, subreads);
return true;
}
else {
return false;
}
}
}
void MapReadsNonCCS(MappingData<T_SuffixArray, T_GenomeSequence, T_Tuple> *mapData,
MappingBuffers & mappingBuffers,
SMRTSequence & smrtRead,
SMRTSequence & smrtReadRC,
CCSSequence & ccsRead,
vector<SMRTSequence> & subreads,
MappingParameters & params,
const int & associatedRandInt,
ReadAlignments & allReadAlignments,
ofstream & threadOut)
{
DNASuffixArray sarray;
TupleCountTable<T_GenomeSequence, DNATuple> ct;
SequenceIndexDatabase<FASTQSequence> seqdb;
T_GenomeSequence genome;
BWT *bwtPtr;
mapData->ShallowCopySuffixArray(sarray);
mapData->ShallowCopyReferenceSequence(genome);
mapData->ShallowCopySequenceIndexDatabase(seqdb);
mapData->ShallowCopyTupleCountTable(ct);
bwtPtr = mapData->bwtPtr;
SeqBoundaryFtr<FASTQSequence> seqBoundary(&seqdb);
vector<ReadInterval> subreadIntervals;
vector<int> subreadDirections;
int bestSubreadIndex;
if ((mapData->reader->GetFileType() != BAM and mapData->reader->GetFileType() != PBDATASET) or not params.concordant) {
MakePrimaryIntervals(mapData->regionTablePtr, smrtRead,
subreadIntervals, subreadDirections,
bestSubreadIndex, params);
} else {
MakePrimaryIntervals(subreads,
subreadIntervals, subreadDirections,
bestSubreadIndex, params);
}
// Flop all directions if direction of the longest subread is 1.
if (bestSubreadIndex >= 0 and
bestSubreadIndex < int(subreadDirections.size()) and
subreadDirections[bestSubreadIndex] == 1) {
UpdateDirections(subreadDirections, true);
}
int startIndex = 0;
int endIndex = subreadIntervals.size();
if (params.concordant) {
// Only the longest subread will be aligned in the first round.
startIndex = max(startIndex, bestSubreadIndex);
endIndex = min(endIndex, bestSubreadIndex + 1);
if (params.verbosity >= 1) {
cout << "Concordant template subread index: " << bestSubreadIndex << ", "
<< smrtRead.HoleNumber() << "/" << subreadIntervals[bestSubreadIndex] << endl;
}
}
//
// Make room for alignments.
//
allReadAlignments.Resize(subreadIntervals.size());
allReadAlignments.alignMode = Subread;
DNALength intvIndex;
for (intvIndex = startIndex; intvIndex < endIndex; intvIndex++) {
SMRTSequence subreadSequence, subreadSequenceRC;
MakeSubreadOfInterval(subreadSequence, smrtRead,
subreadIntervals[intvIndex], params);
MakeSubreadRC(subreadSequenceRC, subreadSequence, smrtRead);
//
// Store the sequence that is being mapped in case no hits are
// found, and missing sequences are printed.
//
allReadAlignments.SetSequence(intvIndex, subreadSequence);
vector<T_AlignmentCandidate*> alignmentPtrs;
mapData->metrics.numReads++;
assert(subreadSequence.zmwData.holeNumber == smrtRead.zmwData.holeNumber);
//
// Try default and fast parameters to map the read.
//
MapRead(subreadSequence, subreadSequenceRC,
genome, // possibly multi fasta file read into one sequence
sarray, *bwtPtr, // The suffix array, and the bwt-fm index structures
seqBoundary, // Boundaries of contigs in the
// genome, alignments do not span
// the ends of boundaries.
ct, // Count table to use word frequencies in the genome to weight matches.
seqdb, // Information about the names of
// chromosomes in the genome, and
// where their sequences are in the genome.
params, // A huge list of parameters for
// mapping, only compile/command
// line values set.
mapData->metrics, // Keep track of time/ hit counts,
// etc.. Not fully developed, but
// should be.
alignmentPtrs, // Where the results are stored.
mappingBuffers, // A class of buffers for structurs
// like dyanmic programming
// matrices, match lists, etc., that are not
// reallocated between calls to
// MapRead. They are cleared though.
mapData, // Some values that are shared
// across threads.
semaphores);
//
// No alignments were found, sometimes parameters are
// specified to try really hard again to find an alignment.
// This sets some parameters that use a more sensitive search
// at the cost of time.
//
if ((alignmentPtrs.size() == 0 or alignmentPtrs[0]->pctSimilarity < 80) and params.doSensitiveSearch) {
MappingParameters sensitiveParams = params;
sensitiveParams.SetForSensitivity();
MapRead(subreadSequence, subreadSequenceRC, genome,
sarray, *bwtPtr,
seqBoundary, ct, seqdb,
sensitiveParams, mapData->metrics,
alignmentPtrs, mappingBuffers,
mapData,
semaphores);
}
//
// Store the mapping quality values.
//
if (alignmentPtrs.size() > 0 and
alignmentPtrs[0]->score < params.maxScore and
params.storeMapQV) {
StoreMapQVs(subreadSequence, alignmentPtrs, params);
}
//
// Select alignments for this subread.
//
vector<T_AlignmentCandidate*> selectedAlignmentPtrs =
SelectAlignmentsToPrint(alignmentPtrs, params, associatedRandInt);
allReadAlignments.AddAlignmentsForSeq(intvIndex, selectedAlignmentPtrs);
//
// Move reference from subreadSequence, which will be freed at
// the end of this loop to the smrtRead, which exists for the
// duration of aligning all subread of the smrtRead.
//
for (size_t a = 0; a < alignmentPtrs.size(); a++) {
if (alignmentPtrs[a]->qStrand == 0) {
alignmentPtrs[a]->qAlignedSeq.ReferenceSubstring(smrtRead,
alignmentPtrs[a]->qAlignedSeq.seq - subreadSequence.seq,
alignmentPtrs[a]->qAlignedSeqLength);
}
else {
alignmentPtrs[a]->qAlignedSeq.ReferenceSubstring(smrtReadRC,
alignmentPtrs[a]->qAlignedSeq.seq - subreadSequenceRC.seq,
alignmentPtrs[a]->qAlignedSeqLength);
}
}
// Fix for memory leakage bug due to undeleted Alignment Candidate objectts which wasn't selected
// for printing
// delete all AC which are in complement of SelectedAlignmemntPtrs vector
// namely (SelectedAlignmentPtrs/alignmentPtrs)
for (int ii = 0; ii < alignmentPtrs.size(); ii++)
{
int found =0;
for (int jj = 0; jj < selectedAlignmentPtrs.size(); jj++)
{
if (alignmentPtrs[ii] == selectedAlignmentPtrs[jj] )
{
found = 1;
break;
}
}
if (found == 0) delete alignmentPtrs[ii];
}
subreadSequence.Free();
subreadSequenceRC.Free();
} // End of looping over subread intervals within [startIndex, endIndex).
if (params.verbosity >= 3)
allReadAlignments.Print(threadOut);
if (params.concordant) {
allReadAlignments.read = smrtRead;
allReadAlignments.alignMode = ZmwSubreads;
if (startIndex >= 0 && startIndex < int(allReadAlignments.subreadAlignments.size())) {
vector<T_AlignmentCandidate*> selectedAlignmentPtrs =
allReadAlignments.CopySubreadAlignments(startIndex);
for(int alignmentIndex = 0; alignmentIndex < int(selectedAlignmentPtrs.size());
alignmentIndex++) {
FlankTAlignedSeq(selectedAlignmentPtrs[alignmentIndex],
seqdb, genome, params.flankSize);
}
for (intvIndex = 0; intvIndex < subreadIntervals.size(); intvIndex++) {
if (intvIndex == startIndex) continue;
int passDirection = subreadDirections[intvIndex];
int passStartBase = subreadIntervals[intvIndex].start;
int passNumBases = subreadIntervals[intvIndex].end - passStartBase;
if (passNumBases <= params.minReadLength) {continue;}
mapData->metrics.numReads++;
SMRTSequence subread;
subread.ReferenceSubstring(smrtRead, passStartBase, passNumBases);
subread.CopyTitle(smrtRead.title);
// The unrolled alignment should be relative to the entire read.
if (params.clipping == SAMOutput::subread) {
SMRTSequence maskedSubread;
MakeSubreadOfInterval(maskedSubread, smrtRead,
subreadIntervals[intvIndex], params);
allReadAlignments.SetSequence(intvIndex, maskedSubread);
maskedSubread.Free();
} else {
allReadAlignments.SetSequence(intvIndex, smrtRead);
}
for (int alnIndex = 0; alnIndex < selectedAlignmentPtrs.size(); alnIndex++) {
T_AlignmentCandidate * alignment = selectedAlignmentPtrs[alnIndex];
if (alignment->score > params.maxScore) break;
AlignSubreadToAlignmentTarget(allReadAlignments,
subread,
smrtRead,
alignment,
passDirection,
subreadIntervals[intvIndex],
intvIndex,
params, mappingBuffers, threadOut);
if (params.concordantAlignBothDirections) {
AlignSubreadToAlignmentTarget(allReadAlignments,
subread,
smrtRead,
alignment,
((passDirection==0)?1:0),
subreadIntervals[intvIndex],
intvIndex,
params, mappingBuffers, threadOut);
}
} // End of aligning this subread to each selected alignment.
subread.Free();
} // End of aligning each subread to where the template subread aligned to.
for(int alignmentIndex = 0; alignmentIndex < selectedAlignmentPtrs.size();
alignmentIndex++) {
if (selectedAlignmentPtrs[alignmentIndex])
delete selectedAlignmentPtrs[alignmentIndex];
}
} // End of if startIndex >= 0 and < subreadAlignments.size()
} // End of if params.concordant
}
void MapReadsCCS(MappingData<T_SuffixArray, T_GenomeSequence, T_Tuple> *mapData,
MappingBuffers & mappingBuffers,
SMRTSequence & smrtRead,
SMRTSequence & smrtReadRC,
CCSSequence & ccsRead,
const bool readIsCCS,
MappingParameters & params,
const int & associatedRandInt,
ReadAlignments & allReadAlignments,
ofstream & threadOut)
{
DNASuffixArray sarray;
TupleCountTable<T_GenomeSequence, DNATuple> ct;
SequenceIndexDatabase<FASTQSequence> seqdb;
T_GenomeSequence genome;
BWT *bwtPtr;
mapData->ShallowCopySuffixArray(sarray);
mapData->ShallowCopyReferenceSequence(genome);
mapData->ShallowCopySequenceIndexDatabase(seqdb);
mapData->ShallowCopyTupleCountTable(ct);
bwtPtr = mapData->bwtPtr;
SeqBoundaryFtr<FASTQSequence> seqBoundary(&seqdb);
//
// The read must be mapped as a whole, even if it contains subreads.
//
vector<T_AlignmentCandidate*> alignmentPtrs;
mapData->metrics.numReads++;
smrtRead.SubreadStart(0).SubreadEnd(smrtRead.length);
smrtReadRC.SubreadStart(0).SubreadEnd(smrtRead.length);
MapRead(smrtRead, smrtReadRC,
genome, sarray, *bwtPtr, seqBoundary, ct, seqdb, params, mapData->metrics,
alignmentPtrs, mappingBuffers, mapData, semaphores);
//
// Store the mapping quality values.
//
if (alignmentPtrs.size() > 0 and
alignmentPtrs[0]->score < params.maxScore and
params.storeMapQV) {
StoreMapQVs(smrtRead, alignmentPtrs, params);
}
//
// Select de novo ccs-reference alignments for subreads to align to.
//
vector<T_AlignmentCandidate*> selectedAlignmentPtrs =
SelectAlignmentsToPrint(alignmentPtrs, params, associatedRandInt);
//
// Just one sequence is aligned. There is one primary hit, and
// all other are secondary.
//
if (readIsCCS == false or params.useCcsOnly) {
// if -noSplitSubreads or -useccsdenovo.
//
// Record some information for proper SAM Annotation.
//
allReadAlignments.Resize(1);
allReadAlignments.AddAlignmentsForSeq(0, selectedAlignmentPtrs);
if (params.useCcsOnly) {
allReadAlignments.alignMode = CCSDeNovo;
}
else {
allReadAlignments.alignMode = Fullread;
}
allReadAlignments.SetSequence(0, smrtRead);
}
else if (readIsCCS) { // if -useccsall or -useccs
// Flank alignment candidates to both ends.
for(int alignmentIndex = 0; alignmentIndex < selectedAlignmentPtrs.size();
alignmentIndex++) {
FlankTAlignedSeq(selectedAlignmentPtrs[alignmentIndex],
seqdb, genome, params.flankSize);
}
//
// Align the ccs subread to where the denovo sequence mapped (explode).
//
CCSIterator ccsIterator;
FragmentCCSIterator fragmentCCSIterator;
CCSIterator *subreadIterator;
//
// Choose a different iterator over subreads depending on the
// alignment mode. When the mode is allpass, include the
// framgents that are not necessarily full pass.
//
if (params.useAllSubreadsInCcs) {
//
// Use all subreads even if they are not full pass
fragmentCCSIterator.Initialize(&ccsRead, mapData->regionTablePtr);
subreadIterator = &fragmentCCSIterator;
allReadAlignments.alignMode = CCSAllPass;
}
else {
// Use only full pass reads.
ccsIterator.Initialize(&ccsRead);
subreadIterator = &ccsIterator;
allReadAlignments.alignMode = CCSFullPass;
}
allReadAlignments.Resize(subreadIterator->GetNumPasses());
int passDirection, passStartBase, passNumBases;
SMRTSequence subread;
//
// The read was previously set to the smrtRead, which was the
// de novo ccs sequence. Since the alignments of exploded
// reads are reported, the unrolled read should be used as the
// reference when printing.
//
allReadAlignments.read = ccsRead.unrolledRead;
subreadIterator->Reset();
int subreadIndex;
//
// Realign all subreads to selected reference locations.
//
for (subreadIndex = 0; subreadIndex < subreadIterator->GetNumPasses(); subreadIndex++) {
int retval = subreadIterator->GetNext(passDirection, passStartBase, passNumBases);
assert(retval == 1);
if (passNumBases <= params.minReadLength) { continue; }
ReadInterval subreadInterval(passStartBase, passStartBase + passNumBases);
subread.ReferenceSubstring(ccsRead.unrolledRead, passStartBase, passNumBases-1);
subread.CopyTitle(ccsRead.title);
// The unrolled alignment should be relative to the entire read.
allReadAlignments.SetSequence(subreadIndex, ccsRead.unrolledRead);
int alignmentIndex;
//
// Align this subread to all the positions that the de novo
// sequence has aligned to.
//
for (alignmentIndex = 0; alignmentIndex < selectedAlignmentPtrs.size(); alignmentIndex++) {
T_AlignmentCandidate *alignment = selectedAlignmentPtrs[alignmentIndex];
if (alignment->score > params.maxScore) break;
AlignSubreadToAlignmentTarget(allReadAlignments,
subread, ccsRead.unrolledRead,
alignment,
passDirection,
subreadInterval,
subreadIndex,
params, mappingBuffers, threadOut);
} // End of aligning this subread to where the de novo ccs has aligned to.
subread.Free();
} // End of alignining all subreads to where the de novo ccs has aligned to.
} // End of if readIsCCS and !params.useCcsOnly
// Fix for memory leakage due to undeleted Alignment Candidate objectts not selected
// for printing
// delete all AC which are in complement of SelectedAlignmemntPtrs vector
// namely (SelectedAlignmentPtrs/alignmentPtrs)
for (int ii = 0; ii < alignmentPtrs.size(); ii++)
{
int found =0;
for (int jj = 0; jj < selectedAlignmentPtrs.size(); jj++)
{
if (alignmentPtrs[ii] == selectedAlignmentPtrs[jj] )
{
found = 1;
break;
}
}
if (found == 0) delete alignmentPtrs[ii];
}
}
void MapReads(MappingData<T_SuffixArray, T_GenomeSequence, T_Tuple> *mapData)
{
//
// Step 1, initialize local pointers to map data
// for programming shorthand.
//
MappingParameters params = mapData->params;
DNASuffixArray sarray;
TupleCountTable<T_GenomeSequence, DNATuple> ct;
SequenceIndexDatabase<FASTQSequence> seqdb;
T_GenomeSequence genome;
BWT *bwtPtr;
mapData->ShallowCopySuffixArray(sarray);
mapData->ShallowCopyReferenceSequence(genome);
mapData->ShallowCopySequenceIndexDatabase(seqdb);
mapData->ShallowCopyTupleCountTable(ct);
bwtPtr = mapData->bwtPtr;
SeqBoundaryFtr<FASTQSequence> seqBoundary(&seqdb);
int numAligned = 0;
SMRTSequence smrtRead, smrtReadRC;
SMRTSequence unrolledReadRC;
CCSSequence ccsRead;
// Print verbose logging to pid.threadid.log for each thread.
ofstream threadOut;
if (params.verbosity >= 3) {
stringstream ss;
ss << getpid() << "." << pthread_self();
string threadLogFileName = ss.str() + ".log";
threadOut.open(threadLogFileName.c_str(), ios::out|ios::app);
}
//
// Reuse the following buffers during alignment. Since these keep
// storage contiguous, hopefully this will decrease memory
// fragmentation.
//
MappingBuffers mappingBuffers;
while (true) {
// Fetch reads from a zmw
bool readIsCCS = false;
AlignmentContext alignmentContext;
// Associate each sequence to read in with a determined random int.
int associatedRandInt = 0;
bool stop = false;
vector<SMRTSequence> subreads;
bool readsOK = FetchReads(mapData->reader, mapData->regionTablePtr,
smrtRead, ccsRead, subreads,
params, readIsCCS,
alignmentContext.readGroupId,
associatedRandInt, stop);
if (stop) break;
if (not readsOK) continue;
if (params.verbosity > 1) {
cout << "aligning read: " << endl;
smrtRead.PrintSeq(cout);
}
smrtRead.MakeRC(smrtReadRC);
if (readIsCCS) {
ccsRead.unrolledRead.MakeRC(unrolledReadRC);
}
//
// When aligning subreads separately, iterate over each subread, and
// print the alignments for these.
//
ReadAlignments allReadAlignments;
allReadAlignments.read = smrtRead;
if (readIsCCS == false and params.mapSubreadsSeparately) {
// (not readIsCCS and not -noSplitSubreads)
MapReadsNonCCS(mapData, mappingBuffers,
smrtRead, smrtReadRC, ccsRead, subreads,
params, associatedRandInt,
allReadAlignments, threadOut);
} // End of if (readIsCCS == false and params.mapSubreadsSeparately).
else { // if (readIsCCS or (not readIsCCS and -noSplitSubreads) )
MapReadsCCS(mapData, mappingBuffers,
smrtRead, smrtReadRC, ccsRead,
readIsCCS, params, associatedRandInt,
allReadAlignments, threadOut);
} // End of if not (readIsCCS == false and params.mapSubreadsSeparately)
PrintAllReadAlignments(allReadAlignments, alignmentContext,
*mapData->outFilePtr,
*mapData->unalignedFilePtr,
params,
subreads,
#ifdef USE_PBBAM
bamWriterPtr,
#endif
semaphores);
allReadAlignments.Clear();
smrtReadRC.Free();
smrtRead.Free();
if (readIsCCS) {
ccsRead.Free();
unrolledReadRC.Free();
}
numAligned++;
if(numAligned % 100 == 0) {
mappingBuffers.Reset();
}
} // End of while (true).
smrtRead.Free();
smrtReadRC.Free();
unrolledReadRC.Free();
ccsRead.Free();
if (params.nProc > 1) {
#ifdef __APPLE__
sem_wait(semaphores.reader);
sem_post(semaphores.reader);
#else
sem_wait(&semaphores.reader);
sem_post(&semaphores.reader);
#endif
}
if (params.nProc > 1) {
pthread_exit(NULL);
}
threadOut.close();
}
int main(int argc, char* argv[]) {
//
// Configure parameters for refining alignments.
//
MappingParameters params;
ReverseCompressIndex index;
pid_t parentPID;
pid_t *pids;
CommandLineParser clp;
clp.SetHelp(BlasrHelp(params));
clp.SetConciseHelp(BlasrConciseHelp());
clp.SetProgramSummary(BlasrSummaryHelp());
clp.SetProgramName("blasr");
clp.SetVersion(GetVersion());
// Register Blasr options.
RegisterBlasrOptions(clp, params);
// Parse command line args.
clp.ParseCommandLine(argc, argv, params.readsFileNames);
string commandLine;
clp.CommandLineToString(argc, argv, commandLine);
if (params.printVerboseHelp) {
cout << BlasrHelp(params) << endl;
exit(0); // Not a failure.
}
if (params.printDiscussion) {
cout << BlasrDiscussion();
exit(0); // Not a failure.
}
if (argc < 3) {
cout << BlasrConciseHelp();
exit(1); // A failure.
}
int a, b;
for (a = 0; a < 5; a++ ) {
for (b = 0; b < 5; b++ ){
if (a != b) {
SMRTDistanceMatrix[a][b] += params.mismatch;
}
else {
SMRTDistanceMatrix[a][b] += params.match;
}
}
}
if (params.scoreMatrixString != "") {
if (StringToScoreMatrix(params.scoreMatrixString, SMRTDistanceMatrix) == false) {
cout << "ERROR. The string " << endl
<< params.scoreMatrixString << endl
<< "is not a valid format. It should be a quoted, space separated string of " << endl
<< "integer values. The matrix: " << endl
<< " A C G T N" << endl
<< " A 1 2 3 4 5" << endl
<< " C 6 7 8 9 10" << endl
<< " G 11 12 13 14 15" << endl
<< " T 16 17 18 19 20" << endl
<< " N 21 22 23 24 25" << endl
<< " should be specified as \"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\"" << endl;
exit(1);
}
}
cerr << "[INFO] " << GetTimestamp() << " [blasr] started." << endl;
params.MakeSane();
//
// The random number generator is used for subsampling for debugging
// and testing consensus and selecting hits when hit policy is random
// or randombest.
//
if (params.useRandomSeed == true) {
InitializeRandomGenerator(params.randomSeed);
}
else {
InitializeRandomGeneratorWithTime();
}
//
// Various aspects of timing are stored here. However this isn't
// quite finished.
//
MappingMetrics metrics;
ofstream fullMetricsFile;
if (params.fullMetricsFileName != "") {
CrucialOpen(params.fullMetricsFileName, fullMetricsFile, std::ios::out);
metrics.SetStoreList();
}
//
// If reading a separate region table, there is a 1-1 correspondence
// between region table and bas file.
//
if (params.readSeparateRegionTable) {
if (FileOfFileNames::IsFOFN(params.regionTableFileName)) {
FileOfFileNames::FOFNToList(params.regionTableFileName, params.regionTableFileNames);
}
else {
params.regionTableFileNames.push_back(params.regionTableFileName);
}
}
if (params.regionTableFileNames.size() != 0 and
params.regionTableFileNames.size() != params.queryFileNames.size()) {
cout << "Error, there are not the same number of region table files as input files." << endl;
exit(1);
}
// If reading a separate ccs fofn, there is a 1-1 corresponence
// between ccs fofn and base file.
if (params.readSeparateCcsFofn) {
if (FileOfFileNames::IsFOFN(params.ccsFofnFileName)) {
FileOfFileNames::FOFNToList(params.ccsFofnFileName, params.ccsFofnFileNames);
}
else {
params.ccsFofnFileNames.push_back(params.ccsFofnFileName);
}
}
if (params.ccsFofnFileNames.size() != 0 and
params.ccsFofnFileNames.size() != params.queryFileNames.size()) {
cout << "Error, there are not the same number of ccs files as input files." << endl;
exit(1);
}
parentPID = getpid();
SequenceIndexDatabase<FASTASequence> seqdb;
SeqBoundaryFtr<FASTASequence> seqBoundary(&seqdb);
//
// Initialize the sequence index database if it used. If it is not
// specified, it is initialized by default when reading a multiFASTA
// file.
//
if (params.useSeqDB) {
ifstream seqdbin;
CrucialOpen(params.seqDBName, seqdbin);
seqdb.ReadDatabase(seqdbin);
}
//
// Make sure the reads file exists and can be opened before
// trying to read any of the larger data structures.
//
FASTASequence fastaGenome;
T_Sequence genome;
FASTAReader genomeReader;
//
// The genome is in normal FASTA, or condensed (lossy homopolymer->unipolymer)