overview_html 27.5 KB
Newer Older
1
2
3
<!DOCTYPE html>
<html>
  <head>
4
5
6
7
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv='cache-control' content='no-cache'>
    <meta http-equiv='expires' content='0'>
    <meta http-equiv='pragma' content='no-cache'>  
8
    <title>BiG-SCAPE Result</title>
9
10
    <link rel="stylesheet" type="text/css" href="../../css/w3.css">
    <link rel="stylesheet" type="text/css" href="../../css/style.css">
11
  </head>
12
13
14
15
16
  <body>
    <script src="../../js/jquery-3.2.1.min.js"></script>
    <script src="../../js/kinetic-v5.1.0.min.js"></script>
    <script src="../../js/Chart.bundle.js"></script>
    <script src="../../js/biojs-io-newick.min.js"></script>
17
    <script src="../../js/clusterfck-0.1-satria.js"></script>
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
    <script src="../../js/inchlib-1.2.0.1-satria.js"></script>
    <script src="./run_data.js"></script>
    <div class="overviewpage">
        <div class="overviewleft">
            <div class="infocontainer">
              <h3>Run Information</h3>
              <div class="infobar">
                <span class="infoleft">Analysis Started:</span>
                <span id="analysis_started" class="inforight"></span>
              </div>
              <div class="infobar">        
                <span class="infoleft">Parameters:</span>
                <span id="parameters" class="inforight"><b></b></span>
              </div>
              <div class="infobar">
                <span class="infoleft">Analysis Completed:</span>
                <span id="analysis_completed" class="inforight"></span>          
              </div>
            </div>
            <div class="infocontainer">
              <h3>Input Data</h3>
              <div class="infobar">
                <span class="infoleft">Total Number of Genomes:</span>
                <span id="total_accession" class="inforight"></span>          
              </div>
              <div class="infobar">
                <span class="infoleft">Total BGCs:</span>
                <span id="total_bgc" class="inforight"></span>          
              </div>
              <div class="infobar">
                <div style="float: left; width: 250;">
                  <canvas id="bgc_per_acc" width="250" height="250"></canvas>
                </div>
                <div style="float: right; width: 250;">
                  <canvas id="bgc_per_class" width="250" height="250"></canvas>
                </div>  
              </div>
            </div>
          </div>
          <div class="overviewright">
            <div class="infocontainer">
              <h3>Network Overview</h3>
              <div>
                <div id="network_selection" class="network-overview w3-row">
                </div>                 
                <div class="infobar">
                  <span class="infoleft">Number of families:</span>
                  <span id="network_total_families" class="inforight"></span>          
                </div>
                <div class="infobar">
                  <span class="infoleft">Average number of BGCs per family:</span>
                  <span id="network_avg_bgc_in_family" class="inforight"></span>          
                </div>
                <div class="infobar">
                  <span class="infoleft">Max number of BGCs in a family:</span>
                  <span id="network_max_bgc_in_family" class="inforight"></span>          
                </div>
                <div class="infobar">
                </div>
                <div class="infobar">
78
79
80
81
82
83
84
85
86
87
88
                    <span style="font-weight: bold;">GCF absence/presence heatmap</span>
                </div>
                <div class="infobar">
                  <span class="infoleft" style="font-size: 12px;">
                    Cluster GCF based on: <br />
                    <select id="abpres_heatmap-col_clustering">                               
                    </select>
                  </span>
                  <span class="inforight" style="font-size: 12px;">
                    Show: <br />
                    <select id="abpres_heatmap-col_showtop">
89
90
91
                      <option value="20">20</option>
                      <option value="50">50</option>
                      <option value="100">100</option>
92
93
                      <option value="all">All</option>
                    </select>
94
                    largest GCFs
95
96
97
98
99
100
101
102
                  </span>
                </div>
                <div class="infobar">
                  <span class="infoleft" style="font-size: 12px;">
                    Cluster Genomes based on: <br />
                    <select id="abpres_heatmap-row_clustering">                               
                    </select>
                  </span>
