-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathBAMParser.cs
1380 lines (1217 loc) · 52.6 KB
/
BAMParser.cs
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using Bio.Algorithms.Alignment;
using Bio.Extensions;
using Bio.IO.SAM;
using Bio.Util;
namespace Bio.IO.BAM
{
/// <summary>
/// A BAMParser reads from a source of binary data that is formatted according to the BAM
/// file specification, and converts the data to in-memory SequenceAlignmentMap object.
/// Documentation for the latest BAM file format can be found at
/// http://samtools.sourceforge.net/SAM1.pdf
/// </summary>
public partial class BAMParser : IDisposable, ISequenceAlignmentParser
{
/// <summary>
/// Symbols supported by BAM.
/// </summary>
private const string BAMAlphabet = "=ACMGRSVTWYHKDBN";
private static readonly byte[] BAMAlphabetAsBytes = BAMAlphabet.ToByteArray();
/// <summary>
/// Holds the BAM file stream.
/// </summary>
private Stream readStream;
/// <summary>
/// Flag to indicate whether the BAM file is compressed or not.
/// </summary>
private bool isCompressed;
/// <summary>
/// Holds the names of the reference sequence.
/// </summary>
private RegexValidatedStringList refSeqNames;
/// <summary>
/// Holds the length of the reference sequences.
/// </summary>
private List<int> refSeqLengths;
/// <summary>
/// A temporary file stream to hold uncompressed blocks.
/// </summary>
private Stream deCompressedStream;
/// <summary>
/// Holds the current position of the compressed BAM file stream.
/// Used while creating BAMIndex objects from a BAM file and while parsing a BAM file using a BAM index file.
/// </summary>
private long currentCompressedBlockStartPos;
/// <summary>
/// Holds the bam index object created from a BAM file.
/// </summary>
private BAMIndex bamIndex;
/// <summary>
/// Flag to indicate to whether to create BAMIndex while parsing BAM file or not.
/// </summary>
private bool createBamIndex = false;
/// <summary>
/// The default constructor which chooses the default encoding based on the alphabet.
/// </summary>
public BAMParser()
{
RefSequences = new List<ISequence>();
refSeqNames = new RegexValidatedStringList(SAMAlignedSequenceHeader.RNameRegxExprPattern);
refSeqLengths = new List<int>();
}
/// <summary>
/// Gets the name of the sequence alignment parser being
/// implemented. This is intended to give the
/// developer some information of the parser type.
/// </summary>
public string Name
{
get { return Properties.Resource.BAM_NAME; }
}
/// <summary>
/// Gets the description of the sequence alignment parser being
/// implemented. This is intended to give the
/// developer some information of the parser.
/// </summary>
public string Description
{
get { return Properties.Resource.BAMPARSER_DESCRIPTION; }
}
/// <summary>
/// The alphabet to use for sequences in parsed SequenceAlignmentMap objects.
/// Always returns singleton instance of SAMDnaAlphabet.
/// </summary>
public IAlphabet Alphabet
{
get
{
return SAMDnaAlphabet.Instance;
}
set
{
throw new NotSupportedException(Properties.Resource.BAMParserAlphabetCantBeSet);
}
}
/// <summary>
/// Gets the file extensions that the parser implementation
/// will support.
/// </summary>
public string SupportedFileTypes
{
get { return Properties.Resource.BAM_FILEEXTENSION; }
}
/// <summary>
/// Reference sequences, used to resolve "=" symbol in the sequence data.
/// </summary>
public IList<ISequence> RefSequences { get; private set; }
/// <summary>
/// Returns a boolean value indicating whether a BAM file is compressed or uncompressed.
/// </summary>
/// <param name="array">Byte array containing first 4 bytes of a BAM file</param>
/// <returns>Returns true if the specified byte array indicates that the BAM file is compressed else returns false.</returns>
private static bool IsCompressedBAMFile(byte[] array)
{
return array[0] == 31
&& array[1] == 139
&& array[2] == 8;
}
/// <summary>
/// Returns a boolean value indicating whether a BAM file is valid uncompressed BAM file or not.
/// </summary>
/// <param name="array">Byte array containing first 4 bytes of a BAM file</param>
/// <returns>Returns true if the specified byte array indicates a valid uncompressed BAM file else returns false.</returns>
private static bool IsUnCompressedBAMFile(byte[] array)
{
return array[0] == 66
&& array[1] == 65
&& array[2] == 77
&& array[3] == 1;
}
/// <summary>
/// Gets optional value depending on the valuetype.
/// </summary>
/// <param name="valueType">Value Type.</param>
/// <param name="array">Byte array to read from.</param>
/// <param name="startIndex">Start index of value in the array.</param>
private static object GetOptionalValue(char valueType, byte[] array, ref int startIndex)
{
object obj;
int len;
switch (valueType)
{
case 'A': // Printable character
obj = (char)array[startIndex];
startIndex++;
break;
case 'c': //signed 8-bit integer
int intValue = (array[startIndex] & 0x7F);
if ((array[startIndex] & 0x80) == 0x80)
{
intValue = intValue + sbyte.MinValue;
}
obj = intValue;
startIndex++;
break;
case 'C':
obj = (uint)array[startIndex];
startIndex++;
break;
case 's':
obj = Helper.GetInt16(array, startIndex);
startIndex += 2;
break;
case 'S':
obj = Helper.GetUInt16(array, startIndex);
startIndex += 2;
break;
case 'i':
obj = Helper.GetInt32(array, startIndex);
startIndex += 4;
break;
case 'I':
obj = Helper.GetUInt32(array, startIndex);
startIndex += 4;
break;
case 'f':
obj = Helper.GetSingle(array, startIndex);
startIndex += 4;
break;
case 'Z':
len = GetStringLength(array, startIndex);
obj = Encoding.UTF8.GetString(array, startIndex, len - 1);
startIndex += len;
break;
case 'H':
len = GetStringLength(array, startIndex);
obj = Helper.GetHexString(array, startIndex, len - 1);
startIndex += len;
break;
case 'B':
char arrayType = (char)array[startIndex];
startIndex++;
int arrayLen = Helper.GetInt32(array, startIndex);
startIndex += 4;
StringBuilder strBuilder = new StringBuilder();
strBuilder.Append(arrayType);
for (int i = 0; i < arrayLen; i++)
{
strBuilder.Append(',');
string value = GetOptionalValue(arrayType, array, ref startIndex).ToString();
strBuilder.Append(value);
}
obj = strBuilder.ToString();
break;
default:
throw new Exception(Properties.Resource.BAM_InvalidOptValType);
}
return obj;
}
/// <summary>
/// Gets the length of the string in byte array.
/// </summary>
/// <param name="array">Byte array which contains string.</param>
/// <param name="startIndex">Start index of array from which string is stored.</param>
private static int GetStringLength(byte[] array, int startIndex)
{
int i = startIndex;
while (i < array.Length && array[i] != '\x0')
{
i++;
}
return i + 1 - startIndex;
}
/// <summary>
/// Gets equivalent sequence char for the specified encoded value.
/// </summary>
/// <param name="encodedValue">Encoded value.</param>
private static byte GetSeqCharAsByte(int encodedValue)
{
if (encodedValue >= 0 && encodedValue <= BAMAlphabetAsBytes.Length)
{
return BAMAlphabetAsBytes[encodedValue];
}
throw new Exception(Properties.Resource.BAM_InvalidEncodedSequenceValue);
}
/// <summary>
/// Decompresses specified compressed stream to out stream.
/// </summary>
/// <param name="compressedStream">Compressed stream to decompress.</param>
/// <param name="outStream">Out stream.</param>
private static void Decompress(Stream compressedStream, Stream outStream)
{
using (var stream = new GZipStream(compressedStream, CompressionMode.Decompress, true))
{
stream.CopyTo(outStream);
}
}
// Gets list of possible bins for a given start and end reference sequence co-ordinates.
private static IList<uint> Reg2Bins(uint start, uint end)
{
List<uint> bins = new List<uint>();
uint k;
--end;
bins.Add(0);
for (k = 1 + (start >> 26); k <= 1 + (end >> 26); ++k) bins.Add(k);
for (k = 9 + (start >> 23); k <= 9 + (end >> 23); ++k) bins.Add(k);
for (k = 73 + (start >> 20); k <= 73 + (end >> 20); ++k) bins.Add(k);
for (k = 585 + (start >> 17); k <= 585 + (end >> 17); ++k) bins.Add(k);
for (k = 4681 + (start >> 14); k <= 4681 + (end >> 14); ++k) bins.Add(k);
return bins;
}
// Gets all chunks for the specified ref sequence index.
private static IList<Chunk> GetChunks(BAMReferenceIndexes refIndex)
{
List<Chunk> chunks = new List<Chunk>();
foreach (Bin bin in refIndex.Bins)
{
chunks.InsertRange(chunks.Count, bin.Chunks);
}
return SortAndMergeChunks(chunks);
}
// Gets chunks for specified ref seq index, start and end co-ordinate this method considers linear index also.
private static IList<Chunk> GetChunks(BAMReferenceIndexes refIndex, int start, int end)
{
//get all bins that overlap
IList<uint> binnumbers = Reg2Bins((uint)start, (uint)end);
//now only get those that match
List<Chunk> chunks = refIndex.Bins.Where(B => binnumbers.Contains(B.BinNumber)).SelectMany(x=>x.Chunks).ToList();
//now use linear indexing to filter any chunks that end before the first start
if (refIndex.LinearIndex.Count > 0)
{
var binStart = start >> 14;
FileOffset minStart;
if (refIndex.LinearIndex.Count > binStart)
{
minStart = refIndex.LinearIndex[binStart];
}
else
{
minStart = refIndex.LinearIndex.Last();
}
chunks = chunks.Where(x => x.ChunkEnd >= minStart).ToList();
}
return SortAndMergeChunks(chunks);
}
/// <summary>
/// Sorts and merges the overlapping chunks.
/// </summary>
/// <param name="chunks">Chunks to sort and merge.</param>
private static List<Chunk> SortAndMergeChunks(IEnumerable<Chunk> chunks)
{
List<Chunk> sortedChunks = chunks.OrderBy(C => C, ChunkSorterForMerging.GetInstance()).ToList();
for (int i = 0; i < sortedChunks.Count - 1; i++)
{
Chunk currentChunk = sortedChunks[i];
Chunk nextChunk = sortedChunks[i + 1];
if (nextChunk.ChunkStart.CompareTo(currentChunk.ChunkStart) >= 0 && nextChunk.ChunkStart.CompareTo(currentChunk.ChunkEnd) <= 0)
{
// merge chunks.
currentChunk.ChunkEnd = currentChunk.ChunkEnd.CompareTo(nextChunk.ChunkEnd) >= 0 ? currentChunk.ChunkEnd : nextChunk.ChunkEnd;
sortedChunks.RemoveAt(i + 1);
i--;
}
}
return sortedChunks;
}
/// <summary>
/// Returns a SequenceAlignmentMap object by parsing a BAM file.
/// </summary>
/// <param name="stream">Stream to read.</param>
/// <returns>SequenceAlignmentMap object.</returns>
public SequenceAlignmentMap ParseOne(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
return GetAlignment(stream);
}
/// <summary>
/// Returns a SequenceAlignmentMap object by parsing a BAM file.
/// </summary>
/// <param name="stream">Stream to read.</param>
/// <returns>SequenceAlignmentMap object.</returns>
ISequenceAlignment IParser<ISequenceAlignment>.ParseOne(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
return GetAlignment(stream);
}
/// <summary>
/// Returns an iterator over a set of SAMAlignedSequences retrieved from a parsed BAM file.
/// </summary>
/// <param name="stream">Stream to read</param>
/// <returns>IEnumerable SAMAlignedSequence object.</returns>
IEnumerable<ISequenceAlignment> IParser<ISequenceAlignment>.Parse(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
yield return GetAlignment(stream);
}
/// <summary>
/// Returns an iterator over a set of SAMAlignedSequences retrieved from a parsed BAM file.
/// </summary>
/// <param name="stream">Stream to read</param>
/// <returns>IEnumerable SAMAlignedSequence object.</returns>
public IEnumerable<SAMAlignedSequence> Parse(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
return this.GetAlignmentMapIterator(stream);
}
/// <summary>
/// Returns the create sequence alignment map.
/// </summary>
/// <param name="reader"></param>
/// <param name="bamIndexStorage"></param>
/// <param name="refSeqName"></param>
/// <param name="refSeqIndex"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
internal SequenceAlignmentMap GetAlignmentMap(Stream reader, BAMIndexStorage bamIndexStorage = null,
string refSeqName = null, int? refSeqIndex = null, int start = 0, int end = int.MaxValue)
{
if (reader == null || reader.Length == 0)
{
throw new Exception(Properties.Resource.BAM_InvalidBAMFile);
}
readStream = reader;
ValidateReader();
SAMAlignmentHeader header = this.GetHeader();
SequenceAlignmentMap seqMap = null;
if (refSeqIndex.HasValue && refSeqName == null)
{
// verify whether the chromosome index is there in the header or not.
if (refSeqIndex < 0 || refSeqIndex >= header.ReferenceSequences.Count)
{
throw new ArgumentOutOfRangeException("refSeqIndex");
}
}
else if (refSeqName != null && !refSeqIndex.HasValue)
{
refSeqIndex = refSeqNames.IndexOf(refSeqName);
if (refSeqIndex < 0 || !refSeqIndex.HasValue)
{
string message = string.Format(CultureInfo.InvariantCulture, Properties.Resource.BAM_RefSeqNotFound, refSeqName);
throw new ArgumentException(message, "refSeqName");
}
}
else if (refSeqIndex.HasValue && refSeqName != null)
{
throw new ArgumentException("Received values for params reSeqIndex and refSeqName. Only one parameter can have a value, not both.");
}
if (refSeqIndex.HasValue)
{
if (bamIndexStorage != null)
{
GetAlignmentWithIndex(bamIndexStorage, (int)refSeqIndex, start, end, header, ref seqMap);
}
else
{
throw new ArgumentNullException("refSeqIndex");
}
}
else
{
GetAlignmentWithoutIndex(header, ref seqMap);
}
return seqMap;
}
/// <summary>
/// Returns SequenceAlignmentMap object by parsing specified BAM stream.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
internal SequenceAlignmentMap GetAlignment(Stream reader)
{
return GetAlignmentMap(reader);
}
internal IEnumerable<SAMAlignedSequence> GetAlignmentMapIterator(Stream reader, BAMIndexStorage bamIndexStorage = null,
string refSeqName = null, int? refSeq = null, int start = 0, int end = int.MaxValue)
{
if (reader == null || reader.Length == 0)
{
throw new Exception(Properties.Resource.BAM_InvalidBAMFile);
}
readStream = reader;
ValidateReader();
SAMAlignmentHeader header = this.GetHeader();
if (refSeq.HasValue && refSeqName == null)
{
// verify whether the chromosome index is there in the header or not.
if (refSeq < 0 || refSeq >= header.ReferenceSequences.Count)
{
throw new ArgumentOutOfRangeException("refSeq");
}
}
else if (refSeqName != null && !refSeq.HasValue)
{
refSeq = refSeqNames.IndexOf(refSeqName);
if (refSeq < 0 || !refSeq.HasValue)
{
string message = string.Format(CultureInfo.InvariantCulture, Properties.Resource.BAM_RefSeqNotFound, refSeqName);
throw new ArgumentException(message, "refSeqName");
}
}
else if (refSeq.HasValue && refSeqName != null)
{
throw new ArgumentException("Received values for params reSeqIndex and refSeqName. Only one parameter can have a value, not both.");
}
if (refSeq.HasValue)
{
if (bamIndexStorage != null)
{
foreach (SAMAlignedSequence seq in GetAlignmentWithIndexYield(bamIndexStorage, (int)refSeq, start, end))
{
yield return seq;
}
}
else
{
throw new ArgumentNullException("refSeqIndex");
}
}
else
{
foreach (SAMAlignedSequence seq in GetAlignmentWithoutIndexYield())
{
yield return seq;
}
}
}
internal IEnumerable<SAMAlignedSequence> GetAlignmentWithIndexYield(BAMIndexStorage bamIndexStorage, int refSeqIndex, int start, int end)
{
IList<Chunk> chunks;
BAMIndex bamIndexInfo = bamIndexStorage.Read();
if (refSeqIndex != -1 && bamIndexInfo.RefIndexes.Count <= refSeqIndex)
{
throw new ArgumentOutOfRangeException("refSeqIndex");
}
BAMReferenceIndexes refIndex = bamIndexInfo.RefIndexes[refSeqIndex];
if (start == 0 && end == int.MaxValue)
{
chunks = GetChunks(refIndex);
}
else
{
chunks = GetChunks(refIndex, start, end);
}
IList<SAMAlignedSequence> alignedSeqs = GetAlignedSequences(chunks, start, end);
foreach (SAMAlignedSequence alignedSeq in alignedSeqs)
{
yield return alignedSeq;
}
readStream = null;
}
private void GetAlignmentWithIndex(BAMIndexStorage bamIndexStorage, int refSeqIndex, int start, int end,
SAMAlignmentHeader header, ref SequenceAlignmentMap seqMap)
{
IList<Chunk> chunks;
seqMap = new SequenceAlignmentMap(header);
BAMIndex bamIndexInfo = bamIndexStorage.Read();
if (refSeqIndex != -1 && bamIndexInfo.RefIndexes.Count <= refSeqIndex)
{
throw new ArgumentOutOfRangeException("refSeqIndex");
}
BAMReferenceIndexes refIndex = bamIndexInfo.RefIndexes[refSeqIndex];
if (start == 0 && end == int.MaxValue)
{
chunks = GetChunks(refIndex);
}
else
{
chunks = GetChunks(refIndex, start, end);
}
IList<SAMAlignedSequence> alignedSeqs = GetAlignedSequences(chunks, start, end);
foreach (SAMAlignedSequence alignedSeq in alignedSeqs)
{
seqMap.QuerySequences.Add(alignedSeq);
}
readStream = null;
}
private void GetAlignmentWithoutIndex(SAMAlignmentHeader header, ref SequenceAlignmentMap seqMap)
{
Chunk lastChunk = null;
FileOffset lastOffSet = new FileOffset(0,0);
BAMReferenceIndexes refIndices = null;
int lastBin = int.MaxValue;
int lastRefSeqIndex = 0;
int lastRefPos = Int32.MinValue;
if (createBamIndex)
{
bamIndex = new BAMIndex();
foreach (int len in this.refSeqLengths)
{
this.bamIndex.RefIndexes.Add(new BAMReferenceIndexes(len));
}
refIndices = bamIndex.RefIndexes[0];
}
if (!createBamIndex && seqMap == null)
{
seqMap = new SequenceAlignmentMap(header);
}
while (!IsEOF())
{
if (createBamIndex)
{
lastOffSet=new FileOffset((ulong)currentCompressedBlockStartPos,(ushort)deCompressedStream.Position);
}
SAMAlignedSequence alignedSeq = GetAlignedSequence(0, int.MaxValue);
// BAM indexing
if (createBamIndex)
{
//TODO: This linear lookup is probably performance murder if many names
int curRefSeqIndex = refSeqNames.IndexOf(alignedSeq.RName);
if (lastRefSeqIndex != curRefSeqIndex)
{
//switch to a new reference sequence and force the last bins to be unequal
if (lastRefSeqIndex > curRefSeqIndex)
{
throw new InvalidDataException("The BAM file is not sorted. " + alignedSeq.QName + " appears after a later sequence");
}
refIndices = bamIndex.RefIndexes[curRefSeqIndex];
lastBin = int.MaxValue;
lastRefSeqIndex = curRefSeqIndex;
lastRefPos = Int32.MinValue;
}
if (lastRefPos > alignedSeq.Pos)
{
throw new InvalidDataException("The BAM file is not sorted. " + alignedSeq.QName + " appears after a later sequence");
}
lastRefPos = alignedSeq.Pos;
//update Bins when we switch over
if (lastBin != alignedSeq.Bin)
{
//do we need to add a new bin here or have we already seen it?
Bin bin = refIndices.Bins.FirstOrDefault(B => B.BinNumber == alignedSeq.Bin);
if (bin == null)
{
bin = new Bin();
bin.BinNumber = (uint)alignedSeq.Bin;
refIndices.Bins.Add(bin);
}
//update the chunk we have just finished with, this code also appears outside the loop
if (lastChunk != null)
{
lastChunk.ChunkEnd = lastOffSet;
}
//make a new chunk for the new bin
Chunk chunk = new Chunk();
chunk.ChunkStart = lastOffSet;
bin.Chunks.Add(chunk);
//update variables
lastChunk = chunk;
lastBin = alignedSeq.Bin;
}
//UPDATE LINEAR INDEX AND PROCESS READ FOR META-DATA
refIndices.AddReadToIndexInformation(alignedSeq,lastOffSet);
}
if (!createBamIndex && alignedSeq != null)
{
seqMap.QuerySequences.Add(alignedSeq);
}
}
// BAM indexing
if (createBamIndex)
{
ulong compressedOff=(ulong)readStream.Position;
ushort uncompressedEnd=0;
//TODO: Shouldn't this always be true? Or go to max value?
if (deCompressedStream != null) {
uncompressedEnd = (ushort)deCompressedStream.Position;
}
FileOffset veryLast=new FileOffset(compressedOff,uncompressedEnd);
lastChunk.ChunkEnd=veryLast;
foreach (var ri in bamIndex.RefIndexes)
{
ri.Freeze();
}
}
}
private IEnumerable<SAMAlignedSequence> GetAlignmentWithoutIndexYield()
{
if (createBamIndex)
{
throw new InvalidOperationException("It was assumed that the index would not be created during enumeration, please check the logic");
}
while (!IsEOF())
{
SAMAlignedSequence alignedSeq = GetAlignedSequence(0, int.MaxValue);
yield return alignedSeq;
}
}
/// <summary>
/// Returns BAMIndex by parsing specified BAM stream.
/// </summary>
/// <param name="stream">Stream to read.</param>
public BAMIndex GetIndexFromBAMStorage(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
try
{
createBamIndex = true;
GetAlignment(stream);
ReduceChunks();
return bamIndex;
}
finally
{
createBamIndex = false;
}
}
/// <summary>
/// Gets the SAMAlignmentHeader from the specified stream.
/// Note that this method resets the specified stream to BOF before reading.
/// </summary>
/// <param name="bamStream">BAM file stream.</param>
public SAMAlignmentHeader GetHeader(Stream bamStream)
{
if (bamStream == null)
{
throw new ArgumentNullException("bamStream");
}
readStream = bamStream;
ValidateReader();
return GetHeader();
}
/// <summary>
/// Returns an aligned sequence by parses the BAM file.
/// </summary>
/// <param name="isReadOnly">
/// Flag to indicate whether the resulting sequence in the SAMAlignedSequence should be in
/// readonly mode or not. If this flag is set to true then the resulting sequence's
/// isReadOnly property will be set to true, otherwise it will be set to false.
/// </param>
public SAMAlignedSequence GetAlignedSequence(bool isReadOnly)
{
return GetAlignedSequence(0, int.MaxValue);
}
/// <summary>
/// Implements the IDisposable interface
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes this object.
/// </summary>
/// <param name="disposing">If true disposes resources held by this instance.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (readStream != null)
{
readStream.Dispose();
readStream = null;
}
if (deCompressedStream != null)
{
deCompressedStream.Dispose();
deCompressedStream = null;
}
}
}
/// <summary>
/// Validates the BAM stream.
/// </summary>
private void ValidateReader()
{
isCompressed = true;
byte[] array = new byte[4];
if (readStream.Read(array, 0, 4) != 4)
{
// cannot read file properly.
throw new Exception(Properties.Resource.BAM_InvalidBAMFile);
}
isCompressed = IsCompressedBAMFile(array);
if (!isCompressed)
{
if (!IsUnCompressedBAMFile(array))
{
// Neither compressed BAM file nor uncompressed BAM file header.
throw new Exception(Properties.Resource.BAM_InvalidBAMFile);
}
}
readStream.Seek(0, SeekOrigin.Begin);
}
/// <summary>
/// Parses the BAM file and returns the Header.
/// </summary>
private SAMAlignmentHeader GetHeader()
{
SAMAlignmentHeader header = new SAMAlignmentHeader();
refSeqNames = new RegexValidatedStringList(SAMAlignedSequenceHeader.RNameRegxExprPattern);
refSeqLengths = new List<int>();
readStream.Seek(0, SeekOrigin.Begin);
this.deCompressedStream = null;
byte[] array = new byte[8];
ReadUnCompressedData(array, 0, 8);
int l_text = Helper.GetInt32(array, 4);
byte[] samHeaderData = new byte[l_text];
if (l_text != 0)
{
ReadUnCompressedData(samHeaderData, 0, l_text);
}
ReadUnCompressedData(array, 0, 4);
int noofRefSeqs = Helper.GetInt32(array, 0);
for (int i = 0; i < noofRefSeqs; i++)
{
ReadUnCompressedData(array, 0, 4);
int len = Helper.GetInt32(array, 0);
byte[] refName = new byte[len];
ReadUnCompressedData(refName, 0, len);
ReadUnCompressedData(array, 0, 4);
int refLen = Helper.GetInt32(array, 0);
refSeqNames.Add(Encoding.UTF8.GetString(refName, 0, refName.Length - 1));
refSeqLengths.Add(refLen);
}
if (samHeaderData.Length != 0)
{
string str = Encoding.UTF8.GetString(samHeaderData, 0, samHeaderData.Length);
using (StringReader reader = new StringReader(str))
{
header = SAMParser.ParseSAMHeader(reader);
}
}
header.ReferenceSequences.Clear();
for (int i = 0; i < refSeqNames.Count; i++)
{
string refname = refSeqNames[i];
int length = refSeqLengths[i];
header.ReferenceSequences.Add(new ReferenceSequenceInfo(refname, length));
}
return header;
}
/// <summary>
/// Merges small chunks belongs to a bin which are in the same compressed block.
/// This will reduce number of seek calls required.
/// </summary>
private void ReduceChunks()
{
if (bamIndex == null)
return;
for (int i = 0; i < bamIndex.RefIndexes.Count; i++)
{
BAMReferenceIndexes bamRefIndex = bamIndex.RefIndexes[i];
for (int j = 0; j < bamRefIndex.Bins.Count; j++)
{
Bin bin = bamRefIndex.Bins[j];
int lastIndex = 0;
int noofchunksToRemove = 0;
for (int k = 1; k < bin.Chunks.Count; k++)
{
// check for the chunks which are in the same compressed blocks.
//note picard merges the same or adjacent blocks, though I think that may be a coding error oon their part
if (bin.Chunks[lastIndex].ChunkEnd.CompressedBlockOffset == bin.Chunks[k].ChunkStart.CompressedBlockOffset)
{
bin.Chunks[lastIndex].ChunkEnd = bin.Chunks[k].ChunkEnd;
noofchunksToRemove++;
}
else
{
bin.Chunks[++lastIndex] = bin.Chunks[k];
}
}
if (noofchunksToRemove > 0)
{
for (int index = 0; index < noofchunksToRemove; index++)
{
bin.Chunks.RemoveAt(bin.Chunks.Count - 1);
}
}
}
}
}
/// <summary>
/// Returns an aligned sequence by parses the BAM file.
/// </summary>
private SAMAlignedSequence GetAlignedSequence(int start, int end)
{
byte[] array = new byte[4];
ReadUnCompressedData(array, 0, 4);
int blockLen = Helper.GetInt32(array, 0);
byte[] alignmentBlock = new byte[blockLen];
ReadUnCompressedData(alignmentBlock, 0, blockLen);
SAMAlignedSequence alignedSeq = new SAMAlignedSequence();
int value;
UInt32 UnsignedValue;
// 0-4 bytes
int refSeqIndex = Helper.GetInt32(alignmentBlock, 0);
alignedSeq.SetPreValidatedRName(refSeqIndex == -1 ? "*" : this.refSeqNames[refSeqIndex]);
// 4-8 bytes
alignedSeq.Pos = Helper.GetInt32(alignmentBlock, 4) + 1;
// if there is no overlap no need to parse further.
// BAMPos > closedEnd
// => (alignedSeq.Pos - 1) > end -1
if (alignedSeq.Pos > end)
{
return null;
}
// 8 - 12 bytes "bin<<16|mapQual<<8|read_name_len"
UnsignedValue = Helper.GetUInt32(alignmentBlock, 8);
// 10 -12 bytes
alignedSeq.Bin = (int)(UnsignedValue & 0xFFFF0000) >> 16;
// 9th bytes
alignedSeq.MapQ = (int)(UnsignedValue & 0x0000FF00) >> 8;
// 8th bytes
int queryNameLen = (int)(UnsignedValue & 0x000000FF);
// 12 - 16 bytes
UnsignedValue = Helper.GetUInt32(alignmentBlock, 12);
// 14-16 bytes
int flagValue = (int)(UnsignedValue & 0xFFFF0000) >> 16;
alignedSeq.Flag = (SAMFlags)flagValue;
// 12-14 bytes
int cigarLen = (int)(UnsignedValue & 0x0000FFFF);
// 16-20 bytes
int readLen = Helper.GetInt32(alignmentBlock, 16);
// 20-24 bytes
int mateRefSeqIndex = Helper.GetInt32(alignmentBlock, 20);
if (mateRefSeqIndex != -1)
{