-
Notifications
You must be signed in to change notification settings - Fork 20
/
importing.js
346 lines (303 loc) · 9.51 KB
/
importing.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import zlib from "zlib";
import stream from "stream";
import buffer from "buffer";
const roundToDp = (number, dp) => {
return Math.round(number * Math.pow(10, dp)) / Math.pow(10, dp);
};
export const formatNumber = (num) => {
return num !== null && typeof num === "number" ? num.toLocaleString() : "";
};
export const modules = { zlib, stream, buffer };
function reduceMaxOrMin(array, accessFunction, maxOrMin) {
if (maxOrMin === "max") {
return accessFunction(
array.reduce(function (max, item) {
return accessFunction(item) > accessFunction(max) ? item : max;
})
);
} else if (maxOrMin === "min") {
return accessFunction(
array.reduce(function (min, item) {
return accessFunction(item) < accessFunction(min) ? item : min;
})
);
}
}
export const setUpStream = (the_stream, data, sendStatusMessage) => {
function processLine(line, line_number) {
if ((line_number % 10000 === 0 && line_number > 0) || line_number == 500) {
console.log(`Processed ${formatNumber(line_number)} lines`);
if (data.header.total_nodes) {
const percentage = (line_number / data.header.total_nodes) * 100;
sendStatusMessage({
message: `Loaded ${formatNumber(line_number)} nodes`,
percentage: percentage.toFixed(2),
total: line_number == 500 ? data.header.total_nodes : undefined,
});
} else {
sendStatusMessage({
message: `Loaded ${formatNumber(line_number)} nodes.`,
});
}
}
// console.log("LINE",line_number,line);
const decoded = JSON.parse(line);
if (line_number === 0) {
data.header = decoded;
data.nodes = [];
data.node_to_mut = {};
} else {
data.node_to_mut[decoded.node_id] = decoded.mutations; // this is an int to ints map
data.nodes.push(decoded);
}
}
let cur_line = "";
let line_counter = 0;
the_stream.on("data", function (data) {
cur_line += data.toString();
if (cur_line.includes("\n")) {
const lines = cur_line.split("\n");
cur_line = lines.pop();
lines.forEach((line) => {
processLine(line, line_counter);
line_counter++;
});
}
});
the_stream.on("error", function (err) {
console.log(err);
});
the_stream.on("end", function () {
console.log("end");
});
};
export const processJsonl = async (
jsonl,
sendStatusMessage,
ReadableWebToNodeStream
) => {
console.log(
"Worker processJsonl" //, jsonl
);
const data = jsonl.data;
const status = jsonl.status;
let the_stream;
if (jsonl.filename.includes("gz")) {
// Create a stream
the_stream = zlib.createGunzip();
} else {
// create a fallback stream, and process the output, initially just logging it
the_stream = new stream.PassThrough();
}
let new_data = {};
setUpStream(the_stream, new_data, sendStatusMessage);
if (status === "loaded") {
const dataAsArrayBuffer = data;
// In a Convert the arrayBuffer to a buffer in a series of chunks
let chunkSize = 5 * 1024 * 1024;
for (let i = 0; i < dataAsArrayBuffer.byteLength; i += chunkSize) {
const chunk = dataAsArrayBuffer.slice(i, i + chunkSize);
const chunkAsBuffer = buffer.Buffer.from(chunk);
// Pipe the chunkStream to the stream
the_stream.write(chunkAsBuffer);
}
console.log("Worker processJsonl", data);
the_stream.end();
} else if (status === "url_supplied") {
const url = jsonl.filename;
let response;
// Try fetch
console.log("STARTING FETCH");
try {
response = await fetch(url);
} catch (error) {
console.log("Fetch error", error);
sendStatusMessage({ error: `Fetch error: ${error}` });
return;
}
console.log("ALL FINE", response);
sendStatusMessage({ message: "Loading root genome" });
const readableWebStream = response.body;
const nodeStream = new ReadableWebToNodeStream(readableWebStream);
nodeStream.pipe(the_stream);
} else if (status === "stream_supplied") {
const nodeStream = jsonl.stream;
nodeStream.pipe(the_stream);
} else {
throw new Error("Unknown status: " + status);
}
// Wait for the stream to finish
await new Promise((resolve, reject) => {
the_stream.on("end", resolve);
the_stream.on("error", reject);
});
console.log("done with stream");
const scale_y =
24e2 /
(new_data.nodes.length > 10e3
? new_data.nodes.length
: new_data.nodes.length * 0.6666);
console.log("Scaling");
for (const node of new_data.nodes) {
// numerically round to the nearest 0.1
node.y = roundToDp(node.y * scale_y, 6);
}
console.log("Calculating y positions");
const y_positions = new_data.nodes.map((node) => node.y);
console.log("Calculating coord extremes");
const overallMaxY = reduceMaxOrMin(new_data.nodes, (node) => node.y, "max");
const overallMinY = reduceMaxOrMin(new_data.nodes, (node) => node.y, "min");
const overallMaxX = reduceMaxOrMin(
new_data.nodes,
(node) => node.x_dist,
"max"
);
const overallMinX = reduceMaxOrMin(
new_data.nodes,
(node) => node.x_dist,
"min"
);
const root = new_data.nodes.find((node) => node.parent_id === node.node_id);
const rootMutations = root.mutations;
root.mutations = [];
console.log("Creating output obj");
const overwrite_config = new_data.header.config ? new_data.header.config : {};
overwrite_config.num_tips = root.num_tips;
const output = {
nodes: new_data.nodes,
overallMaxX,
overallMaxY,
overallMinX,
overallMinY,
y_positions,
mutations: new_data.header.mutations
? new_data.header.mutations
: new_data.header.aa_mutations,
node_to_mut: new_data.node_to_mut,
rootMutations: rootMutations,
rootId: root.node_id,
overwrite_config,
};
return output;
};
export const generateConfig = (config, processedUploadedData) => {
config.num_nodes = processedUploadedData.nodes.length;
config.initial_x =
(processedUploadedData.overallMaxX + processedUploadedData.overallMinX) / 2;
config.initial_y =
(processedUploadedData.overallMaxY + processedUploadedData.overallMinY) / 2;
config.initial_zoom = config.initial_zoom ? config.initial_zoom : -2;
config.genes = [
...new Set(processedUploadedData.mutations.map((x) => (x ? x.gene : null))),
]
.filter((x) => x)
.sort();
config.rootMutations = processedUploadedData.rootMutations;
config.rootId = processedUploadedData.rootId;
config.name_accessor = "name";
const to_remove = [
"parent_id",
"node_id",
"x",
"x_dist",
"x_time",
"y",
"mutations",
"name",
"num_tips",
"time_x",
"clades",
"is_tip",
];
const firstNode = processedUploadedData.nodes[0];
config.x_accessors =
firstNode.x_dist !== undefined && firstNode.x_time !== undefined
? ["x_dist", "x_time"]
: firstNode.x_dist
? ["x_dist"]
: ["x_time"];
config.keys_to_display = Object.keys(processedUploadedData.nodes[0]).filter(
(x) => !to_remove.includes(x)
);
/*config.search_types = [
{ name: "name", label: "Name", type: "text_match" },
{ name: "meta_Lineage", label: "PANGO lineage", type: "text_exact" },
{ name: "meta_Country", label: "Country", type: "text_match" },
{ name: "mutation", label: "Mutation", type: "mutation" },
{ name: "revertant", label: "Revertant", type: "revertant" },
{ name: "genbank", label: "Genbank", type: "text_per_line" },
];*/
const prettyName = (x) => {
// if x starts with meta_
if (x.startsWith("meta_")) {
const bit = x.substring(5);
const capitalised_first_letter =
bit.charAt(0).toUpperCase() + bit.slice(1);
return capitalised_first_letter;
}
if (x === "mutation") {
return "Mutation";
}
const capitalised_first_letter = x.charAt(0).toUpperCase() + x.slice(1);
return capitalised_first_letter;
};
const typeFromKey = (x) => {
if (x === "mutation") {
return "mutation";
}
if (x === "genotype") {
return "genotype";
}
if (x === "num_tips") {
return "number";
}
if (x === "genbank") {
return "text_per_line";
}
if (x === "revertant") {
return "revertant";
}
if (x === "meta_Lineage") {
return "text_exact";
}
if (x === "boolean") return "boolean";
return "text_match";
};
const initial_search_types = ["name", ...config.keys_to_display];
if (processedUploadedData.mutations.length > 0) {
initial_search_types.push("mutation");
initial_search_types.push("genotype");
}
if (processedUploadedData.rootMutations.length > 0) {
initial_search_types.push("revertant");
}
initial_search_types.push("num_tips");
if (initial_search_types.length > 1) {
initial_search_types.push("boolean");
}
config.search_types = initial_search_types.map((x) => ({
name: x,
label: prettyName(x),
type: typeFromKey(x),
}));
config.search_types.forEach((x) => {
// if "text" is found in the type
if (x.type.includes("text")) {
x.controls = true;
}
});
const colorByOptions = [...config.keys_to_display];
if (processedUploadedData.mutations.length > 0) {
colorByOptions.push("genotype");
}
colorByOptions.push("None");
if (colorByOptions.length < 2) {
config.colorMapping = { None: [50, 50, 150] };
}
config.colorBy = { colorByOptions };
//check if 'meta_pangolin_lineage' is in options
config.defaultColorByField = colorByOptions.includes("meta_pangolin_lineage")
? "meta_pangolin_lineage"
: colorByOptions[0];
};
export default { processJsonl, generateConfig };