103
                </div>
104
105
106
107
108
                <!--div class="infobar">
                  <span class="inforight" style="font-size: 12px;">
                    test
                  </span>
                  <span class="inforight" style="font-size: 12px;">
109
110
                      test
                    </span>
111
                </div-->
112
                <div class="infobar">
113
114
115
116
                </div>
                <div class="infobar">
                  <div id="abpres_heatmap">
                </div>
117
118
119
120
121
                </div>
              </div>
            </div>
          </div>
    </div>
122
123
124
  </body>
  <!-- javascripts -->
  <script type="text/javascript">
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
    function getRandomColor() {
      var letters = '0123456789ABCDEF';
      var color = '#';
      for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }
    $(document).ready(function(){
      // run information
      $("#analysis_started").html(run_data["start_time"]);
      $("#analysis_completed").html(run_data["end_time"] + " (" + run_data["duration"] + ")");
      $("#parameters").html("<strong>" + run_data["parameters"] + "</strong>");
      // input information
      $("#total_accession").html(run_data["input"]["accession"].length);
      $("#total_bgc").html(run_data["input"]["bgc"].length);
      // pie chart: BGC per Accession
      var pieLabels = [];
      var pieColors = [];
      var pieData = [];
      for (var i in run_data["input"]["accession"]) {
        pieLabels.push(run_data["input"]["accession"][i]["label"]);
        pieColors.push(getRandomColor());
        pieData.push(0);
      }
      for (var i in run_data["input"]["bgc"]) {
        pieData[run_data["input"]["bgc"][i]["acc"]] += 1;
      }
      new Chart(document.getElementById("bgc_per_acc"), {
        type: 'pie',
        data: {
          labels: pieLabels,
          datasets: [{
            label: "",
            backgroundColor: pieColors,
            data: pieData
          }]
        },
        options: {
          title: {
            display: true,
            text: 'BGC per Genome'
          },
          legend: {
            display: false,
          },
          responsive: false,
        }
      });
      // pie chart: BGC per Class
      var pieLabels = [];
      var pieColors = [];
      var pieData = [];
      for (var i in run_data["input"]["classes"]) {
        pieLabels.push(run_data["input"]["classes"][i]["label"]);
        var ccolor = (run_data["input"]["classes"][i].hasOwnProperty("color")?["input"]["classes"][i]["color"]:getRandomColor());
        pieColors.push(ccolor);
        pieData.push(0);
      }
      for (var i in run_data["input"]["bgc"]) {
        pieData[run_data["input"]["bgc"][i]["class"]] += 1;
      }
      new Chart(document.getElementById("bgc_per_class"), {
        type: 'pie',
        data: {
          labels: pieLabels,
          datasets: [{
            label: "",
            backgroundColor: pieColors,
            data: pieData
          }]
        },
        options: {
          title: {
            display: true,
            text: 'BGC per Class'
          },
          legend: {
            display: false,
          },
          responsive: false,
        }
      });
      // Network selector
      $("#network_selection").html("");
      for (var i in run_data["networks"]) {
        var selector = $("<div>" + run_data["networks"][i]["label"] + "</div>").addClass("tablink w3-bottombar w3-hover-light-grey w3-padding").appendTo($("<a href='##' onclick='javascript:viewNetwork(" + i + ");'></a>").appendTo($("#network_selection")));
      }
      viewNetwork(0);
    });
