]> git.donarmstrong.com Git - bamtools.git/blob - src/api/internal/index/BamStandardIndex_p.h
Updated file headers (filename, license, description, etc)
[bamtools.git] / src / api / internal / index / BamStandardIndex_p.h
1 // ***************************************************************************
2 // BamStandardIndex.h (c) 2010 Derek Barnett
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 10 November 2011 (DB)
6 // ---------------------------------------------------------------------------
7 // Provides index operations for the standardized BAM index format (".bai")
8 // ***************************************************************************
9
10 #ifndef BAM_STANDARD_INDEX_FORMAT_H
11 #define BAM_STANDARD_INDEX_FORMAT_H
12
13 //  -------------
14 //  W A R N I N G
15 //  -------------
16 //
17 // This file is not part of the BamTools API.  It exists purely as an
18 // implementation detail.  This header file may change from version to
19 // version without notice, or even be removed.
20 //
21 // We mean it.
22
23 #include "api/BamAux.h"
24 #include "api/BamIndex.h"
25 #include "api/IBamIODevice.h"
26 #include <map>
27 #include <set>
28 #include <string>
29 #include <vector>
30
31 namespace BamTools {
32 namespace Internal {
33
34 // -----------------------------------------------------------------------------
35 // BamStandardIndex data structures
36
37 // defines start and end of a contiguous run of alignments
38 struct BaiAlignmentChunk {
39
40     // data members
41     uint64_t Start;
42     uint64_t Stop;
43
44     // constructor
45     BaiAlignmentChunk(const uint64_t& start = 0,
46                       const uint64_t& stop = 0)
47         : Start(start)
48         , Stop(stop)
49     { }
50 };
51
52 // comparison operator (for sorting)
53 inline
54 bool operator<(const BaiAlignmentChunk& lhs, const BaiAlignmentChunk& rhs) {
55     return lhs.Start < rhs.Start;
56 }
57
58 // convenience typedef for a list of all alignment 'chunks' in a BAI bin
59 typedef std::vector<BaiAlignmentChunk> BaiAlignmentChunkVector;
60
61 // convenience typedef for a map of all BAI bins in a reference (ID => chunks)
62 typedef std::map<uint32_t, BaiAlignmentChunkVector> BaiBinMap;
63
64 // convenience typedef for a list of all 'linear offsets' in a reference
65 typedef std::vector<uint64_t> BaiLinearOffsetVector;
66
67 // contains all fields necessary for building, loading, & writing
68 // full BAI index data for a single reference
69 struct BaiReferenceEntry {
70
71     // data members
72     int32_t ID;
73     BaiBinMap Bins;
74     BaiLinearOffsetVector LinearOffsets;
75
76     // ctor
77     BaiReferenceEntry(const int32_t& id = -1)
78         : ID(id)
79     { }
80 };
81
82 // provides (persistent) summary of BaiReferenceEntry's index data
83 struct BaiReferenceSummary {
84
85     // data members
86     int NumBins;
87     int NumLinearOffsets;
88     uint64_t FirstBinFilePosition;
89     uint64_t FirstLinearOffsetFilePosition;
90
91     // ctor
92     BaiReferenceSummary(void)
93         : NumBins(0)
94         , NumLinearOffsets(0)
95         , FirstBinFilePosition(0)
96         , FirstLinearOffsetFilePosition(0)
97     { }
98 };
99
100 // convenience typedef for describing a full BAI index file summary
101 typedef std::vector<BaiReferenceSummary> BaiFileSummary;
102
103 // end BamStandardIndex data structures
104 // -----------------------------------------------------------------------------
105
106 class BamStandardIndex : public BamIndex {
107
108     // ctor & dtor
109     public:
110         BamStandardIndex(Internal::BamReaderPrivate* reader);
111         ~BamStandardIndex(void);
112
113     // BamIndex implementation
114     public:
115         // builds index from associated BAM file & writes out to index file
116         bool Create(void);
117         // returns whether reference has alignments or no
118         bool HasAlignments(const int& referenceID) const;
119         // attempts to use index data to jump to @region, returns success/fail
120         // a "successful" jump indicates no error, but not whether this region has data
121         //   * thus, the method sets a flag to indicate whether there are alignments
122         //     available after the jump position
123         bool Jump(const BamTools::BamRegion& region, bool* hasAlignmentsInRegion);
124         // loads existing data from file into memory
125         bool Load(const std::string& filename);
126     public:
127         // returns format's file extension
128         static const std::string Extension(void);
129
130     // internal methods
131     private:
132
133         // index file ops
134         void CheckMagicNumber(void);
135         void CloseFile(void);
136         bool IsDeviceOpen(void) const;
137         void OpenFile(const std::string& filename, IBamIODevice::OpenMode mode);
138         void Seek(const int64_t& position, const int origin);
139         int64_t Tell(void) const;
140
141         // BAI index building methods
142         void ClearReferenceEntry(BaiReferenceEntry& refEntry);
143         void SaveAlignmentChunkToBin(BaiBinMap& binMap,
144                                      const uint32_t& currentBin,
145                                      const uint64_t& currentOffset,
146                                      const uint64_t& lastOffset);
147         void SaveLinearOffsetEntry(BaiLinearOffsetVector& offsets,
148                                    const int& alignmentStartPosition,
149                                    const int& alignmentStopPosition,
150                                    const uint64_t& lastOffset);
151
152         // random-access methods
153         void AdjustRegion(const BamRegion& region, uint32_t& begin, uint32_t& end);
154         void CalculateCandidateBins(const uint32_t& begin,
155                                     const uint32_t& end,
156                                     std::set<uint16_t>& candidateBins);
157         void CalculateCandidateOffsets(const BaiReferenceSummary& refSummary,
158                                        const uint64_t& minOffset,
159                                        std::set<uint16_t>& candidateBins,
160                                        std::vector<int64_t>& offsets);
161         uint64_t CalculateMinOffset(const BaiReferenceSummary& refSummary, const uint32_t& begin);
162         void GetOffset(const BamRegion& region, int64_t& offset, bool* hasAlignmentsInRegion);
163         uint64_t LookupLinearOffset(const BaiReferenceSummary& refSummary, const int& index);
164
165         // BAI summary (create/load) methods
166         void ReserveForSummary(const int& numReferences);
167         void SaveBinsSummary(const int& refId, const int& numBins);
168         void SaveLinearOffsetsSummary(const int& refId, const int& numLinearOffsets);
169         void SkipBins(const int& numBins);
170         void SkipLinearOffsets(const int& numLinearOffsets);
171         void SummarizeBins(BaiReferenceSummary& refSummary);
172         void SummarizeIndexFile(void);
173         void SummarizeLinearOffsets(BaiReferenceSummary& refSummary);
174         void SummarizeReference(BaiReferenceSummary& refSummary);
175
176         // BAI full index input methods
177         void ReadBinID(uint32_t& binId);
178         void ReadBinIntoBuffer(uint32_t& binId, int32_t& numAlignmentChunks);
179         void ReadIntoBuffer(const unsigned int& bytesRequested);
180         void ReadLinearOffset(uint64_t& linearOffset);
181         void ReadNumAlignmentChunks(int& numAlignmentChunks);
182         void ReadNumBins(int& numBins);
183         void ReadNumLinearOffsets(int& numLinearOffsets);
184         void ReadNumReferences(int& numReferences);
185
186         // BAI full index output methods
187         void MergeAlignmentChunks(BaiAlignmentChunkVector& chunks);
188         void SortLinearOffsets(BaiLinearOffsetVector& linearOffsets);
189         void WriteAlignmentChunk(const BaiAlignmentChunk& chunk);
190         void WriteAlignmentChunks(BaiAlignmentChunkVector& chunks);
191         void WriteBin(const uint32_t& binId, BaiAlignmentChunkVector& chunks);
192         void WriteBins(const int& refId, BaiBinMap& bins);
193         void WriteHeader(void);
194         void WriteLinearOffsets(const int& refId, BaiLinearOffsetVector& linearOffsets);
195         void WriteReferenceEntry(BaiReferenceEntry& refEntry);
196
197     // data members
198     private:
199         bool m_isBigEndian;
200         BaiFileSummary m_indexFileSummary;
201
202         // our input buffer
203         unsigned int m_bufferLength;
204         struct RaiiWrapper {
205             IBamIODevice* Device;
206             char* Buffer;
207             RaiiWrapper(void);
208             ~RaiiWrapper(void);
209         };
210         RaiiWrapper m_resources;
211
212     // static methods
213     private:
214         // checks if the buffer is large enough to accomodate the requested size
215         static void CheckBufferSize(char*& buffer,
216                                     unsigned int& bufferLength,
217                                     const unsigned int& requestedBytes);
218         // checks if the buffer is large enough to accomodate the requested size
219         static void CheckBufferSize(unsigned char*& buffer,
220                                     unsigned int& bufferLength,
221                                     const unsigned int& requestedBytes);
222     // static constants
223     private:
224         static const int MAX_BIN;
225         static const int BAM_LIDX_SHIFT;
226         static const std::string BAI_EXTENSION;
227         static const char* const BAI_MAGIC;
228         static const int SIZEOF_ALIGNMENTCHUNK;
229         static const int SIZEOF_BINCORE;
230         static const int SIZEOF_LINEAROFFSET;
231 };
232
233 } // namespace Internal
234 } // namespace BamTools
235
236 #endif // BAM_STANDARD_INDEX_FORMAT_H