-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArborView.html
2412 lines (2017 loc) · 114 KB
/
ArborView.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
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<style>
.inline-block-child {
display: inline-block;
}
.scrollbar-window{
overflow: auto;
/*overflow-x: scroll;*/
/*height: 200px;*/
}
input[type="file"] {
/* Hide the button in boot strap*/
display: none;
}
.input-group-text:hover {
filter: brightness(80%);
}
.legend-element:hover {
filter: opacity(0.5);
cursor: pointer;
}
@keyframes spin {
0% {
transform: rotate(0);
}
25% {
transform: rotate(-0.05turn);
}
50% {
transform: rotate(0);
}
75% {
transform: rotate(0.05turn);
}
100% {
transform: translateY(0);
}
}
@keyframes updown {
0% {
transform: translateY(-10%);
}
50% {
transform: translateY(10%);
}
100% {
transform: translateY(-10%);
}
}
.icon-spin {
animation: spin 1s linear infinite;
}
.icon-jump {
animation: updown 1s ease infinite
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Random colour library for creating some nice highlighted trees https://github.com/davidmerfield/randomColor -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/randomcolor/0.6.1/randomColor.min.js" integrity="sha512-vPeZ7JCboHcfpqSx5ZD+/jpEhS4JpXxfz9orSvAPPj0EKUVShU2tgy7XkU+oujBJKnWmu4hU7r9MMQNWPfXsYw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<!-- Below switching to tidy tree 0.5.1 as the dev broke 0.5.0 -->
<script rel="stylesheet" type="text/javascript" href="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
<!--JQuery Beautiful Data Tables-->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<!--Bootstrap 5 library elements-->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<!--toggle buttons by https://palcarazm.github.io/bootstrap5-toggle/ -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/css/bootstrap5-toggle.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/bootstrap5-toggle.jquery.min.js"></script>
<!-- Sweet Alerts 2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script type="text/javascript">
const __DEADBEEF__ = 0xDEADBEEF;
const __DEADFOOD__ = 0xDEADF00D;
//var test_newick = "((BGIOSIFCE006902.1_ORYSA:0.652945[&&NHX:S=ORYSA],(At4g19560.1_ARATH:0.566484[&&NHX:S=ARATH],(At4g19600.1_ARATH:0.229647[&&NHX:S=ARATH],At5g45190.1_ARATH:0.149569[&&NHX:S=ARATH]):0.109796[&&NHX:S=ARATH:SIS=100:D=Y:B=100]):0.283052[&&NHX:S=ARATH:SIS=100:D=Y:B=100]):0.930921[&&NHX:S=Magnoliophyta:D=N:B=100],((((((((((((CCNK_HUMAN:0.001351[&&NHX:S=HUMAN],CCNK_F3_PANTR:0.001588[&&NHX:S=PANTR]):0.009317[&&NHX:S=Homo/Pan/Gorilla_group:D=N:B=100],CCNK_MACMU:0.01227[&&NHX:S=MACMU]):0.020339[&&NHX:S=Catarrhini:D=N:B=100],(CCNK_BOVIN:0.049478[&&NHX:S=BOVIN],CCNK_CANFA:0.076883[&&NHX:S=CANFA]):0.026972[&&NHX:S=Laurasiatheria:D=N:B=97]):0.01376[&&NHX:S=Eutheria:D=N:B=62],(Ccnk_MOUSE:0.018183[&&NHX:S=MOUSE],LOC500715_RAT:0.02728[&&NHX:S=RAT]):0.054247[&&NHX:S=Murinae:D=N:B=100]):0.087752[&&NHX:S=Eutheria:D=N:B=65],CCNK_MONDO:0.069457[&&NHX:S=MONDO]):0.053263[&&NHX:S=Theria:D=N:B=83],NP_001026380_CHICK:0.085022[&&NHX:S=CHICK]):0.059401[&&NHX:S=Amniota:D=N:B=80],CCNK_XENTR:0.175799[&&NHX:S=XENTR]):0.075577[&&NHX:S=Tetrapoda:D=N:B=97],((si_dkey-60a16_F2_BRARE:0.143195[&&NHX:S=BRARE],(CCNK_TETNG:0.142629[&&NHX:S=TETNG],CCNK_F2_GASAC:0.115749[&&NHX:S=GASAC]):0.130837[&&NHX:S=Percomorpha:D=N:B=100]):0.077038[&&NHX:S=Clupeocephala:D=N:B=95],ENSGACT00000017400_GASAC:0.40355[&&NHX:S=GASAC]):0.058401[&&NHX:S=Clupeocephala:SIS=33:D=Y:B=13]):0.233994[&&NHX:S=Euteleostomi:D=N:B=18],(ENSCINT00000017473_CIOIN:0[&&NHX:S=CIOIN],ENSCINT00000026852_CIOIN:0.002343[&&NHX:S=CIOIN]):0.481407[&&NHX:S=CIOIN:SIS=100:D=Y:B=100]):0.090892[&&NHX:S=Chordata:D=N:B=98],((CycK-RA_DROME:0.17719[&&NHX:S=DROME],dper_GLEANR_8777_caf1_DROPE:0.174477[&&NHX:S=DROPE]):0.199588[&&NHX:S=Sophophora:D=N:B=100],(AAEL013531-RA_AEDAE:0.214131[&&NHX:S=AEDAE],XP_317464_ANOGA:0.204436[&&NHX:S=ANOGA]):0.178396[&&NHX:S=Culicidae:D=N:B=100]):0.293157[&&NHX:S=Diptera:D=N:B=100]):0.104694[&&NHX:S=Coelomata:D=N:B=98],Smp_130980_SCHMA:0.624197[&&NHX:S=SCHMA]):0.041513[&&NHX:S=Bilateria:D=N:B=84],(WBGene00009650_CAEEL:0.186775[&&NHX:S=CAEEL],(CBG04574_CAEBR:0.21279[&&NHX:S=CAEBR],cr01.sctg48.wum.67.1_CAERE:0.192611[&&NHX:S=CAERE]):0.076335[&&NHX:S=Caenorhabditis:D=N:B=86]):1.18006[&&NHX:S=Caenorhabditis:D=N:B=86]):0.311276[&&NHX:S=Bilateria:D=N:B=84])[&&NHX:S=Eukaryota:D=N:B=0];";
const TREE = __DEADBEEF__;
// the '= __DEADFOOD__' is an expression to find and replace and inline tsv string e.g. 'head1\thead2\nv1\tv2\n'
const DATA = __DEADFOOD__;
const DEBUG = false;
const TREE_OFFSET = 100;
var NEWICK = null;
var tree_root = null;
var METADATA = null;
var TABLE_HEADERS = null;
var data_table = null;
var query_table = null;
var ORIGINAL_DATA = null;
var ORIGINAL_VIEW_BOX = null;
var ORIGINAL_WIDTH_SVG = 0;
var LAST_MOVE_X = 0;
var LAST_MOVE_Y = 0;
var SHOW_BRANCH_LENGTHS = true;
var TREE_VAL = 1; // sets defualt tree to draw
//var TREE_SWITCH = false;
var collapse_subtree = false; // can think of another way to signal state without our larger refactor
var focused_element = null; // Focused element to have its colour reset
var RADIUS_INCREASED = false;
var MENU_CREATED = false;
const colour_legend = new Array;
const default_color = "#999";
const clicked_color = "blue";
const ID_FIELD = 0;
// Refactoring selected nodes to make it easier to update the legend and selected nodes on dom changes
//const SELECTED_NODES = new Set();
const right_mouse = 3;
const center_mouse = 2;
const left_mouse = 1;
const CIRCLE_SIZE_SELECTED = 6;
const INNER_NODE_SIZE = 4;
const LEAF_NODE_SIZE = 6;
const DECIMAL_PLACES = 4;
const DISTANCE_LABEL_OFFSET = 5.2
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TREE FUNCTIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// These are messy due to the way in which they were created, and there has not been time
// to refactor them yet sadly.
const dendrogram_chart = (data) => {
// Made with lost of help from: https://observablehq.com/d/6c52fee38fb28b2f
var ele = document.getElementById("TreeData");
var ele_style = window.getComputedStyle(ele);
const width = parseInt(ele_style.width);
//var width = window.innerWidth;
const marginTop = 40;
const marginRight = 10;
const marginBottom = 30; // updated for viewing
const marginLeft = 40;
let label_safety_factor = 200;
const inner_radius = width - label_safety_factor;
function setDistance(d, y0, k) {
// From the tree of life code
d.distance = (y0 += d.data.d) * k;
if (d.children) d.children.forEach(d => setDistance(d, y0, k));
}
function maxLength(d) {
return d.data.d + (d.children ? d3.max(d.children, maxLength) : 0);
}
// Rows are separated by dx pixels, columns by dy pixels. These names can be counter-intuitive
// (dx is a height, and dy a width). This because the tree must be viewed with the root at the
// “bottom”, in the data domain. The width of a column is based on the tree’s height.
const root = d3.hierarchy(data);
setDistance(root, root.data.d = 0, (inner_radius / maxLength(root))) // Third value is a scaling factor
const leaves_in_tree = root.leaves();
const pixels_per_label = 15;
const dx = 20;
const dy = (width - marginRight - marginLeft) / (1 + root.height);
tree = d3.cluster()
.nodeSize([dx, dy])
.separation( (a, b) => { return 1;}) // Can pass in a custom function to alter distance between labels, 1 means all labels are spaced the same distance
diagonal = (d) => {
//console.log(d.source);
// TODO have this reflect the branch length
// https://www.w3.org/TR/SVG/paths.html#PathElement for path movements meanings
//return `M${d.source.y},${d.source.x} V${d.target.x} H${d.target.y}`
return `M${d.source.distance},${d.source.x} L${d.source.distance},${d.target.x} L${d.target.distance},${d.target.x}`
};
// Create the SVG container, a layer for the links and a layer for the nodes.
const svg = d3.create("svg")
.attr("id", "TreeSVG")
.attr("width", width + 20) //makes sure all tree nodes are within view
.attr("style", `width:100%; height: auto; font: 10px sans-serif; user-select: none;`)
const gLink = svg.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.8)
.attr("stroke-width", 2.0);
const gNode = svg.append("g")
.attr("cursor", "pointer")
.attr("pointer-events", "all");
function showLinkExtension(d, show=true) {
const dest = show ? inner_radius : d.target.distance;
const path = d3.path();
path.moveTo(d.target.distance, d.target.x);
path.lineTo(dest, d.target.x);
return path.toString();
}
function update(event, source) {
const duration = event?.altKey ? 2500 : 250; // hold the alt key to slow down the transition
const nodes = root.descendants().reverse(); // Might be able to replace with the recurse tree function for speed up
const links = root.links();
// Compute the new tree layout.
// Converting tree to cluster may solve our conundrum...
tree(root);
svg.selectAll(".extension-node-links").remove();
const linkExtension = svg.append("g") // Would probably save rendering if this was tied to the "entered nodes"
.attr("class", "extension-node-links")
.attr("fill", "none")
.attr("stroke", "#000")
.attr("stroke-opacity", 0.5)
.attr("stroke-dasharray", "4")
.selectAll("path")
.data(root.links().filter(d => d.target.data.leaf ))
.join("path")
.each(function(d) { d.target.linkExtensionNode = this; })
.attr("d", (d) => showLinkExtension(d, true)); // Shows lines to link
let left = root;
let right = root;
root.eachBefore(node => {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
});
ORIGINAL_WIDTH_SVG=width
const height = right.x - left.x + marginTop + marginBottom;
const transition = svg.transition()
.duration(duration)
.attr("height", height)
.attr("viewBox", [0, left.x - marginTop, width, height])
.tween("resize", window.ResizeObserver ? null : () => () => svg.dispatch("toggle"));
// Update the nodes…
const node = gNode.selectAll("g")
.data(nodes, d => d.id);
// Enter any new nodes at the parent's previous position.
const nodeEnter = node.enter().append("g")
//.attr("transform", d => `translate(${source.y0},${source.x0})`)
.attr("transform", d => `translate(${source.y0},${source.x0})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0)
.attr("id", (d) => {
if(d.data.name){
return d.data.name;
}
})
.attr("class", (d) => {
if(!d.children){
return "tree-node leaf-node";
}
return "tree-node inner-node";
})
.on("mousedown", (event, d) => {
d.children = d.children ? null : d._children;
if(event.which == left_mouse){
NodeDropDownMenu(event, d, () => {
if(update(event, d)){
// TODO event does not need to be called on collapse only un-collapse
let descendants = d.descendants(); // TODO the d3 leaves may be too slow, recurseTree better
let uncollapsed_descendants_length = 1;
// The length of the uncollapsed descendants is greater than one on uncollapse
if(descendants.length > uncollapsed_descendants_length){
for(const item of descendants){
let name = item.data.name;
if(name !== "" && SelectedNodes.nodes.has(name)){
SelectedNodes.nodes.set(name, $(`#TreeSVG [id='${name}']`)[0]); // TODO query all nodes at once
let [parent, circle, text] = SelectedNodes.getNodeData(SelectedNodes.nodes.get(name));
SelectedNodes.setSelectedColours(text, circle);
}
}
}
}
});
}
});
nodeEnter.append("circle")
.attr("r", d => d._children ? INNER_NODE_SIZE : LEAF_NODE_SIZE) // size 6 for leaf nodes and 4 for inner nodes
.attr("fill", d => d._children ? "#555" : "#999")
.attr("stroke-width", 10);
// Add branch length to all inner nodes
nodeEnter.append("text")
.text((d) => {
if(!d.data.leaf){
return Number((d.data.d).toFixed(DECIMAL_PLACES))
}})
.attr("class", "branch-length")
.style("visibility", () => {
if(!SHOW_BRANCH_LENGTHS){
return "hidden"
}else{
return "visible"
}
})
.attr("position", "relative")
.attr("dx", (d) => {
let val = Number((d.data.d).toFixed(DECIMAL_PLACES)).toString();
return `${-val.length * DISTANCE_LABEL_OFFSET}pt`;
})
.attr("dy", 14)
.attr("font-size", 12);
nodeEnter.append("text")
// dx the 12 corresponds to a safety metric to add some space between nodes, no children, dx is 0 to align leaves to inner nodes
// Below two lines allow for inner nodes to show up
.attr("dx", d => d._children ? 0 : inner_radius - d.distance + 12)
.attr("dy", d => d._children ? -8 : 0)
//.attr("transform", d => d._children ? `translate(${inner_radius + d.distance},${d.y})` : "")
.attr("x", d => d._children ? -10 : 6)
.attr("font-size", 12)
.attr("text-anchor", d => d._children ? "end" : "start")
.text(d => d.data.name)
.clone(true).lower()
.attr("stroke", "white");
// Transition nodes to their new position.
const nodeUpdate = node.merge(nodeEnter).transition(transition)
.attr("transform", d => `translate(${d.distance},${d.x})`) // aligns the text to the nodes
.attr("fill-opacity", 1)
.attr("stroke-opacity", 1);
// Transition exiting nodes to the parent's new position.
const nodeExit = node.exit().transition(transition).remove()
.attr("transform", d => `translate(${source.y},${source.x})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0);
// Update the links…
const link = gLink.selectAll("path")
.data(links, d => d.target.id)
.attr("d", diagonal);
// Enter any new links at the parent's previous position.
const linkEnter = link.enter().append("path")
.attr("d", diagonal);
link.merge(linkEnter).transition(transition)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition(transition).remove()
.attr("d", diagonal);
// Stash the old positions for transition.
root.eachBefore(d => {
d.x0 = d.x;
d.y0 = d.y;
});
return true;
}
// Do the first update to the initial configuration of the tree — where a number of nodes
// are open (arbitrarily selected as the root, plus nodes with 7 letters).
root.x0 = dy / 2;
root.y0 = 0;
root.descendants().forEach((d, i) => {
d.id = i;
d._children = d.children;
});
update(null, root);
return svg.node();
};
const dendrogram_circle = (data) => {
// Made with lots of help from: https://observablehq.com/d/6c52fee38fb28b2f
var ele = document.getElementById("TreeData");
var ele_style = window.getComputedStyle(ele);
const width = parseInt(ele_style.width);
const height = width;
const outerRadius = width / 2;
const innerRadius = outerRadius - 170;
const decimal_places = 4;
const sc_to_radians = Math.PI / 180;
const root = d3.hierarchy(data);
const dx = 20;
const dy = outerRadius;
function linkStep(startAngle, startRadius, endAngle, endRadius) {
const c0 = Math.cos(startAngle = (startAngle - 90) / 180 * Math.PI);
const s0 = Math.sin(startAngle);
const c1 = Math.cos(endAngle = (endAngle - 90) / 180 * Math.PI);
const s1 = Math.sin(endAngle);
return "M" + startRadius * c0 + "," + startRadius * s0
+ (endAngle === startAngle ? "" : "A" + startRadius + "," + startRadius + " 0 0 " + (endAngle > startAngle ? 1 : 0) + " " + startRadius * c1 + "," + startRadius * s1)
+ " L" + endRadius * c1 + "," + endRadius * s1;
}
function setRadius(d, y0, k) {
d.radius = (y0 += d.data.d) * k;
if (d.children) d.children.forEach(d => setRadius(d, y0, k));
}
function linkVariable(d) {
return linkStep(d.source.x, d.source.radius, d.target.x, d.target.radius);
}
function maxLength(d) {
return d.data.d + (d.children ? d3.max(d.children, maxLength) : 0);
}
function linkConstant(d) {
return linkStep(d.source.x, d.source.y, d.target.x, d.target.y);
}
function linkExtensionVariable(d) {
return linkStep(d.target.x, d.target.radius, d.target.x, innerRadius);
}
function linkExtensionConstant(d) {
return linkStep(d.target.x, d.target.y, d.target.x, innerRadius);
}
tree = d3.cluster()
.size([360, innerRadius])
.separation((a, b) => 1);
const svg = d3.create("svg")
.attr("id", "TreeSVG")
.attr("viewBox", [0, 0, width, height])
.attr("font-family", "sans-serif")
.attr("font-size", 10);
const gNode = svg.append("g")
.attr("cursor", "pointer")
.attr("pointer-events", "all")
.attr("transform", `translate(${outerRadius}, ${outerRadius})`);
const gLink = svg.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.8)
.attr("stroke-width", 2.0)
.attr("transform", `translate(${outerRadius}, ${outerRadius})`);
root.data.d = 0
const max_len = innerRadius / maxLength(root)
setRadius(root, root.data.d, max_len);
function translate_points(d){
let x = Math.cos((d.x - 90) * sc_to_radians) * d.radius
let y = Math.sin((d.x - 90) * sc_to_radians) * d.radius;
let output = `rotate(${d.x - 90}) translate(${d.radius},0)`
return output
}
function translate_text(d){
let new_rad = innerRadius - d.radius + 6
if(!d.data.leaf){
new_rad = d.radius
}
let x = Math.cos((d.x - 90) * sc_to_radians) * new_rad;
let y = Math.sin((d.x - 90) * sc_to_radians) * new_rad;
let rot_val = d.x - 90;
if(x < 0){
rot_val = d.x + 90;
}
d.x0 = x;
d.y0 = y;
let output = `translate(${x}, ${y}) rotate(${rot_val})`
return output
}
function update(event, source){
const duration = event?.altKey ? 2500 : 250; // hold the alt key to slow down the transition
const nodes = root.descendants().reverse(); // Might be able to replace with the recurse tree function for speed up
const links = root.links();
tree(root)
svg.selectAll(".extension-node-links").remove();
const linkExtension = svg.append("g")
.attr("class", "extension-node-links")
.attr("fill", "none")
.attr("stroke", "#000")
.attr("stroke-opacity", 0.25)
.attr("stroke-dasharray", "4")
.selectAll("path")
.data(root.links().filter(d => d.target.data.leaf ))
.join("path")
.each(function(d) { d.target.linkExtensionNode = this; })
//.attr("d", linkExtensionConstant); // linkExtension constant can be passed in to align all branches to labels
.attr("d", (d) => linkExtensionVariable(d))
// Added to move points over
.attr("transform", `translate(${outerRadius}, ${outerRadius})`);
let left = root;
let right = root;
root.eachBefore(node => {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
});
ORIGINAL_WIDTH_SVG=width
const transition = svg.transition()
.duration(duration)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.tween("resize", window.ResizeObserver ? null : () => () => svg.dispatch("toggle"));
const node = gNode.selectAll("g")
.data(nodes, d => d.id);
const nodeEnter = node.enter().append("g")
.attr("transform", translate_points)
// Transform statement below can be used to re-orient leaves at the cost of mis-aligning them on collapse
//.attr("transform", d => `rotate(${d.x - 90}) translate(${d.radius},0)${d.x < 180 ? "" : " rotate(180)"}`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0)
.attr("id", (d) => {
if(d.data.name){
return d.data.name;
}
})
.attr("class", (d) => {
if(d.data.leaf){
return "tree-node leaf-node";
}
return "tree-node inner-node";
})
.on("mousedown", (event, d) => {
d.children = d.children ? null : d._children;
if(event.which == left_mouse){
NodeDropDownMenu(event, d, () => {
let updated_p = false;
updated_p = update(event, d);
if(updated_p){
let descendants = d.descendants(); // TODO the d3 leaves may be too slow, recurseTree better
let uncollapsed_descendants_length = 1;
// The length of the uncollapsed descendants is greater than one on uncollapse
if(descendants.length > uncollapsed_descendants_length){
for(const item of descendants){
let name = item.data.name;
if(name !== "" && SelectedNodes.nodes.has(name)){
SelectedNodes.nodes.set(name, $(`#TreeSVG [id='${name}']`)[0]); // TODO query all nodes at once
let [parent, circle, text] = SelectedNodes.getNodeData(SelectedNodes.nodes.get(name));
SelectedNodes.setSelectedColours(text, circle);
}
}
}
}
});
}
});
nodeEnter.append("circle")
.attr("r", d => d.data.leaf ? LEAF_NODE_SIZE : INNER_NODE_SIZE) // size 6 for leaf nodes and 4 for inner nodes
.attr("fill", d => d.data.leaf ? "#999" : "#555")
.attr("stroke-width", 10);
nodeEnter.append("text")
.text((d) => {
if(!d.data.leaf){
return Number((d.data.d).toFixed(DECIMAL_PLACES))
}})
.attr("class", "branch-length")
.style("visibility", () => {
if(!SHOW_BRANCH_LENGTHS){
return "hidden"
}else{
return "visible"
}
})
.attr("position", "relative")
.attr("dx", (d) => {
let val = Number((d.data.d).toFixed(DECIMAL_PLACES)).toString();
return `${-val.length * DISTANCE_LABEL_OFFSET}pt`;
})
.attr("transform", (d) => {
return ""
})
.attr("dy", 14)
.attr("font-size", "12");
nodeEnter.append("text")
.attr("dy", d => d._children ? -8 : 0) // dx being in a different cord system seems to be causing issues...
.attr("dx", (d) => {
let hyp = 0
if(!d._children){
hyp = innerRadius - d.radius + 6;
}else{
hyp = d.data.d - 10;
}
return hyp}) // labels are not bein moved to the correct pos when redrawn
.text(d => d.data.name)
.clone(true).lower()
.attr("font-size", "12")
.attr("stroke-linejoin", "round")
.attr("stroke", "white");
// Getting spontatnous errors in redraw
// get new position
const nodeUpdate = node.merge(nodeEnter)
.transition(transition)
.attr("transform", translate_points) // aligns the text to the nodes
.attr("fill-opacity", 1)
.attr("stroke-opacity", 1);
const nodeExit = node.exit().transition(transition).remove()
.attr("transform", translate_points) // aligns the text to the nodes
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0);
// Update the links…
const link = gLink.selectAll("path")
.data(links, d => d.target.id)
.attr("d", linkVariable);
const linkEnter = link.enter().append("path")
.attr("d", linkVariable);
link.merge(linkEnter).transition(transition)
.attr("d", linkVariable);
// Transition exiting nodes to the parent's new position.
// TODO see if transition can be added it makes the whole flow smoother
link.exit().remove(); // Removing the transition got rid of path errors
// Stash the old positions for transition.
root.eachBefore(d => {
d.x0 = d.x;
d.y0 = d.y;
});
return true;
}
root.x0 = root.x
root.y0 = 0;
root.descendants().forEach((d, i) => {
d.id = i;
d._children = d.children;
});
update(null, root);
return svg.node();
};
const tidytree_chart = (data) => {
// Specify the charts’ dimensions. The height is variable, depending on the layout.
var ele = document.getElementById("TreeData");
var ele_style = window.getComputedStyle(ele);
const width = parseInt(ele_style.width);
//const width = window.innerWidth;
const marginTop = 40;
const marginRight = 10;
const marginBottom = 30;
const marginLeft = 40;
// Rows are separated by dx pixels, columns by dy pixels. These names can be counter-intuitive
// (dx is a height, and dy a width). This because the tree must be viewed with the root at the
// “bottom”, in the data domain. The width of a column is based on the tree’s height.
const root = d3.hierarchy(data);
const dx = 20;
const dy = (width - marginRight - marginLeft) / (1 + root.height);
// Define the tree layout and the shape for links.
tree = d3.tree().nodeSize([dx, dy]);
diagonal = d3.linkHorizontal().x(d => d.y).y(d => d.x);
// Create the SVG container, a layer for the links and a layer for the nodes.
const svg = d3.create("svg")
.attr("id", "TreeSVG")
.attr("width", width + 20) //makes sure all tree nodes are within view
.attr("height", dx)
.attr("style", `width:${width}px; height: auto; font: 10px sans-serif; user-select: none;`)
const gLink = svg.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.8)
.attr("stroke-width", 0.8);
const gNode = svg.append("g")
.attr("cursor", "pointer")
.attr("pointer-events", "all");
function update(event, source) {
const duration = event?.altKey ? 2500 : 250; // hold the alt key to slow down the transition
const nodes = root.descendants().reverse();
const links = root.links();
// Compute the new tree layout.
// Converting tree to cluster may solve our conundrum...
tree(root);
let left = root;
let right = root;
root.eachBefore(node => {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
});
ORIGINAL_WIDTH_SVG=width
const height = right.x - left.x + marginTop + marginBottom;
const transition = svg.transition()
.duration(duration)
.attr("height", height)
.attr("viewBox", [0, left.x - marginTop, width, height])
.tween("resize", window.ResizeObserver ? null : () => () => svg.dispatch("toggle"));
// Update the nodes…
const node = gNode.selectAll("g")
.data(nodes, d => d.id);
// Enter any new nodes at the parent's previous position.
const nodeEnter = node.enter().append("g")
.attr("transform", d => `translate(${source.y0},${source.x0})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0)
.attr("id", (d) => {
if(d.data.name){
return d.data.name;
}
})
.attr("class", (d) => {
if(!d.children){
return "tree-node leaf-node";
}
return "tree-node inner-node";
})
.on("mousedown", (event, d) => {
d.children = d.children ? null : d._children;
if(event.which == left_mouse){
NodeDropDownMenu(event, d, () => {
if(update(event, d)){
let descendants = d.descendants(); // TODO the d3 leaves may be too slow, recurseTree better
let uncollapsed_descendants_length = 1;
// The length of the uncollapsed descendants is greater than one on uncollapse
if(descendants.length > uncollapsed_descendants_length){
for(const item of descendants){
let name = item.data.name;
if(name !== "" && SelectedNodes.nodes.has(name)){
SelectedNodes.nodes.set(name, $(`#TreeSVG [id='${name}']`)[0]); // TODO query all nodes at once
let [parent, circle, text] = SelectedNodes.getNodeData(SelectedNodes.nodes.get(name));
SelectedNodes.setSelectedColours(text, circle);
}
}
}
}
});
}
});
nodeEnter.append("circle")
.attr("r", d => d.data.leaf ? LEAF_NODE_SIZE : INNER_NODE_SIZE)
.attr("fill", d => d.data.leaf ? "#555" : "#999")
.attr("stroke-width", 10);
nodeEnter.append("text") // TODO can do this with if statement and recurse over them all may be a bit slower but more mem friednly
.text((d) => {
if(!d.data.leaf){
return Number((d.data.d).toFixed(DECIMAL_PLACES))
}})
.attr("class", "branch-length")
.style("visibility", () => {
if(!SHOW_BRANCH_LENGTHS){
return "hidden"
}else{
return "visible"
}
})
.attr("position", "relative")
.attr("dx", (d) => {
let val = Number((d.data.d).toFixed(DECIMAL_PLACES)).toString();
return `${-val.length * DISTANCE_LABEL_OFFSET}pt`;
})
.attr("dy", 18)
.attr("font-size", "12");
nodeEnter.append("text")
.attr("dy", d => d._children ? -6 : 0)
.attr("x", d => d._children ? -6 : 6)
.text(d => d.data.name)
.clone(true).lower()
.attr("stroke-linejoin", "round")
.attr("stroke-width", 3)
.attr("stroke", "white")
.attr("font-size", "12");
// Transition nodes to their new position.
const nodeUpdate = node.merge(nodeEnter).transition(transition)
.attr("transform", d => `translate(${d.y},${d.x})`)
.attr("fill-opacity", 1)
.attr("stroke-opacity", 1);
// Transition exiting nodes to the parent's new position.
const nodeExit = node.exit().transition(transition).remove()
.attr("transform", d => `translate(${source.y},${source.x})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0);
// Update the links…
const link = gLink.selectAll("path")
.data(links, d => d.target.id)
// Enter any new links at the parent's previous position.
const linkEnter = link.enter().append("path")
.attr("d", d => {
const o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
link.merge(linkEnter).transition(transition)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition(transition).remove()
.attr("d", d => {
const o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
});
// Stash the old positions for transition.
root.eachBefore(d => {
d.x0 = d.x;
d.y0 = d.y;
});
return true;
}
// Do the first update to the initial configuration of the tree — where a number of nodes
// are open (arbitrarily selected as the root, plus nodes with 7 letters).
root.x0 = dy / 2;
root.y0 = 0;
root.descendants().forEach((d, i) => {
d.id = i;
d._children = d.children;
});
update(null, root);
return svg.node();
}
var TREE_SWITCH = new Map([[1, dendrogram_chart],[2, tidytree_chart], [3, dendrogram_circle]]); // key value pairs map to switch between tree views
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ End of tree definitions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Class for selected nodes
class SelectedNodes {
static nodes = new Map();
static #circle_pos = 1;
static #name_pos = 3;
static #circle_size_selected = LEAF_NODE_SIZE * 1.5;
static #circle_size_default = LEAF_NODE_SIZE;
static #default_color = "#999";
static #clicked_color = "blue";
static #svg_parent = "g";
static selection_id = "#SelectedNodes";
static getDefaultColour(){
return SelectedNodes.#default_color;
}
static getSelectedColour(){
return SelectedNodes.#clicked_color
}
static getCirclePos(){
return SelectedNodes.#circle_pos;
}
static getNamePos(){
return SelectedNodes.#circle_pos;
}
static clearNodes(){
SelectedNodes.nodes.clear();
}
static setSelectedColours(text, circle){
text.style.fontWeight = "bold";
text.style.fill = "black";
if(!circle.dataset.oldfill && circle.style.fill != SelectedNodes.#default_color){
circle.dataset.oldfill = circle.style.fill
}
circle.style.fill = SelectedNodes.#clicked_color;
circle.setAttribute("r", SelectedNodes.#circle_size_selected);
}
static deSelectedColours(text, circle){
text.style.fontWeight = "normal";
text.style.fill = "black";
if(circle.dataset.oldfill){
circle.style.fill = circle.dataset.oldfill;
if(circle.dataset.oldfill === SelectedNodes.#default_color){
delete circle.dataset.oldfill
}
}else{
circle.style.fill = SelectedNodes.#default_color
}
circle.setAttribute("r", SelectedNodes.#circle_size_default);
}
static getNodeData(element){
let child_nodes = element.childNodes;
let circle = child_nodes[SelectedNodes.#circle_pos];
let text = child_nodes[SelectedNodes.#name_pos];
return [element, circle, text]; // element is g tag
}
static addNodes(element) {
/* Function to update the set of nodes, going forward each node should probably contain the element by ID and the html element
This class is also being refactored as it should never get a none leaf-node
param element: a html "g" element to update the colour of
*/
let [parent, circle, text] = SelectedNodes.getNodeData(element.closest(SelectedNodes.#svg_parent));
if(!SelectedNodes.nodes.has(text.textContent)){
SelectedNodes.nodes.set(text.textContent, parent);
SelectedNodes.setSelectedColours(text, circle);
}else if (DEBUG){
console.log(`${text.textContent} already exists in map.`)
}
}
static unselectNode(element){
// Function tied to an on click event removing it from the map, legend and de-colouring it
let elm = element.closest(SelectedNodes.#svg_parent)
let [parent, circle, text] = SelectedNodes.getNodeData(elm);