215
    
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
    function viewNetwork(idx) {
      $("#network_selection .tablink").removeClass("w3-border-red");
      $("#network_selection .tablink").eq(idx).addClass("w3-border-red");
      var maxBGC = 0;
      var sumBGC = 0;
      var totalFamily = run_data["networks"][idx]["families"].length;
      for (var i in run_data["networks"][idx]["families"]) {
        var members = run_data["networks"][idx]["families"][i]["members"];
        if (members.length > maxBGC) {
          maxBGC = members.length;
        }
        sumBGC += members.length;
      }
      $("#network_total_families").html(totalFamily);
      $("#network_avg_bgc_in_family").html((sumBGC / totalFamily).toFixed(0));
      $("#network_max_bgc_in_family").html(maxBGC);
      // absence/presence heatmap
233
234
235
236
237
238
239
240
241
      $("#abpres_heatmap-row_clustering").change(function(handler){ renderHeatmap(idx); });
      $("#abpres_heatmap-row_clustering").html("")
        .append("<option value='abpres' selected>Family Absence/Presence</option>")
        .append("<option value='name'>Accession Label</option>");
      for (var i in run_data["input"]["accession_newick"]) {
        $("#abpres_heatmap-row_clustering").append("<option value='newick_" + i + "'>" + run_data["input"]["accession_newick"][i]["label"] + "</option>");
      }
      $("#abpres_heatmap-col_clustering").change(function(handler){ renderHeatmap(idx); });
      $("#abpres_heatmap-col_clustering").html("")
242
243
244
        .append("<option value='abpres' selected>Genomes Absence/Presence</option>")
        .append("<option value='gcf'>BiG-SCAPE Distance Matrix</option>");
      $("#abpres_heatmap-col_showtop").change(function(handler){ renderHeatmap(idx); });
245
246
247
248
249
      renderHeatmap(idx);
    }
    
    function renderHeatmap(idx) {
      var inchlib_data = generateRealHeatmapData(run_data["input"], run_data["networks"][idx]);
250
251
252
253
254
      var inchlib = new InCHlib({
          target: "abpres_heatmap",
          metadata: false,
          heatmap_colors: "OrRd",
          draw_row_ids: true,
255
          dendrogram: true,
256
257
258
259
          column_dendrogram: true,
          heatmap_part_width: 0.9,
          max_column_width: 15,
          fixed_row_id_size: 5,
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
          alternative_data: false,
          navigation_toggle: {
            color_scale: false,
            export_button: true,
            hint_button: false,
            filter_button: false,
          },
      });
      inchlib.settings.ranges = [];
      for(i = 0; i < inchlib_data.data.feature_names.length; i++) {
        inchlib.settings.ranges.push([0,1,1]);
      }
      inchlib.read_data(inchlib_data);
      inchlib.draw();
    }

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
    function calculateDistance(vector_1, vector_2, method) {
      switch (method) {
        case "eucledian":
          var sumpower = 0.00;
          for (var i in vector_1) {
            sumpower += Math.pow(vector_1[i] - vector_2[i], 2);
          }
          return Math.sqrt(sumpower);
      case "jaccard":
          var union = 0.00;
          var intersection = 0.00;
          for (var i in vector_1) {
            if ((vector_1[i] > 0) && (vector_2[i] > 0)) {
              intersection += 1.00;
              union += 1.00;
            } else if ((vector_1[i] > 0) || (vector_2[i] > 0)) {
              union += 1.00;
            }
          }
          return (union > 0?(1.00 - (intersection / union)):1.00);
        default:
          return 0
      }
    }

