-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbai.ts
286 lines (253 loc) · 7.93 KB
/
bai.ts
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
import QuickLRU from 'quick-lru'
import Chunk from './chunk'
import IndexFile from './indexFile'
import { BaseOpts, findFirstData, optimizeChunks, parsePseudoBin } from './util'
import { VirtualOffset, fromBytes } from './virtualOffset'
const BAI_MAGIC = 21578050 // BAI\1
function roundDown(n: number, multiple: number) {
return n - (n % multiple)
}
function roundUp(n: number, multiple: number) {
return n - (n % multiple) + multiple
}
export interface IndexCovEntry {
start: number
end: number
score: number
}
function reg2bins(beg: number, end: number) {
end -= 1
return [
[0, 0],
[1 + (beg >> 26), 1 + (end >> 26)],
[9 + (beg >> 23), 9 + (end >> 23)],
[73 + (beg >> 20), 73 + (end >> 20)],
[585 + (beg >> 17), 585 + (end >> 17)],
[4681 + (beg >> 14), 4681 + (end >> 14)],
] as const
}
export default class BAI extends IndexFile {
public setupP?: ReturnType<BAI['_parse']>
async lineCount(refId: number, opts?: BaseOpts) {
const indexData = await this.parse(opts)
return indexData.indices(refId)?.stats?.lineCount || 0
}
async _parse(_opts?: BaseOpts) {
const bytes = await this.filehandle.readFile()
const dataView = new DataView(bytes.buffer)
// check BAI magic numbers
if (dataView.getUint32(0, true) !== BAI_MAGIC) {
throw new Error('Not a BAI file')
}
const refCount = dataView.getInt32(4, true)
const depth = 5
const binLimit = ((1 << ((depth + 1) * 3)) - 1) / 7
// read the indexes for each reference sequence
let curr = 8
let firstDataLine: VirtualOffset | undefined
const offsets = [] as number[]
for (let i = 0; i < refCount; i++) {
offsets.push(curr)
const binCount = dataView.getInt32(curr, true)
curr += 4
for (let j = 0; j < binCount; j += 1) {
const bin = dataView.getUint32(curr, true)
curr += 4
if (bin === binLimit + 1) {
curr += 4
curr += 32
} else if (bin > binLimit + 1) {
throw new Error('bai index contains too many bins, please use CSI')
} else {
const chunkCount = dataView.getInt32(curr, true)
curr += 4
for (let k = 0; k < chunkCount; k++) {
curr += 8
curr += 8
}
}
}
const linearCount = dataView.getInt32(curr, true)
curr += 4
// as we're going through the linear index, figure out the smallest
// virtual offset in the indexes, which tells us where the BAM header
// ends
const linearIndex = new Array<VirtualOffset>(linearCount)
for (let j = 0; j < linearCount; j++) {
const offset = fromBytes(bytes, curr)
curr += 8
firstDataLine = findFirstData(firstDataLine, offset)
linearIndex[j] = offset
}
}
const indicesCache = new QuickLRU<number, ReturnType<typeof getIndices>>({
maxSize: 5,
})
function getIndices(refId: number) {
let curr = offsets[refId]
if (curr === undefined) {
return undefined
}
const binCount = dataView.getInt32(curr, true)
let stats
curr += 4
const binIndex: Record<number, Chunk[]> = {}
for (let j = 0; j < binCount; j += 1) {
const bin = dataView.getUint32(curr, true)
curr += 4
if (bin === binLimit + 1) {
curr += 4
stats = parsePseudoBin(bytes, curr + 16)
curr += 32
} else if (bin > binLimit + 1) {
throw new Error('bai index contains too many bins, please use CSI')
} else {
const chunkCount = dataView.getInt32(curr, true)
curr += 4
const chunks = new Array<Chunk>(chunkCount)
for (let k = 0; k < chunkCount; k++) {
const u = fromBytes(bytes, curr)
curr += 8
const v = fromBytes(bytes, curr)
curr += 8
firstDataLine = findFirstData(firstDataLine, u)
chunks[k] = new Chunk(u, v, bin)
}
binIndex[bin] = chunks
}
}
const linearCount = dataView.getInt32(curr, true)
curr += 4
// as we're going through the linear index, figure out the smallest
// virtual offset in the indexes, which tells us where the BAM header
// ends
const linearIndex = new Array<VirtualOffset>(linearCount)
for (let j = 0; j < linearCount; j++) {
const offset = fromBytes(bytes, curr)
curr += 8
firstDataLine = findFirstData(firstDataLine, offset)
linearIndex[j] = offset
}
return {
binIndex,
linearIndex,
stats,
}
}
return {
bai: true,
firstDataLine,
maxBlockSize: 1 << 16,
indices: (refId: number) => {
if (!indicesCache.has(refId)) {
const result = getIndices(refId)
if (result) {
indicesCache.set(refId, result)
}
return result
}
return indicesCache.get(refId)
},
refCount,
}
}
async indexCov(
seqId: number,
start?: number,
end?: number,
opts?: BaseOpts,
): Promise<IndexCovEntry[]> {
const v = 16384
const range = start !== undefined
const indexData = await this.parse(opts)
const seqIdx = indexData.indices(seqId)
if (!seqIdx) {
return []
}
const { linearIndex = [], stats } = seqIdx
if (linearIndex.length === 0) {
return []
}
const e = end === undefined ? (linearIndex.length - 1) * v : roundUp(end, v)
const s = start === undefined ? 0 : roundDown(start, v)
const depths = range
? new Array((e - s) / v)
: new Array(linearIndex.length - 1)
const totalSize = linearIndex[linearIndex.length - 1]!.blockPosition
if (e > (linearIndex.length - 1) * v) {
throw new Error('query outside of range of linear index')
}
let currentPos = linearIndex[s / v]!.blockPosition
for (let i = s / v, j = 0; i < e / v; i++, j++) {
depths[j] = {
score: linearIndex[i + 1]!.blockPosition - currentPos,
start: i * v,
end: i * v + v,
}
currentPos = linearIndex[i + 1]!.blockPosition
}
return depths.map(d => ({
...d,
score: (d.score * (stats?.lineCount || 0)) / totalSize,
}))
}
async blocksForRange(
refId: number,
min: number,
max: number,
opts: BaseOpts = {},
) {
if (min < 0) {
min = 0
}
const indexData = await this.parse(opts)
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!indexData) {
return []
}
const ba = indexData.indices(refId)
if (!ba) {
return []
}
// List of bin #s that overlap min, max
const overlappingBins = reg2bins(min, max)
const chunks: Chunk[] = []
// Find chunks in overlapping bins. Leaf bins (< 4681) are not pruned
for (const [start, end] of overlappingBins) {
for (let bin = start; bin <= end; bin++) {
if (ba.binIndex[bin]) {
const binChunks = ba.binIndex[bin]!
for (const binChunk of binChunks) {
chunks.push(new Chunk(binChunk.minv, binChunk.maxv, bin))
}
}
}
}
// Use the linear index to find minimum file position of chunks that could
// contain alignments in the region
const nintv = ba.linearIndex.length
let lowest: VirtualOffset | undefined
const minLin = Math.min(min >> 14, nintv - 1)
const maxLin = Math.min(max >> 14, nintv - 1)
for (let i = minLin; i <= maxLin; ++i) {
const vp = ba.linearIndex[i]
if (vp && (!lowest || vp.compareTo(lowest) < 0)) {
lowest = vp
}
}
return optimizeChunks(chunks, lowest)
}
async parse(opts: BaseOpts = {}) {
if (!this.setupP) {
this.setupP = this._parse(opts).catch((e: unknown) => {
this.setupP = undefined
throw e
})
}
return this.setupP
}
async hasRefSeq(seqId: number, opts: BaseOpts = {}) {
const header = await this.parse(opts)
return !!header.indices(seqId)?.binIndex
}
}