-
Notifications
You must be signed in to change notification settings - Fork 1
/
sbu.html
488 lines (441 loc) · 20.6 KB
/
sbu.html
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
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>MOFid/MOFkey generator</title>
<link href="mofid.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="favicon.ico">
<link rel="icon" href="favicon.ico">
<style>
#headerlogo {
height: 2em;
margin-right: 2em;
}
#headerlogo, h1, #loading {
display: inline-block;
}
body {
display: grid; /* https://css-tricks.com/snippets/css/complete-guide-grid/ */
grid-template-columns: repeat(2, minmax(400px, auto));
/*grid-auto-rows: minmax(100px, auto);*/
grid-column-gap: 2em;
grid-row-gap: 1em;
grid-template-areas:
"head head"
/*"load load"*/
"upload viz"
"algorithm viz"
"mofid mofid";
}
/* Replace explicit grid columns by the somewhat-visual grid-template-areas approach */
/*header, .loading { grid-column: 1 / span 2; }*/
header { grid-area: head; }
/*#loading { grid-area: load; }*/
#inputblock { grid-area: upload; }
#resultsdownload { grid-area: algorithm; }
#viewportwrapper { grid-area: viz; }
#identifiers { grid-area: mofid; }
</style>
</head>
<body>
<script type="text/javascript" src="ngl.js"></script>
<!-- FIXME: the webGavrog scripts take too long to load, so they're blocking to the page load -->
<script type="text/javascript" src="webGavrog/runtime.js"></script>
<script type="text/javascript" src="webGavrog/vendors.js"></script>
<script type="text/javascript" src="webGavrog/main.js"></script>
<script type="text/javascript">
var stage;
var lsdir = function(path) {
return FS.readdir(path).filter(function(e) {
return !['..', '.'].includes(e); // filter out current and parent dirs
}).sort();
};
// Adapted from examples at http://nglviewer.org/ngl/api/manual/usage/embedding.html
// and https://codepen.io/pen?template=JNLMXb and http://nglviewer.org/ngldev/api/manual/snippets.html
document.addEventListener("DOMContentLoaded", function () {
stage = new NGL.Stage("cifviewport");
stage.setParameters( {backgroundColor: "white"} );
});
var runMOFidCode = function(cifdata) {
C_obcode = Module.cwrap(
'analyzeMOFc', 'null', ['string', 'number', 'number']
);
if(!FS.analyzePath('/Output').exists) {
FS.mkdir('/Output'); // See also docs on filesystem API: https://kripken.github.io/emscripten-site/docs/api_reference/Filesystem-API.html
// Ideally, the C_obcode executable would automatically make all of the directories,
// but it's broken at least in an old version of Emscripten.
FS.mkdir('/Output/MetalOxo');
FS.mkdir('/Output/SingleNode');
FS.mkdir('/Output/AllNode');
FS.mkdir('/Output/StandardIsolated');
}
var buflen = 65536;
var ptr = Module._malloc(buflen);
var buffer= new Uint8Array(Module.HEAPU8.buffer, ptr, buflen); // Get a bytes view on the newly allocated buffer.
C_obcode(cifdata, ptr, buflen);
var ans = Module.UTF8ToString(ptr);
Module._free(ptr);
return ans;
};
var analyzeMOF = function(input_cif_str, cif_name) {
// Get relevant MOFid/MOFkey information from an input string of CIF-formatted coordinates
var raw_mofid_output = runMOFidCode(input_cif_str);
var single_node_topology = getTopology("/Output/SingleNode/topology.cgd");
var all_node_topology = getTopology("/Output/AllNode/topology.cgd");
// Extract the MOFid, per run_mofid.py:cif2mofid
const fragment_info = _extractFragments(raw_mofid_output);
let mofid_topology = '';
if (fragment_info.cat == null) {
mofid_topology = 'NA'
} else if (single_node_topology == all_node_topology) {
mofid_topology = single_node_topology;
} else {
mofid_topology = single_node_topology + ',' + all_node_topology;
}
let mof_name = cif_name;
if (cif_name.endsWith('.cif') || cif_name.endsWith('.CIF')) {
mof_name = cif_name.substring(0, cif_name.length - 4);
}
const all_fragments = fragment_info.nodes.concat(fragment_info.linkers);
all_fragments.sort();
// Assembling the MOFid from id_constructor.py:assemble_mofid
let mofid = all_fragments.join('.');
mofid += ' MOFid-v1.';
mofid += mofid_topology + '.';
if (fragment_info.cat == 'no_mof') {
mofid += fragment_info.cat
} else if (fragment_info.cat != null) {
mofid += 'cat' + fragment_info.cat;
} else {
mofid += 'NA';
}
if (mofid.startsWith(' ')) { // Null linkers. Make .smi compatible
mofid = '*' + mofid + 'no_mof';
}
mofid += ';' + mof_name;
// Extract the MOFkey
var base_mofkey = "";
if (fragment_info.parsed) {
base_mofkey = FS.readFile("/Output/MetalOxo/mofkey_no_topology.txt", {'encoding': 'utf8'});
}
var mofkey = base_mofkey.replace('MOFkey-v1', 'MOFkey-v1.' + single_node_topology);
return {
raw_output: raw_mofid_output,
mofid: mofid,
mofkey: mofkey,
fragments: fragment_info
};
}
var _extractFragments = function(raw_mofid_output) {
// Parse the MOFid output, per id_constructor.py:extract_fragments
let all_fragments = raw_mofid_output.trim().split(/\r\n|\r|\n/g);
all_fragments = all_fragments.map(a => a.trim());
if (all_fragments == '') {
return {nodes: ['*'], linkers: [], cat: cat, parsed: false};
}
const cat_num_line = all_fragments.pop();
let cat = null;
if (cat_num_line.includes('simplified net(s)')) {
cat = (parseInt(cat_num_line[8]) - 1).toString(); // '# Found x simplified net(s)'
if (cat == '-1') {
cat = null;
}
} else {
all_fragments = ['*'];
}
// Parse node/linker fragment notation
if (all_fragments[0] != '# Nodes:') {
return {nodes: ['*'], linkers: [], cat: cat, parsed: false};
}
all_fragments.shift();
const linker_flag_loc = all_fragments.findIndex(line => (line == "# Linkers:"));
const node_fragments = all_fragments.slice(0, linker_flag_loc);
const linker_fragments = all_fragments.slice(linker_flag_loc+1);
node_fragments.sort();
linker_fragments.sort();
return {nodes: node_fragments, linkers: linker_fragments, cat: cat, parsed: true};
}
var rawToSmiles = function(raw_mofid) {
// Converts the raw output from the MOFid code to a parseable SMILES format
var lines = raw_mofid.replace(/\t/g, '').split(/\r\n|\r|\n/g); // remove trailing tabs before splitting
lines.pop(); // remove line about number of simplified nets
return lines.join('.');
}
handleInput = function() {
var ciffile = document.getElementById("cifloader").files[0];
document.getElementById("obresults").innerHTML = "<code>Processing " + ciffile.name + "</code>";
var cifreader = new FileReader();
cifreader.onload = function(event) {
var mofid_results = analyzeMOF(event.target.result, ciffile.name);
if (mofid_results.fragments.parsed) {
const mofid_html = "<div>MOFid:<br /><code>" + mofid_results.mofid + "</code></div>";
const mofkey_html = "<div>MOFkey:<br /><code>" + mofid_results.mofkey + "</code></div>";
document.getElementById("obresults").innerHTML = mofid_html + mofkey_html;
clearDropdown("cifdownload");
updateFileLists(); // populate the initial list of files
document.getElementById("folderdownload").selectedIndex = "0"; // back to the orig_mol
document.getElementById("resultsdownload").classList.remove("inactive");
document.getElementById("viewportnote").style.display = "none";
document.getElementById("viewportwrapper").classList.remove("inactive");
clearViewer(stage);
drawEmPDB(stage, "/Output/orig_mol.pdb");
} else {
document.getElementById("obresults").innerHTML = "<pre>Failed to calculate MOFid components</pre>";
document.getElementById("resultsdownload").classList.add("inactive");
document.getElementById("viewportwrapper").classList.add("inactive");
}
};
cifreader.readAsText(ciffile);
}
getTopology = function(path_to_cgd) {
// Extract topology from a generated CGD simplified net
const raw_rcsr_extract = FS.readFile("/RCSRnets.arc", {'encoding': 'utf8'});
const raw_cgd = FS.readFile(path_to_cgd, {'encoding': 'utf8'});
if (!raw_cgd.includes('NODE')) {
return "ERROR"; // not a MOF: no node building blocks found!
} else {
return webGavrog.getRawRCSRTopology(raw_cgd, raw_rcsr_extract);
}
}
clearDropdown = function(select_id) {
// Clear out the listed options from a <select> tag
var select_tag = document.getElementById(select_id);
while (select_tag.firstChild) {
select_tag.removeChild(select_tag.firstChild);
}
}
updateFileLists = function() {
clearDropdown("cifdownload");
var folder_name = getInputValue("folderdownload");
var selected_view_index = document.getElementById("view_type").selectedIndex;
var filelist;
var view_value_list = ["original", "nodes_and_linkers", "simplified_net"];
var view_name_list = ["Original MOF", "Nodes + Linkers", "Simplified topology"];
if (folder_name == "") { // original base directory
filelist = ["orig_mol.cif", "orig_mol.pdb"];
// Only keeping the original MOF in the viewer types:
view_value_list = [view_value_list[0]];
view_name_list = [view_name_list[0]];
selected_view_index = "0";
} else {
filelist = lsdir("/Output/" + folder_name);
// Removing the original MOF from the viewer types:
view_value_list.shift();
view_name_list.shift();
}
if (folder_name == "AllNode") {
// Separate linkers into branches + branch points for the AllNode algorithm
view_value_list[0] = "nodes_and_branches";
}
filelist.forEach(function(file) {
var option = document.createElement("option");
option.text = file;
option.value = file;
document.getElementById("cifdownload").appendChild(option);
});
clearDropdown("view_type");
for (var i=0; i<view_value_list.length; i++) {
var option = document.createElement("option");
option.text = view_name_list[i];
option.value = view_value_list[i];
document.getElementById("view_type").appendChild(option);
}
document.getElementById("view_type").selectedIndex = selected_view_index;
}
getInputValue = function(html_id) {
var input_tag = document.getElementById(html_id);
return input_tag.options[input_tag.selectedIndex].value;
}
updateAlgorithmSelection = function() {
updateFileLists();
updateAlgorithmView();
}
updateAlgorithmView = function() {
var view_name = getInputValue("view_type");
var folder_name = getInputValue("folderdownload");
clearViewer(stage);
if (view_name == "original") {
drawEmPDB(stage, "/Output/orig_mol.pdb", "element");
} else if (view_name == "nodes_and_linkers" || view_name == "nodes_and_branches") {
drawEmPDB(stage, "/Output/" + folder_name + "/nodes.pdb", UniformColor(0xFF9155));
drawEmPDB(stage, "/Output/" + folder_name + "/node_bridges.pdb", UniformColor(0xFF9155));
if (view_name == "nodes_and_linkers") {
drawEmPDB(stage, "/Output/" + folder_name + "/linkers.pdb", UniformColor(0x2298FE));
} else {
drawEmPDB(stage, "/Output/" + folder_name + "/branches.pdb", UniformColor(0x2298FE));
drawEmPDB(stage, "/Output/" + folder_name + "/branch_points.pdb", UniformColor(0x2298FE));
}
} else if (view_name == "simplified_net") {
//drawEmPDB(stage, "/Output/" + folder_name + "/simplified_topology_with_two_conn.pdb", UniformColor(0x888888));
drawEmPDB(stage, "/Output/" + folder_name + "/simplified_topology_with_two_conn.pdb", "element");
} else {
throw "Unknown view name: " + view_name;
}
}
clearViewer = function(ngl_stage) {
ngl_stage.removeAllComponents();
}
addPDBtoViewer = function(ngl_stage, path_to_cif, color_scheme = "element") {
var component;
ngl_stage.loadFile(path_to_cif, {ext: "pdb"}).then( function( o ){
o.addRepresentation("ball+stick", {colorScheme: color_scheme});
o.addRepresentation( "unitcell" );
o.autoView();
/* See class documentation at http://nglviewer.org/ngl/api/class/src/stage/stage.js~Stage.html */
/* See also the general documentation at http://nglviewer.org/ngl/api/manual/ */
} );
return component;
}
drawEmPDB = function(ngl_stage, emscripten_path, color_scheme = "element") {
var cif_string = FS.readFile(emscripten_path, {'encoding': 'utf8'});
var temp_file = new Blob([cif_string], {type: 'chemical/x-cif'});
return addPDBtoViewer(ngl_stage, temp_file, color_scheme);
}
UniformColor = function(hex_color = 0x000000) {
return NGL.ColormakerRegistry.addScheme(function(params) {
this.atomColor = function(atom) {
return hex_color;
}
});
}
handleDownload = function() {
var folder_input = document.getElementById("folderdownload");
var download_input = document.getElementById("cifdownload");
var folder_name = folder_input.options[folder_input.selectedIndex].value;
var filename = download_input.options[download_input.selectedIndex].value;
var filepath = "Output/" + folder_name + "/" + filename; // Set in deconstructor.h:DEFAULT_OUTPUT_PATH
var contents = FS.readFile(filepath, {'encoding': 'utf8'});
var download_contents = "data:text/plain;base64," + btoa(contents);
// Open download dialog using a temporary hidden link
var fakelink = document.createElement("a");
fakelink.setAttribute("href", download_contents);
fakelink.setAttribute("download", filename);
fakelink.style.display = "none";
document.body.appendChild(fakelink);
fakelink.click();
document.body.removeChild(fakelink);
}
</script>
<header>
<img src="mofid_logo.png" id="headerlogo" />
<h1>MOFid/MOFkey generator</h1>
<div id="loading">
<div class="spinner" id='spinner'></div>
<div class="emscripten" id="status">Downloading...</div>
<div class="emscripten">
<progress value="0" max="100" id="progress" hidden=1></progress>
</div>
</div>
</header>
<div id="inputblock" class="content">
Enter CIF:
<input type="file" id="cifloader"></input>
<input type="submit" value="Submit" id="emrun" onclick="handleInput()" disabled></input>
</div>
<div id="resultsdownload" class="content inactive">
<!--<h3>Algorithms</h3>-->
<div>Visualization algorithm:
<select id="folderdownload" onchange="updateAlgorithmSelection()">
<option value="" selected>Original input</option>
<option value="MetalOxo">Metal-Oxo</option>
<option value="SingleNode">Single Node</option>
<option value="AllNode">All Node</option>
<option value="StandardIsolated">"Standard" Algorithm</option>
</select>
</div>
<div>Visualization type:
<select id="view_type" onchange="updateAlgorithmView()">
<option value="none" selected>None</option>
</select>
</div>
<div>
Download CIF:
<select id="cifdownload"><option value="temp">Download options</option></select>
<input type="submit" value="Download" id="rundownload" onclick="handleDownload()"></input>
</div>
</div>
<div id="viewportwrapper" style="width:400px;" class="content inactive">
<div id="viewportnote" style="position: relative; left: 1em; top: 1em; z-index: 2;">(MOFs are visualized here)</div>
<div id="cifviewport" style="width:400px; height:300px;"></div>
</div>
<div id="identifiers">
<span id="obresults"></span> <!-- TODO: implement a popup menu for "raw results" -->
</div>
<script type='text/javascript'>
var statusElement = document.getElementById('status');
var progressElement = document.getElementById('progress');
var spinnerElement = document.getElementById('spinner');
var Module = {
preRun: [],
postRun: [function() {document.getElementById("emrun").disabled = false;}],
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&");
//text = text.replace(/</g, "<");
//text = text.replace(/>/g, ">");
//text = text.replace('\n', '<br>', 'g');
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
printErr: function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
if (0) { // XXX disabled for safety typeof dump == 'function') {
dump(text + '\n'); // fast, straight to the real console
} else {
console.error(text);
}
},
canvas: (function() {
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
return null;
})(),
setStatus: function(text) {
if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' };
if (text === Module.setStatus.text) return;
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
var now = Date.now();
if (m && now - Date.now() < 30) return; // if this is a progress update, skip it if too soon
if (m) {
text = m[1];
progressElement.value = parseInt(m[2])*100;
progressElement.max = parseInt(m[4])*100;
progressElement.hidden = false;
spinnerElement.hidden = false;
} else {
progressElement.value = null;
progressElement.max = null;
progressElement.hidden = true;
if (!text) spinnerElement.style.display = 'none';
}
statusElement.innerHTML = text;
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
}
};
Module.setStatus('Downloading...');
window.onerror = function(event) {
// TODO: do not warn on ok events like simulating an infinite loop or exitStatus
Module.setStatus('Exception thrown, see JavaScript console');
spinnerElement.style.display = 'none';
Module.setStatus = function(text) {
if (text) Module.printErr('[post-exception status] ' + text);
};
};
</script>
<script async type="text/javascript" src="sbu.js"></script>
</body>
</html>