301
302
    function generateRealHeatmapData(input_data, network_data) {
      var parser = require("biojs-io-newick");
303
304
305
306
307
      var family_data = network_data["families"].slice(0).sort(function(a,b) { return b["members"].length - a["members"].length });
      var get_fam_id = [];
      for (var i in family_data) {
        get_fam_id.push(network_data["families"].indexOf(family_data[i]));
      }
308
309
310
311
312
313
314
315
316
317
318
319
320
      var result = {
        "data": {
          "nodes": {},
          "feature_names": []
        },
        "alternative_data": {
          "feature_names": [],
          "nodes": {}
        },
        "column_dendrogram": {
          "nodes": {}
        }
      }
321
      // apply GCF filtering
322
      var included_gcfs = [];
323
324
325
326
327
328
329
330
331
332
333
334
335
      var gcf_to_show = 1;
      switch ($("#abpres_heatmap-col_showtop").val()) {
        case "all":
          if (confirm("This will includes all " + family_data.length + " GCFs. It may affect performance and/or the visibility of the heatmap. Continue?")) {
            gcf_to_show = family_data.length;
          } else {
            $("#abpres_heatmap-col_showtop").val("20");
            gcf_to_show = parseInt($("#abpres_heatmap-col_showtop").val());
          }
          break;
        default:
          gcf_to_show = parseInt($("#abpres_heatmap-col_showtop").val());
          break;
336
      }
337
338
339
340
      for (var i = 0; i < gcf_to_show; i++) {
        if (i < family_data.length) {
          included_gcfs.push(i);
        }
341
      }
342
      // calculate absence/presence
343
      var acc_features = {};
344
345
      var acc_labels = {};
      var feature_names = [];
346
347
348
      for (var i in run_data["input"]["accession"]) {
        var accId = run_data["input"]["accession"][i]["id"];
        acc_features[accId] = [];
349
        for (var j = 0; j < included_gcfs.length; j++) {
350
351
352
          acc_features[accId].push(0);
        }
      }
353
354
355
356
357
      for (var i in included_gcfs) {
        var fam_data = family_data[included_gcfs[i]];
        feature_names.push(fam_data["label"]);
        for (var j in fam_data["members"]) {
          var bgcId = fam_data["members"][j];
358
359
360
361
          var accId = run_data["input"]["accession"][run_data["input"]["bgc"][bgcId]["acc"]]["id"];
          acc_features[accId][i] += 1;
        }
      }
362
363
364
365
366
367
368
369
370
371
372
      // apply Genomes filtering (only shows genomes with filtered GCFs, unless using custom newick)
      var included_accessions = [];
      for (var i = 0; i < run_data["input"]["accession"].length; i++) {
        var accId = run_data["input"]["accession"][i]["id"];
        for (var j in acc_features[accId]) {
          if ((acc_features[accId][j] > 0) || (["abpres", "name"].indexOf($("#abpres_heatmap-row_clustering").val()) < 0)) {
            included_accessions.push(i);
            break;
          }
        }
      }
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
      // build row (accession) dendrogram
      switch ($("#abpres_heatmap-row_clustering").val()) {
        case "abpres":
          var cluster_items = [];
          for (var i in run_data["input"]["accession"]) {
            if (included_accessions.indexOf(parseInt(i)) > -1) {
              var accId = run_data["input"]["accession"][i]["id"];
              cluster_items.push({
                "id": accId,
                "features": acc_features[accId]
              });
              acc_labels[accId] = input_data["accession"][i]["label"];
            }
          }
          var cluster_fck = clusterfck.hcluster(cluster_items, function(f1, f2){
388
            return calculateDistance(f1["features"], f2["features"], "jaccard");
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
          }, clusterfck.COMPLETE_LINKAGE);
          result["data"]["nodes"] = clusterfck_tree_to_inchlib_nodes(cluster_fck[0]);
          break;
        case "name":
          var cluster_items = [];
          for (var i in run_data["input"]["accession"]) {
            if (included_accessions.indexOf(parseInt(i)) > -1) {
              var accId = run_data["input"]["accession"][i]["id"];
              cluster_items.push({
                "id": accId,
                "features": input_data["accession"][i]["label"]
              });
              acc_labels[accId] = input_data["accession"][i]["label"];
            }
          }
          var cluster_fck = clusterfck.hcluster(cluster_items, function(f1, f2){
            var label1 = f1["features"].toLowerCase();
            var label2 = f2["features"].toLowerCase();
            var word_length = Math.max(label1.length, label2.length);
            var matches = 0;
            for (var i=0; i < word_length; i++) {
              if (label1[i] !== label2[i]) {
                break;
              }
              matches++;
            }
            return (word_length - matches) / word_length;
          }, clusterfck.COMPLETE_LINKAGE);
          result["data"]["nodes"] = clusterfck_tree_to_inchlib_nodes(cluster_fck[0]);
          break;
        default:
          var newick_idx = parseInt($("#abpres_heatmap-row_clustering").val().split("newick_").pop());
          var acc_tree = parser.parse_newick(input_data["accession_newick"][newick_idx]["newick"]);
          for (var i in run_data["input"]["accession"]) {
            acc_labels[run_data["input"]["accession"][i]["id"]] = input_data["accession"][i]["label"];
          }
          var incorporated_accession = get_all_labels_in_tree(acc_tree);
          if ((acc_tree["children"][0]["name"] === undefined) || (acc_tree["children"][0]["name"].length < 1)) { // hack-ish catch
            acc_tree["children"].shift();
          }
          result["data"]["nodes"] = biojs_newick_tree_to_inchlib_nodes(acc_tree);
          break;
      }
      
      // build column (family) dendrogram
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
      switch ($("#abpres_heatmap-col_clustering").val()) {
        case "abpres":
          var cluster_items = [];
          for (var i in included_gcfs) {
            var fam_features = [];
            for (var j in included_accessions) {
              var accId = run_data["input"]["accession"][included_accessions[j]]["id"];
              fam_features.push(acc_features[accId][i]);
            }
            cluster_items.push({
              "id": family_data[included_gcfs[i]]["label"],
              "features": fam_features
            });
          }
          var cluster_fck = clusterfck.hcluster(cluster_items, function(f1, f2){
            return calculateDistance(f1["features"], f2["features"], "jaccard");
          }, clusterfck.COMPLETE_LINKAGE);
          result["column_dendrogram"]["nodes"] = clusterfck_tree_to_inchlib_nodes(cluster_fck[0]);
          break;
453
        case "gcf":
454
455
456
457
          var cluster_items = [];
          for (var i in included_gcfs) {
            cluster_items.push({
              "id": family_data[included_gcfs[i]]["label"],
458
              "features": [included_gcfs[i]]
459
460
461
            });
          }
          var cluster_fck = clusterfck.hcluster(cluster_items, function(f1, f2){
462
463
464
            var famId_1 = get_fam_id[f1["features"][0]];
            var famId_2 = get_fam_id[f2["features"][0]];
            return (famId_1 > famId_2?1.00-network_data["families_similarity"][famId_1][famId_2][0]:1.00-network_data["families_similarity"][famId_2][famId_1][0]);
465
466
467
          }, clusterfck.COMPLETE_LINKAGE);
          result["column_dendrogram"]["nodes"] = clusterfck_tree_to_inchlib_nodes(cluster_fck[0]);
          break;
468
469
      }
      // update row labels
470
471
472
473
      for (var i in result["data"]["nodes"]) {
        var node = result["data"]["nodes"][i];
        if (node.hasOwnProperty("objects")) {
          var accId = node["objects"][0];
474
          node["objects"][0] = acc_labels[accId];
475
476
477
          node["features"] = acc_features[accId];
        }
      }
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
      // update columns based on column dendrogram
      function fetchSortedTreeIdx(nodes, curNode = -1, sortedIdx = []) {
        if (curNode === -1) { // look for the root node
          for (var idx in nodes) {
            if (!nodes[idx].hasOwnProperty("parent")) {
              curNode = idx;
              break;
            }
          }
        }
        var node = nodes[curNode];
        if (node.hasOwnProperty("left_child")) {
          sortedIdx = fetchSortedTreeIdx(nodes, node["right_child"], sortedIdx);
          sortedIdx = fetchSortedTreeIdx(nodes, node["left_child"], sortedIdx);
        } else {
          sortedIdx.push(curNode);
        }
        return sortedIdx;
      }
      var col_dendrosorted = fetchSortedTreeIdx(result["column_dendrogram"]["nodes"]);
      var colidx_dendrosorted = [];
      for (var i in col_dendrosorted) {
        var famId = result["column_dendrogram"]["nodes"][col_dendrosorted[i]]["objects"][0];
        colidx_dendrosorted.push(feature_names.indexOf(famId));
      }
      var feature_names_dendrosorted = [];
      for (i in colidx_dendrosorted) {
        feature_names_dendrosorted.push(feature_names[colidx_dendrosorted[i]]);
      }
      feature_names = feature_names_dendrosorted;
      result["data"]["feature_names"] = feature_names;
      for (nodeId in result["data"]["nodes"]) {
        var node = result["data"]["nodes"][nodeId];
        if (node.hasOwnProperty("features")) {
          var feature_dendrosorted = [];
          for (i in colidx_dendrosorted) {
            feature_dendrosorted.push(node["features"][colidx_dendrosorted[i]]);
          }
          node["features"] = feature_dendrosorted;
        }
      }
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
      return result;
    }

    function get_all_labels_in_tree(node) {
      var accession_list = [];
      if (node.hasOwnProperty("children")) {
        for (var i = 0; i < node["children"].length; i++) {
          var accessions_children = get_all_labels_in_tree(node["children"][i]);
          for (var j in accessions_children) {
            accession_list.push(accessions_children[j]);
          }
        }
      } else {
        accession_list.push(node["name"]);
      }
      return accession_list;
    }

