forked from igvteam/igv.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.js
325 lines (260 loc) · 9.19 KB
/
search.js
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
import {igvxhr, StringUtils} from "../node_modules/igv-utils/src/index.js"
const DEFAULT_SEARCH_CONFIG = {
timeout: 5000,
type: "plain", // Legacy plain text support -- deprecated
url: 'https://igv.org/genomes/locus.php?genome=$GENOME$&name=$FEATURE$',
coords: 0,
chromosomeField: "chromosome",
startField: "start",
endField: "end",
geneField: "gene",
snpField: "snp"
}
/**
* Return an object representing the locus of the given string. Object is of the form
* {
* chr,
* start,
* end,
* locusSearchString,
* gene,
* snp
* }
* @param browser
* @param string
* @returns {Promise<*>}
*/
async function search(browser, string) {
if (undefined === string || '' === string.trim()) {
return
}
if (string && string.trim().toLowerCase() === "all" || string === "*") {
string = "all"
}
const loci = string.split(' ')
let searchConfig = browser.searchConfig || DEFAULT_SEARCH_CONFIG
let list = []
const searchLocus = async (locus) => {
let locusObject = parseLocusString(browser, locus)
if (!locusObject) {
const feature = browser.genome.featureDB[locus.toUpperCase()]
if (feature) {
locusObject = {
chr: feature.chr,
start: feature.start,
end: feature.end,
gene: feature.name,
locusSearchString: string
}
}
}
if (!locusObject && (browser.config && false !== browser.config.search)) {
try {
locusObject = await searchWebService(browser, locus, searchConfig)
} catch (error) {
console.error(error)
throw Error("Search service currently unavailable.")
}
}
return locusObject
}
for (let locus of loci) {
const locusObject = await searchLocus(locus)
if (locusObject) {
locusObject.locusSearchString = locus
list.push(locusObject)
}
}
// If nothing is found, consider possibility that loci name itself has spaces
if (list.length === 0) {
const locusObject = await searchLocus(string)
if (locusObject) {
locusObject.locusSearchString = string
list.push(locusObject)
}
}
return 0 === list.length ? undefined : list
}
function parseLocusString(browser, locus) {
// Check for tab delimited locus string
const tabTokens = locus.split('\t')
if (tabTokens.length >= 3) {
// Possibly a tab-delimited locus
try {
const chr = browser.genome.getChromosomeName(tabTokens[0])
const start = parseInt(tabTokens[1].replace(/,/g, ''), 10) - 1
const end = parseInt(tabTokens[2].replace(/,/g, ''), 10)
if (!isNaN(start) && !isNaN(end)) {
return {chr, start, end}
}
} catch (e) {
// Not a tab delimited locus, apparently, but not really an error as that was a guess
}
}
const a = locus.split(':')
const chr = a[0]
if ('all' === chr && browser.genome.getChromosome(chr)) {
return {chr, start: 0, end: browser.genome.getChromosome(chr).bpLength}
} else if (undefined === browser.genome.getChromosome(chr)) {
return undefined
} else {
const queryChr = browser.genome.getChromosomeName(chr)
const extent = {
chr: queryChr,
start: 0,
end: browser.genome.getChromosome(chr).bpLength
}
if (a.length > 1) {
let b = a[1].split('-')
if (b.length > 2) {
// Allow for negative coordinates, which is possible if showing alignment soft clips
if (a[1].startsWith('-')) {
const i = a[1].indexOf('-', 1)
if (i > 0) {
const t1 = a[1].substring(0, i)
const t2 = a[1].substring(i + 1)
b = [t1, t2]
}
} else {
return undefined
}
}
let numeric
numeric = b[0].replace(/,/g, '')
if (isNaN(numeric)) {
return undefined
}
extent.start = parseInt(numeric, 10) - 1
extent.end = extent.start + 1
if (1 === b.length) {
// Don't clamp coordinates if single coordinate is supplied.
extent.start -= 20
extent.end += 20
}
if (2 === b.length) {
numeric = b[1].replace(/,/g, '')
if (isNaN(numeric)) {
return undefined
} else {
extent.end = parseInt(numeric, 10)
}
// Allow negative coordinates only if browser is softclipped, i.e. there is at least alignment track with softclipping on
if (extent.start < 0 && !browser.isSoftclipped()) {
const delta = -extent.start
extent.start += delta
extent.end += delta
}
}
}
return extent
}
}
async function searchWebService(browser, locus, searchConfig) {
let path = searchConfig.url.replace("$FEATURE$", locus.toUpperCase())
if (path.indexOf("$GENOME$") > -1) {
path = path.replace("$GENOME$", (browser.genome.id ? browser.genome.id : "hg19"))
}
const options = searchConfig.timeout ? {timeout: searchConfig.timeout} : undefined
const result = await igvxhr.loadString(path, options)
const locusObject = processSearchResult(browser, result, searchConfig)
if (locusObject) {
locusObject.locusSearchString = locus
}
return locusObject
}
function processSearchResult(browser, result, searchConfig) {
let results
if ('plain' === searchConfig.type) {
results = parseSearchResults(browser, result)
} else {
results = JSON.parse(result)
}
if (searchConfig.resultsField) {
results = results[searchConfig.resultsField]
}
if (!results || 0 === results.length) {
return undefined
} else {
const chromosomeField = searchConfig.chromosomeField || "chromosome"
const startField = searchConfig.startField || "start"
const endField = searchConfig.endField || "end"
const coords = searchConfig.coords || 1
let result
if (Array.isArray(results)) {
// Ignoring all but first result for now
// TODO -- present all and let user select if results.length > 1
result = results[0]
} else {
// When processing search results from Ensembl REST API
// Example: https://rest.ensembl.org/lookup/symbol/macaca_fascicularis/BRCA2?content-type=application/json
result = results
}
if (!(result.hasOwnProperty(chromosomeField) && (result.hasOwnProperty(startField)))) {
console.error("Search service results must include chromosome and start fields: " + result)
}
const chrResult = result[chromosomeField]
const chromosome = browser.genome.getChromosome(chrResult)
if (!chromosome) {
return undefined
}
const chr = chromosome.name
let start = result[startField] - coords
let end = result[endField]
if (undefined === end) {
end = start + 1
}
const locusObject = {chr, start, end}
// Some GTEX hacks
const type = result.type ? result.type : "gene"
if (searchConfig.geneField && type === "gene") {
locusObject.gene = result[searchConfig.geneField]
}
if (searchConfig.snpField && type === "snp") {
locusObject.snp = result[searchConfig.snpField]
}
return locusObject
}
}
/**
* Parse the igv line-oriented (non json) search results.
* Example
* EGFR chr7:55,086,724-55,275,031 refseq
*
*/
function parseSearchResults(browser, data) {
const linesTrimmed = []
const results = []
const lines = StringUtils.splitLines(data)
lines.forEach(function (item) {
if ("" === item) {
// do nothing
} else {
linesTrimmed.push(item)
}
})
linesTrimmed.forEach(function (line) {
var tokens = line.split("\t"),
source,
locusTokens,
rangeTokens,
obj
if (tokens.length >= 3) {
locusTokens = tokens[1].split(":")
rangeTokens = locusTokens[1].split("-")
source = tokens[2].trim()
obj =
{
gene: tokens[0],
chromosome: browser.genome.getChromosomeName(locusTokens[0].trim()),
start: parseInt(rangeTokens[0].replace(/,/g, '')),
end: parseInt(rangeTokens[1].replace(/,/g, '')),
type: ("gtex" === source ? "snp" : "gene")
}
results.push(obj)
}
})
return results
}
// Export some functions for unit testing
export {parseLocusString, searchWebService}
export default search