-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
504 lines (444 loc) · 16.1 KB
/
Copy pathindex.js
File metadata and controls
504 lines (444 loc) · 16.1 KB
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
/**
* Requires a BioMart Export file with the columns given by the values in the HEADER constant
*
* @module importer/ensembl
*/
const { loadDelimToJson, requestWithRetry, convertRowFields } = require('../util');
const {
rid, generateCacheKey,
} = require('../graphkb');
const { logger } = require('../logging');
const _hgnc = require('../hgnc');
const _entrez = require('../entrez/gene');
const { ensembl: SOURCE_DEFN } = require('../sources');
const BASE_URL = 'http://rest.ensembl.org';
const CACHE = {};
/**
* Create and link a non-versioned record of the current versioned record
*/
const generalize = async (conn, record) => {
const general = await conn.addRecord({
content: {
biotype: record.biotype,
name: record.name,
source: record.source,
sourceId: record.sourceId,
sourceIdVersion: null,
},
existsOk: true,
target: 'Feature',
});
await conn.addRecord({
content: { in: rid(record), out: rid(general), source: rid(record.source) },
existsOk: true,
target: 'Generalizationof',
});
return general;
};
/**
* Fetch the parent feature: gene for transcript, or transcript for protein
* and then link via element of, return the parent feature
*/
const linkFeatureToParent = async (conn, transcript, parentBiotype = 'gene') => {
const { Parent: geneId } = await requestWithRetry({
json: true,
method: 'GET',
uri: `${BASE_URL}/lookup/id/${transcript.sourceId}`,
});
if (!geneId) {
return null;
}
const gene = await conn.addRecord({
content: {
biotype: parentBiotype,
source: rid(transcript.source),
sourceId: geneId,
sourceIdVersion: null,
},
existsOk: true,
target: 'Feature',
});
await conn.addRecord({
content: { in: rid(gene), out: rid(transcript), source: rid(transcript.source) },
existsOk: true,
fetchExisting: false,
target: 'ElementOf',
});
return gene;
};
/**
* Fetch and link the ensembl gene to the entrez gene
*/
const linkGeneToEntrez = async (conn, record) => {
const xrefs = await requestWithRetry({
method: 'GET',
uri: `${BASE_URL}/xrefs/id/${record.sourceId}`,
});
for (const xref of xrefs) {
if (xref.dbname === 'EntrezGene') {
const [gene] = await _entrez.fetchAndLoadByIds(conn, [xref.primary_id]);
// link to the current record
await conn.addRecord({
content: { in: rid(gene), out: rid(record), source: rid(record.source) },
existsOk: true,
target: 'CrossReferenceOf',
});
return gene;
}
}
return null;
};
const fetchAndLoadById = async (conn, { sourceId, sourceIdVersion, biotype }) => {
if (sourceId.includes('.') && !sourceIdVersion) {
[sourceId, sourceIdVersion] = sourceId.split('.');
}
const cacheKey = generateCacheKey({ sourceId, sourceIdVersion });
if (CACHE[cacheKey]) {
return CACHE[cacheKey];
}
// get the source record from the cache
if (!CACHE._source) {
CACHE._source = rid(await conn.addSource(SOURCE_DEFN));
}
// try to fetch from graphkb first
try {
const result = await conn.getUniqueRecordBy({
filters: [
{ sourceId },
{ sourceIdVersion },
{ biotype },
{ source: CACHE._source },
],
target: 'Feature',
});
CACHE[cacheKey] = result;
return CACHE[cacheKey];
} catch (err) {}
const current = await conn.addRecord({
content: {
biotype,
source: CACHE._source,
sourceId,
sourceIdVersion,
},
target: 'Feature',
});
let generalCurrent;
if (sourceIdVersion != null) {
generalCurrent = await generalize(conn, current);
} else {
generalCurrent = current;
}
if (biotype === 'gene') {
await linkGeneToEntrez(conn, current);
return current;
} if (biotype === 'transcript') {
// link to the gene
await linkFeatureToParent(conn, generalCurrent, 'gene');
} else if (biotype === 'protein') {
// link to the transcript
const transcript = await linkFeatureToParent(conn, generalCurrent, 'transcript');
// link to the gene
await linkFeatureToParent(conn, transcript, 'gene');
} else {
throw Error(`unsupported biotype: ${biotype}`);
}
CACHE[cacheKey] = current;
return current;
};
/**
* Given a TAB delmited biomart export of Ensembl data, upload the features to GraphKB
*
* @param {object} opt options
* @param {string} opt.filename the path to the tab delimited export file
* @param {ApiConnection} opt.conn the api connection object
*/
const uploadFile = async (opt) => {
const HEADER = {
geneIdVersion: 'Gene stable ID version',
hgncId: 'HGNC ID',
proteinIdVersion: 'Protein stable ID version',
transcriptIdVersion: 'Transcript stable ID version',
};
const { filename, conn } = opt;
const contentList = await loadDelimToJson(filename);
const rows = contentList.map(row => convertRowFields(HEADER, row));
// process versions
for (const row of rows) {
[row.geneId, row.geneIdVersion] = row.geneIdVersion.toLowerCase().split('.');
[row.transcriptId, row.transcriptIdVersion] = row.transcriptIdVersion.toLowerCase().split('.');
[row.proteinId, row.proteinIdVersion] = row.proteinIdVersion.toLowerCase().split('.');
}
const source = await conn.addSource(SOURCE_DEFN);
const visited = {}; // cache genes to speed up adding records
const hgncMissingRecords = new Set();
logger.info('pre-load the entrez cache to avoid unecessary requests');
await _entrez.preLoadCache(conn);
// skip any genes that have already been loaded before we start
logger.info('retreiving the list of previously loaded genes');
const preLoadedGene = new Set();
const genesList = await conn.getRecords({
filters: {
AND: [
{ source: rid(source) }, { biotype: 'gene' }, { dependency: null },
],
},
neighbors: 0,
target: 'Feature',
});
const preLoadedTranscript = new Set();
const transcriptList = await conn.getRecords({
filters: {
AND: [
{ source: rid(source) }, { biotype: 'transcript' }, { dependency: null },
],
},
neighbors: 0,
target: 'Feature',
});
const preLoadedProtein = new Set();
const proteinList = await conn.getRecords({
filters: {
AND: [
{ source: rid(source) }, { biotype: 'protein' }, { dependency: null },
],
},
neighbors: 0,
target: 'Feature',
});
const counts = { error: 0, skip: 0, success: 0 };
for (const record of genesList) {
const gene = generateCacheKey(record);
preLoadedGene.add(gene);
logger.info(`Gene ${gene} has already been loaded`);
}
for (const record of transcriptList) {
const transcript = generateCacheKey(record);
preLoadedTranscript.add(transcript);
logger.info(`Transcript ${transcript} has already been loaded`);
}
for (const record of proteinList) {
const protein = generateCacheKey(record);
preLoadedProtein.add(protein);
logger.info(`Protein ${protein} has already been loaded`);
}
logger.info(`processing ${rows.length} records`);
for (let index = 0; index < rows.length; index++) {
const record = rows[index];
const { geneId, geneIdVersion } = record;
const { transcriptId, transcriptIdVersion } = record;
const { proteinId, proteinIdVersion } = record;
const geneVersion = generateCacheKey({
sourceId: geneId,
sourceIdVersion: geneIdVersion,
});
const transcriptVersion = generateCacheKey({
sourceId: transcriptId,
sourceIdVersion: transcriptIdVersion,
});
const proteinVersion = generateCacheKey({
sourceId: proteinId,
sourceIdVersion: proteinIdVersion,
});
logger.info(`processing ${geneId}.${geneIdVersion || ''} (${index} / ${rows.length})`);
let newGene = false,
skip = 0;
if (preLoadedGene.has(geneVersion)) {
visited[geneVersion] = genesList.find((gene) => `${gene.sourceId}-${gene.sourceIdVersion}` === geneVersion);
visited[geneId] = genesList.find((gene) => `${gene.sourceId}` === geneId && gene.sourceIdVersion === null);
skip++;
} else {
if (visited[geneVersion] === undefined) {
visited[geneVersion] = await conn.addRecord({
content: {
biotype: 'gene',
source: rid(source),
sourceId: geneId,
sourceIdVersion: geneIdVersion,
},
existsOk: true,
target: 'Feature',
});
}
if (visited[geneId] === undefined) {
newGene = true;
visited[geneId] = await conn.addRecord({
content: {
biotype: 'gene',
source: rid(source),
sourceId: geneId,
sourceIdVersion: null,
},
existsOk: true,
target: 'Feature',
});
}
await conn.addRecord({
content: {
in: rid(visited[geneVersion]), out: rid(visited[geneId]), source: rid(source),
},
existsOk: true,
fetchExisting: false,
target: 'generalizationof',
});
}
const gene = visited[geneId];
const versionedGene = visited[geneVersion];
// transcript
if (preLoadedTranscript.has(transcriptVersion)) {
visited[transcriptVersion] = transcriptList.find((transcript) => `${transcript.sourceId}-${transcript.sourceIdVersion}` === transcriptVersion);
visited[transcriptId] = transcriptList.find((transcript) => `${transcript.sourceId}` === transcriptId && transcript.sourceIdVersion === null);
skip++;
} else {
if (visited[transcriptVersion] === undefined) {
visited[transcriptVersion] = await conn.addRecord({
content: {
biotype: 'transcript',
source: rid(source),
sourceId: record.transcriptId,
sourceIdVersion: record.transcriptIdVersion,
},
existsOk: true,
target: 'Feature',
});
}
if (visited[transcriptId] === undefined) {
visited[transcriptId] = await conn.addRecord({
content: {
biotype: 'transcript',
source: rid(source),
sourceId: record.transcriptId,
sourceIdVersion: null,
},
existsOk: true,
target: 'Feature',
});
// transcript -> elementof -> gene
await conn.addRecord({
content: {
in: rid(gene), out: rid(visited[transcriptId]), source: rid(source),
},
existsOk: true,
fetchExisting: false,
target: 'elementof',
});
}
await conn.addRecord({
content: {
in: rid(visited[transcriptVersion]),
out: rid(visited[transcriptId]),
source: rid(source),
},
existsOk: true,
fetchExisting: false,
target: 'generalizationof',
});
}
const versionedTranscript = visited[transcriptVersion];
const transcript = visited[transcriptId];
// versioned: transcript -> elementof -> gene
await conn.addRecord({
content: {
in: rid(versionedGene),
out: rid(versionedTranscript),
source: rid(source),
},
existsOk: true,
fetchExisting: false,
target: 'elementof',
});
// protein
if (preLoadedProtein.has(proteinVersion)) {
visited[proteinVersion] = proteinList.find((protein) => `${protein.sourceId}-${protein.sourceIdVersion}` === proteinVersion);
visited[proteinId] = proteinList.find((protein) => `${protein.sourceId}` === proteinId && protein.sourceIdVersion === null);
skip++;
} else {
if (visited[proteinVersion] === undefined) {
visited[proteinVersion] = await conn.addRecord({
content: {
biotype: 'protein',
source: rid(source),
sourceId: record.proteinId,
sourceIdVersion: record.proteinIdVersion,
},
existsOk: true,
target: 'Feature',
});
}
if (visited[proteinId] === undefined) {
visited[proteinId] = await conn.addRecord({
content: {
biotype: 'protein',
source: rid(source),
sourceId: record.proteinId,
sourceIdVersion: null,
},
existsOk: true,
target: 'Feature',
});
// protein -> elementof -> transcript
await conn.addRecord({
content: {
in: rid(transcript), out: rid(visited[proteinId]), source: rid(source),
},
existsOk: true,
fetchExisting: false,
target: 'elementof',
});
}
await conn.addRecord({
content: {
in: rid(visited[proteinVersion]),
out: rid(visited[proteinId]),
source: rid(source),
},
existsOk: true,
fetchExisting: false,
target: 'generalizationof',
});
}
// versioned: protein -> elementof -> transcript
await conn.addRecord({
content: {
in: rid(versionedTranscript),
out: rid(visited[proteinVersion]),
source: rid(source),
},
existsOk: true,
fetchExisting: false,
target: 'elementof',
});
// gene -> crossreferenceof -> hgnc
if (record.hgncId && newGene) {
skip--;
try {
const hgnc = await _hgnc.fetchAndLoadBySymbol({ conn, paramType: 'hgnc_id', symbol: record.hgncId });
await conn.addRecord({
content: {
in: rid(hgnc), out: rid(gene), source: rid(source),
},
existsOk: true,
fetchExisting: false,
target: 'crossreferenceof',
});
} catch (err) {
hgncMissingRecords.add(record.hgncId);
logger.log('error', `failed cross-linking from ${gene.sourceid} to ${record.hgncId}`);
}
}
if (skip === 3) {
counts.skip++;
continue;
}
counts.success++;
}
if (hgncMissingRecords.size) {
logger.warn(`Unable to retrieve ${hgncMissingRecords.size} hgnc records for linking`);
}
logger.info(JSON.stringify(counts));
};
module.exports = {
SOURCE_DEFN,
fetchAndLoadById,
uploadFile,
};