537
538
539
540
541
    // convert clusterfck tree to inchlib nodes
    function clusterfck_tree_to_inchlib_nodes(node, parentNode = -1, nodes = {}, leaf_count = 0, node_count = 0, branch_parent_length = 0, branch_total_length = 0, isLeftChild = true) {
      if (node["size"] > 1) { // is a node
        node_count++;
        var nId = "node_" + node_count;
542
        var branchLength = branch_parent_length + 1;
543
        if (node.hasOwnProperty("dist")) {
544
          //branchLength += node["dist"];
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
        }
        if (branchLength > branch_total_length) {
          branch_total_length = branchLength;
        }
        nodes[nId] = {
          "count": node["size"],
          "distance": branchLength,
        }
        if (parentNode !== -1) {
          nodes[nId]["parent"] = parentNode;
        }
        if (nodes.hasOwnProperty(parentNode)) {
          if (isLeftChild) {
            nodes[parentNode]["left_child"] = nId;
          } else {
            nodes[parentNode]["right_child"] = nId;
561
          }
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
        }
        var recresult = clusterfck_tree_to_inchlib_nodes(node["left"], nId, nodes, leaf_count, node_count, branchLength, branch_total_length, true);
        nodes = recresult[0];
        leaf_count = recresult[1];
        node_count = recresult[2];
        if (recresult[3] > branch_total_length) {
          branch_total_length = recresult[3];
        }
        recresult = clusterfck_tree_to_inchlib_nodes(node["right"], nId, nodes, leaf_count, node_count, branchLength, branch_total_length, false);
        nodes = recresult[0];
        leaf_count = recresult[1];
        node_count = recresult[2];
        if (recresult[3] > branch_total_length) {
          branch_total_length = recresult[3];
        }
      } else { // is a leaf
        leaf_count++;
        var lId = "leaf_" + leaf_count;
580
        var branchLength = branch_parent_length + 1;
581
        if (node.hasOwnProperty("dist")) {
582
          //branchLength += node["dist"];
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
        }

        if (branchLength > branch_total_length) {
          branch_total_length = branchLength;
        }
        nodes[lId] = {
          "count": 1,
          "distance": branchLength,
          "features": [],
          "objects": [node["canonical"]["id"]],
        };
        if (nodes[lId]["parent"] !== -1) {
          nodes[lId]["parent"] = parentNode;
        }
        if (nodes.hasOwnProperty(parentNode)) {
          if (isLeftChild) {
            nodes[parentNode]["left_child"] = lId;
          } else {
            nodes[parentNode]["right_child"] = lId;
602
          }
603
604
605
606
607
        }
      }
      if (parentNode == -1) {
        // the root tree, fill left_child & right_child and churn results
        for (var nodeId in nodes) {
608
609
610
611
612
613
          // ignore branch length
          if (nodeId.split("_")[0] == "node") {
            nodes[nodeId]["distance"] = branch_total_length - nodes[nodeId]["distance"];
          } else {
            nodes[nodeId]["distance"] = 0;
          }
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
        }
        return nodes;
      } else {
        // recursive return
        return [nodes, leaf_count, node_count, branch_total_length];
      }
    }

    // convert biojs-io-newick tree to inchlib nodes
    function biojs_newick_tree_to_inchlib_nodes(node, parentNode = -1, nodes = {}, leaf_count = 0, node_count = 0, branch_parent_length = 0, branch_total_length = 0) {
      if (node.hasOwnProperty("children")) { // is a node
        node_count++;
        var node_count_pre = node_count;
        for (var i = 0; i < node["children"].length - 1; i++) {    
          var nId = "node_" + (node_count + i);
          var branchLength = branch_parent_length + (i==0?(node.hasOwnProperty("branch_length")?node["branch_length"]:0.00):0.00);
630
631
632
          if (branchLength > branch_total_length) {
            branch_total_length = branchLength;
          }
633
634
          nodes[nId] = {
            "parent": (i==0?parentNode:("node_" + (node_count + i - 1))),
635
            "distance": branchLength,
636
            "count": 0,
637
          };
638
639
          if (nodes[nId]["parent"] === -1) {
            delete nodes[nId]["parent"];
640
          }
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
          if (i < node["children"].length - 2) {
            nodes[nId]["right_child"] = "node_" + (node_count + i + 1);
          }
        }
        node_count += Math.max(0, node["children"].length - 2);
        for (var i = 0; i < node["children"].length; i++) {
          var pId = (i < node["children"].length - 2?(node_count_pre + i):(node_count_pre + node["children"].length - 2));
          var parentChild = "node_" + pId;
          var branchLength = branch_parent_length + (node.hasOwnProperty("branch_length")?node["branch_length"]:0.00);
          var recresult = biojs_newick_tree_to_inchlib_nodes(node["children"][i], parentChild, nodes, leaf_count, node_count, branchLength, 0);
          nodes = recresult[0];
          if (nodes[parentChild].hasOwnProperty("parent")) {
            nodes[nodes[parentChild]["parent"]]["count"] += nodes[parentChild]["count"];
          }
          leaf_count = recresult[1];
          node_count = recresult[2];
          if (recresult[3] > branch_total_length) {
            branch_total_length = recresult[3];
659
660
          }
        }
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
        if (nodes.hasOwnProperty(parentNode)) {
          nodes[parentNode]["left_child"] = "node_" + node_count_pre;
        }
      } else { // is a leaf
        leaf_count++;
        var lId = "leaf_" + leaf_count;
        var branchLength = branch_parent_length + (node.hasOwnProperty("branch_length")?node["branch_length"]:0.00);
        if (branchLength > branch_total_length) {
          branch_total_length = branchLength;
        }
        nodes[lId] = {
          "count": 1,
          "distance": branchLength,
          "features": [],
          "parent": parentNode, 
          "objects": [node["name"]]
        };
        if (nodes[lId]["parent"] === -1) {
          delete nodes[lId]["parent"];
        }
        if (nodes.hasOwnProperty(parentNode)) {
          nodes[parentNode]["count"] += nodes[lId]["count"];
          if (!nodes[parentNode].hasOwnProperty("right_child")) {
            nodes[parentNode]["right_child"] = lId;
          } else {
            nodes[parentNode]["left_child"] = lId;
687
          }
688
        }
689
      }
690
691
692
      if (parentNode == -1) {
        // the root tree, fill left_child & right_child and churn results
        for (var nodeId in nodes) {
693
            nodes[nodeId]["distance"] = branch_total_length - nodes[nodeId]["distance"];
694
695
696
697
698
699
700
        }
        return nodes;
      } else {
        // recursive return
        return [nodes, leaf_count, node_count, branch_total_length];
      }
    }
701
  </script>
702
</html>