/
BamAdapter.ts
251 lines (222 loc) · 7.32 KB
/
BamAdapter.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
import { BamFile } from '@gmod/bam'
import {
BaseFeatureDataAdapter,
BaseOptions,
} from '@jbrowse/core/data_adapters/BaseAdapter'
import { Region } from '@jbrowse/core/util/types'
import { bytesForRegions, updateStatus, Feature } from '@jbrowse/core/util'
import { openLocation } from '@jbrowse/core/util/io'
import { ObservableCreate } from '@jbrowse/core/util/rxjs'
import { toArray } from 'rxjs/operators'
import { firstValueFrom } from 'rxjs'
// locals
import BamSlightlyLazyFeature from './BamSlightlyLazyFeature'
interface Header {
idToName: string[]
nameToId: Record<string, number>
}
export default class BamAdapter extends BaseFeatureDataAdapter {
private samHeader?: Header
private setupP?: Promise<Header>
private configureP?: Promise<{
bam: BamFile
sequenceAdapter?: BaseFeatureDataAdapter
}>
// derived classes may not use the same configuration so a custom
// configure method allows derived classes to override this behavior
protected async configurePre() {
const bamLocation = this.getConf('bamLocation')
const location = this.getConf(['index', 'location'])
const indexType = this.getConf(['index', 'indexType'])
const pm = this.pluginManager
const csi = indexType === 'CSI'
const bam = new BamFile({
bamFilehandle: openLocation(bamLocation, pm),
csiFilehandle: csi ? openLocation(location, pm) : undefined,
baiFilehandle: !csi ? openLocation(location, pm) : undefined,
// chunkSizeLimit and fetchSizeLimit are more troublesome than
// helpful, and have given overly large values on the ultra long
// nanopore reads even with 500MB limits, so disabled with infinity
yieldThreadTime: Infinity,
})
const adapterConfig = this.getConf('sequenceAdapter')
if (adapterConfig && this.getSubAdapter) {
const { dataAdapter } = await this.getSubAdapter(adapterConfig)
return {
bam,
sequenceAdapter: dataAdapter as BaseFeatureDataAdapter,
}
} else {
return { bam }
}
}
protected async configure() {
if (!this.configureP) {
this.configureP = this.configurePre().catch(e => {
this.configureP = undefined
throw e
})
}
return this.configureP
}
async getHeader(opts?: BaseOptions) {
const { bam } = await this.configure()
return bam.getHeaderText(opts)
}
private async setupPre(opts?: BaseOptions) {
const { statusCallback = () => {} } = opts || {}
const { bam } = await this.configure()
this.samHeader = await updateStatus(
'Downloading index',
statusCallback,
async () => {
const samHeader = await bam.getHeader(opts)
// use the @SQ lines in the header to figure out the
// mapping between ref ref ID numbers and names
const idToName: string[] = []
const nameToId: Record<string, number> = {}
samHeader
?.filter(l => l.tag === 'SQ')
.forEach((sqLine, refId) => {
sqLine.data.forEach(item => {
if (item.tag === 'SN') {
// this is the ref name
const refName = item.value
nameToId[refName] = refId
idToName[refId] = refName
}
})
})
return { idToName, nameToId }
},
)
return this.samHeader
}
async setup(opts?: BaseOptions) {
if (!this.setupP) {
this.setupP = this.setupPre(opts).catch(e => {
this.setupP = undefined
throw e
})
}
return this.setupP
}
async getRefNames(opts?: BaseOptions) {
const { idToName } = await this.setup(opts)
return idToName
}
private async seqFetch(refName: string, start: number, end: number) {
const { sequenceAdapter } = await this.configure()
const refSeqStore = sequenceAdapter
if (!refSeqStore) {
return undefined
}
if (!refName) {
return undefined
}
const features = refSeqStore.getFeatures({
refName,
start,
end,
assemblyName: '',
})
const seqChunks = await firstValueFrom(features.pipe(toArray()))
let sequence = ''
seqChunks
.sort((a, b) => a.get('start') - b.get('start'))
.forEach(chunk => {
const chunkStart = chunk.get('start')
const chunkEnd = chunk.get('end')
const trimStart = Math.max(start - chunkStart, 0)
const trimEnd = Math.min(end - chunkStart, chunkEnd - chunkStart)
const trimLength = trimEnd - trimStart
const chunkSeq = chunk.get('seq') || chunk.get('residues')
sequence += chunkSeq.slice(trimStart, trimStart + trimLength)
})
if (sequence.length !== end - start) {
throw new Error(
`sequence fetch failed: fetching ${refName}:${(
start - 1
).toLocaleString()}-${end.toLocaleString()} returned ${sequence.length.toLocaleString()} bases, but should have returned ${(
end - start
).toLocaleString()}`,
)
}
return sequence
}
getFeatures(
region: Region & { originalRefName?: string },
opts?: BaseOptions & {
filterBy: {
flagInclude: number
flagExclude: number
tagFilter: { tag: string; value: unknown }
readName: string
}
},
) {
const { refName, start, end, originalRefName } = region
const { signal, filterBy, statusCallback = () => {} } = opts || {}
return ObservableCreate<Feature>(async observer => {
const { bam } = await this.configure()
await this.setup(opts)
const records = await updateStatus(
'Downloading alignments',
statusCallback,
() => bam.getRecordsForRange(refName, start, end, opts),
)
await updateStatus('Processing alignments', statusCallback, async () => {
const {
flagInclude = 0,
flagExclude = 0,
tagFilter,
readName,
} = filterBy || {}
for (const record of records) {
let ref: string | undefined
if (!record.get('MD')) {
ref = await this.seqFetch(
originalRefName || refName,
record.get('start'),
record.get('end'),
)
}
const flags = record.flags
if ((flags & flagInclude) !== flagInclude && !(flags & flagExclude)) {
continue
}
if (tagFilter) {
const v = record.get(tagFilter.tag)
if (!(v === '*' ? v !== undefined : `${v}` === tagFilter.value)) {
continue
}
}
if (readName && record.get('name') !== readName) {
continue
}
observer.next(new BamSlightlyLazyFeature(record, this, ref))
}
observer.complete()
})
}, signal)
}
async getMultiRegionFeatureDensityStats(
regions: Region[],
opts?: BaseOptions,
) {
const { bam } = await this.configure()
// this is a method to avoid calling on htsget adapters
if (bam.index) {
const bytes = await bytesForRegions(regions, bam)
const fetchSizeLimit = this.getConf('fetchSizeLimit')
return { bytes, fetchSizeLimit }
} else {
return super.getMultiRegionFeatureDensityStats(regions, opts)
}
}
freeResources(/* { region } */): void {}
// depends on setup being called before the BAM constructor
refIdToName(refId: number) {
return this.samHeader?.idToName[refId]
}
}