-
Notifications
You must be signed in to change notification settings - Fork 31
/
empress.js
3569 lines (3347 loc) · 144 KB
/
empress.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
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
define([
"underscore",
"Camera",
"Drawer",
"Colorer",
"VectorOps",
"CanvasEvents",
"BarplotPanel",
"Legend",
"util",
"chroma",
"LayoutsUtil",
"ExportUtil",
"TreeController",
], function (
_,
Camera,
Drawer,
Colorer,
VectorOps,
CanvasEvents,
BarplotPanel,
Legend,
util,
chroma,
LayoutsUtil,
ExportUtil,
TreeController
) {
/**
* @class EmpressTree
*
* @param {BPTree} tree The phylogenetic tree.
* @param {BIOMTable or null} biom The BIOM table used to color the tree.
* If no table / sample metadata was passed
* to Empress (i.e. using qiime empress
* tree-plot), this should be null.
* @param {Array} featureMetadataColumns Columns of the feature metadata.
* Note: The order of this array should match the order of
* the arrays which are the values of tipMetadata and
* intMetadata. If no feature metadata was provided
* when generating an Empress visualization, this
* parameter should be [] (and tipMetadata and
* intMetadata should be {}s).
* @param {Object} tipMetadata Feature metadata for tips in the tree.
* Note: This should map tip names to an array of feature
* metadata values. Each array should have the same
* length as featureMetadataColumns.
* @param {Object} intMetadata Feature metadata for internal nodes in tree.
* Note: Should be formatted analogously to tipMetadata.
* Note that internal node names can be non-unique.
* @param {Canvas} canvas The HTML canvas that the tree will be drawn on.
*/
function Empress(
tree,
biom,
featureMetadataColumns,
tipMetadata,
intMetadata,
canvas
) {
/**
* @type {Camera}
* The camera used to look at the tree
* @private
*/
this._cam = new Camera();
/**
* @type {Drawer}
* used to draw the tree
* @private
*/
// allow canvas to be null to make testing empress easier
if (canvas !== null) {
this._drawer = new Drawer(canvas, this._cam);
this._canvas = canvas;
}
/**
* @type {Array}
* The default color of the tree
*/
this.DEFAULT_COLOR = Colorer.rgbToFloat([64, 64, 64]);
/**
* @type {BPTree}
* The phylogenetic balance parenthesis tree
* @private
*/
this._tree = new TreeController(tree);
/**
* Used to index into _treeData
* @type {Object}
* @private
*/
this._tdToInd = {
// all nodes (non-layout parameters)
color: 0,
isColored: 1,
visible: 2,
// unrooted layout
x2: 3,
y2: 4,
// rectangular layout
xr: 3,
yr: 4,
highestchildyr: 5,
lowestchildyr: 6,
// circular layout
xc0: 3,
yc0: 4,
xc1: 5,
yc1: 6,
angle: 7,
arcx0: 8,
arcy0: 9,
arcstartangle: 10,
arcendangle: 11,
};
/**
* The number of non layout parameters in _treeData.
* @type {Number}
* @private
*/
this._numOfNonLayoutParams = 3;
/**
* @type {Array}
* The metadata associated with the tree branches
* Note: postorder positions are used as indices because internal node
* names are not assumed to be unique.
* @private
*/
this._treeData = new Array(this._tree.size + 1);
// set default color/visible status for each node
// Note: currently empress tree uses 1-based index since the bp-tree
// bp-tree.js is based off of used 1-based index.
for (var i = 1; i <= this._tree.size; i++) {
this._treeData[i] = new Array(this._tdToInd.length);
this._treeData[i].splice(
this._tdToInd.color,
0,
this.DEFAULT_COLOR
);
this._treeData[i].splice(this._tdToInd.isColored, 0, false);
this._treeData[i].splice(this._tdToInd.visible, 0, true);
}
/**
* @type {Legend}
* Legend describing the way the tree is colored.
* @private
*/
this._legend = new Legend(document.getElementById("legend-main"));
/**
* @type {BiomTable}
* BIOM table: includes feature presence information and sample-level
* metadata. Can be null if no table / sample metadata was passed to
* Empress.
* @private
*/
this._biom = biom;
this.isCommunityPlot = !_.isNull(this._biom);
/**
* @type{Array}
* Feature metadata column names.
* @private
*/
this._featureMetadataColumns = featureMetadataColumns;
/**
* @type{Object}
* Feature metadata: keys are tree node names, and values are arrays
* of length equal to this._featureMetadataColumns.length.
* For the sake of simplicity, we split this up into tip and internal
* node feature metadata objects.
* @private
*/
this._tipMetadata = tipMetadata;
this._intMetadata = intMetadata;
/**
* @type{Object}
* As described above, maps layout names to node coordinate suffixes
* in the tree data.
* @private
*/
this._layoutToCoordSuffix = {
Rectangular: "r",
Circular: "c1",
Unrooted: "2",
};
/**
* @type {String}
* The default / current layouts used in the tree visualization.
* @private
*/
this._defaultLayout = "Unrooted";
this._currentLayout = "Unrooted";
/**
* @type {BarplotPanel}
* Manages a collection of BarplotLayers, as well as the state of the
* barplot panel. Also can call Empress.drawBarplots() /
* Empress.undrawBarplots() when needed. Can be null if no feature or
* sample metadata was passed to Empress.
* @private
*/
this._barplotPanel = null;
if (this.isCommunityPlot || this._featureMetadataColumns.length > 0) {
this._barplotPanel = new BarplotPanel(this, this._defaultLayout);
}
/**
* @type {Number}
* The y scaling factor for the rectangular layout. This is used to
* adjust the thickness of barplot bars.
* @private
*/
this._yrscf = null;
/**
* @type {Number}
* For the rectangular layout, this is the rightmost x-coordinate;
* for the circular layout, this is the maximum distance from the
* root of the tree (a.k.a. the maximum radius in polar coordinates).
* For layouts which do not support barplots (e.g. the unrooted
* layout), the value of this is arbitrary. Used for determining the
* "closest-to-the-root" point at which we can start drawing barplots.
* @private
*/
this._maxDisplacement = null;
/**
* @type {Number}
* A multiple of this._maxDisplacement. This is used as the unit for
* barplot lengths.
* @private
*/
this._barplotUnit = null;
/**
* @type{Boolean}
* Indicates whether or not barplots are currently drawn.
* @private
*/
this._barplotsDrawn = false;
/**
* @type{Number}
* The (not-yet-scaled) line width used for drawing "thick" lines.
* Can be passed as input to this.thickenColoredNodes().
*/
this._currentLineWidth = 0;
/**
* @type{Bool}
* Whether or not to draw node circles.
* Values will range between 0 and 2.
* 0 - Show only internal node circles
* 1 - Show all node circles
* 2 - Do not show node circles
* 3 - show nodes with only 1 descendant
*/
this.drawNodeCircles = 3;
/**
* @type{Bool}
* Whether the camera is focused on a selected node.
*/
this.focusOnSelectedNode = true;
/**
* @type{Bool}
* Whether unrepresented tips are ignored when propagating colors.
*/
this.ignoreAbsentTips = true;
/**
* @type{Bool}
* Whether to ignore node lengths during layout or not
*/
this.ignoreLengths = false;
/**
* @type{String}
* Branch length method: one of "normal", "ignore", or "ultrametric"
*/
this.branchMethod = "normal";
/**
* @type{String}
* Leaf sorting method: one of "none", "ascending", or "descending"
*/
this.leafSorting = "descending";
/**
* @type{CanvasEvents}
* Handles user events
*/
// allow canvas to be null to make testing empress easier
if (
canvas !== null &&
document.getElementById("quick-search") !== null
) {
this._events = new CanvasEvents(this, this._drawer, canvas);
}
/**
* @type{Object}
* @private
* Stores the information about the collapsed clades. This object is
* used to determine if a user clicked on a collapsed clade.
*
* Note: <node_key> refers to the key in _treeData
* Format:
* {
* <node_key>: {
* left: <node_key>,
* right: <node_key>,
* deepest: <node_key>,
* length: <Number>,
* color: <Number>
* }
* }
*/
this._collapsedClades = {};
/**
* @type(Set)
* @private
* Clades that should will not be collapse. Currently, clades are only
* cleared from this set when resetTree() is called.
*/
this._dontCollapse = new Set();
/**
* @type{Array}
* @private
*
* Stores the vertex information that is passed to WebGL
*
* Format: [x, y, RGB, ...]
*/
this._collapsedCladeBuffer = [];
/**
* @type{String}
* @private
*
* The method used to collapsed the tree
*/
this._collapseMethod = "normal";
/**
* @type{Array}
* @private
*
* This stores the group membership of a node. -1 means the node doesn't
* belong to a group. This array is used to collapse clades by search
* for clades in this array that share the same group membership.
*/
this._group = new Array(this._tree.size + 1).fill(-1);
}
/**
* Computes the current tree layout and fills _treeData.
*
* Also updates this._maxDisplacement.
*/
Empress.prototype.getLayoutInfo = function () {
var data,
i,
j = 1;
// set up length getter
var branchMethod = this.branchMethod;
var checkLengthsChange = LayoutsUtil.shouldCheckBranchLengthsChanged(
branchMethod
);
var lengthGetter = LayoutsUtil.getLengthMethod(
branchMethod,
this._tree.getTree()
);
// Rectangular
if (this._currentLayout === "Rectangular") {
data = LayoutsUtil.rectangularLayout(
this._tree.getTree(),
4020,
4020,
// since lengths for "ignoreLengths" are set by `lengthGetter`,
// we don't need (and should likely deprecate) the ignoreLengths
// option for the Layout functions since the layout function only
// needs to know lengths in order to layout a tree, it doesn't
// really need encapsulate all of the logic for determining
// what lengths it should lay out.
this.leafSorting,
undefined,
lengthGetter,
checkLengthsChange
);
this._yrscf = data.yScalingFactor;
for (i of this._tree.postorderTraversal((includeRoot = true))) {
// remove old layout information
this._treeData[i].length = this._numOfNonLayoutParams;
// store new layout information
this._treeData[i][this._tdToInd.xr] = data.xCoord[j];
this._treeData[i][this._tdToInd.yr] = data.yCoord[j];
this._treeData[i][this._tdToInd.highestchildyr] =
data.highestChildYr[j];
this._treeData[i][this._tdToInd.lowestchildyr] =
data.lowestChildYr[j];
j += 1;
}
} else if (this._currentLayout === "Circular") {
data = LayoutsUtil.circularLayout(
this._tree.getTree(),
4020,
4020,
this.leafSorting,
undefined,
lengthGetter,
checkLengthsChange
);
for (i of this._tree.postorderTraversal((includeRoot = true))) {
// remove old layout information
this._treeData[i].length = this._numOfNonLayoutParams;
// store new layout information
this._treeData[i][this._tdToInd.xc0] = data.x0[j];
this._treeData[i][this._tdToInd.yc0] = data.y0[j];
this._treeData[i][this._tdToInd.xc1] = data.x1[j];
this._treeData[i][this._tdToInd.yc1] = data.y1[j];
this._treeData[i][this._tdToInd.angle] = data.angle[j];
this._treeData[i][this._tdToInd.arcx0] = data.arcx0[j];
this._treeData[i][this._tdToInd.arcy0] = data.arcy0[j];
this._treeData[i][this._tdToInd.arcstartangle] =
data.arcStartAngle[j];
this._treeData[i][this._tdToInd.arcendangle] =
data.arcEndAngle[j];
j += 1;
}
} else {
data = LayoutsUtil.unrootedLayout(
this._tree.getTree(),
4020,
4020,
undefined,
lengthGetter,
checkLengthsChange
);
for (i of this._tree.postorderTraversal((includeRoot = true))) {
// remove old layout information
this._treeData[i].length = this._numOfNonLayoutParams;
// store new layout information
this._treeData[i][this._tdToInd.x2] = data.xCoord[j];
this._treeData[i][this._tdToInd.y2] = data.yCoord[j];
j += 1;
}
}
this._drawer.loadTreeCoordsBuff(this.getTreeCoords());
this._computeMaxDisplacement();
};
/**
* Initializes WebGL and then draws the tree
*/
Empress.prototype.initialize = function () {
this._drawer.initialize();
this._events.setMouseEvents();
var nodeNames = this._tree.getAllNames();
// Don't include nodes with the name null (i.e. nodes without a
// specified name in the Newick file) in the auto-complete.
nodeNames = nodeNames.filter((n) => n !== null);
this._events.autocomplete(nodeNames);
this.getLayoutInfo();
this.centerLayoutAvgPoint();
};
/**
* Retrieve an attribute from a node.
*
* @param{Number} node Postorder position of node.
* @param{String} attr The attribute to retrieve from the node.
*
* @return The attribute; if attr is not a valid attribute of node, then
* undefined will be returned.
*/
Empress.prototype.getNodeInfo = function (node, attr) {
if (attr === "name") {
return this._tree.name(this._tree.postorderselect(node));
}
return this._treeData[node][this._tdToInd[attr]];
};
/**
* Sets an attribute of a node.
*
* Note: this method does not perfom any kind of validation. It is assumed
* that node, attr and value are all valid.
*
* @param{Integer} node post-order position of node..
* @param{String} attr The attribute to set for the node.
* @param{Object} value The value to set for the given attribute for the
* node.
*/
Empress.prototype.setNodeInfo = function (node, attr, value) {
this._treeData[node][this._tdToInd[attr]] = value;
};
/**
* Draws the tree
*/
Empress.prototype.drawTree = function () {
this._drawer.loadTreeColorBuff(this.getTreeColor());
this._drawer.loadNodeBuff(this.getNodeCoords());
this._drawer.loadCladeBuff(this._collapsedCladeBuffer);
this._drawer.draw();
};
/**
* Exports a SVG image of the active legends.
*
* Currently this just includes the legend used for tree coloring, but
* eventually this'll be expanded to include all the barplot legends as
* well.
*
* @return {String} svg
*/
Empress.prototype.exportLegendSVG = function () {
var legends = [];
// Add the legend used for coloring the tree (if shown).
if (this._legend.isActive()) {
legends.push(this._legend);
}
// Add all the active legends from all the barplot layers.
// NOTE: Since we expect there to be many more barplot legends than
// just the one tree-coloring legend, we could potentially save a tiny
// bit of time by just setting legends to the output of getLegends()
// and then calling unshift() to add this._legend to the start of the
// array. However, I don't think the speed gain would be worth making
// this code much less readable ._.
if (this._barplotsDrawn) {
legends.push(...this._barplotPanel.getLegends());
}
if (legends.length === 0) {
util.toastMsg("No active legends to export.", 5000);
return null;
} else {
return ExportUtil.exportLegendSVG(legends);
}
};
/**
* Retrieves the coordinate info of the tree.
*
* We used to interlace the coordinate information with the color information
* i.e. [x1, y1, red1, green1, blue1, x2, y2, red2, green2, blue2,...]
* This was inefficient because tree coordinates do not change during most
* update operations (such as feature coloring). Thus, we split the
* coordinate information into two seperate buffers. One for tree
* tree coordinates and another for color.
*
* @return {Array}
*/
Empress.prototype.getTreeCoords = function () {
var tree = this._tree;
var coords = [];
var addPoint = function (x, y) {
coords.push(x, y);
};
/* Draw a vertical line, if we're in rectangular layout mode. Note that
* we *don't* draw a horizontal line (with the branch length of the
* root) for the root node, even if it has a nonzero branch length;
* this could be modified in the future if desired. See #141 on GitHub.
*
* (The python code explicitly disallows trees with <= 1 nodes, so
* we're never going to be in the unfortunate situation of having the
* root be the ONLY node in the tree. So this behavior is ok.)
*/
if (this._currentLayout === "Rectangular") {
addPoint(
this.getX(tree.size),
this.getNodeInfo(tree.size, "lowestchildyr")
);
addPoint(
this.getX(tree.size),
this.getNodeInfo(tree.size, "highestchildyr")
);
}
// iterate through the tree in postorder, skip root
for (var node of this._tree.postorderTraversal()) {
// name of current node
// var node = this._treeData[node];
var parent = tree.postorder(
tree.parent(tree.postorderselect(node))
);
// parent = this._treeData[parent];
if (!this.getNodeInfo(node, "visible")) {
continue;
}
if (this._currentLayout === "Rectangular") {
/* Nodes in the rectangular layout can have up to two "parts":
* a horizontal line, and a vertical line at the end of this
* line. These parts are indicated below as AAA... and BBB...,
* respectively. (Child nodes are indicated by CCC...)
*
* BCCCCCCCCCCCC
* B
* AAAAAAAB
* B
* BCCCCCCCCCCCC
*
* All nodes except for the root are drawn with a horizontal
* line, and all nodes except for tips are drawn with a
* vertical line.
*/
// 1. Draw horizontal line (we're already skipping the root)
addPoint(this.getX(parent), this.getY(node));
addPoint(this.getX(node), this.getY(node));
// 2. Draw vertical line, if this is an internal node
if (this.getNodeInfo(node, "lowestchildyr") !== undefined) {
// skip if node is root of collapsed clade
if (this._collapsedClades.hasOwnProperty(node)) continue;
addPoint(
this.getX(node),
this.getNodeInfo(node, "highestchildyr")
);
addPoint(
this.getX(node),
this.getNodeInfo(node, "lowestchildyr")
);
}
} else if (this._currentLayout === "Circular") {
/* Same deal as above, except instead of a "vertical line" this
* time we draw an "arc".
*/
// 1. Draw line protruding from parent (we're already skipping
// the root so this is ok)
//
// Note that position info for this is stored as two sets of
// coordinates: (xc0, yc0) for start point, (xc1, yc1) for end
// point. The *c1 coordinates are explicitly associated with
// the circular layout so we can just use this.getX() /
// this.getY() for these coordinates.
addPoint(
this.getNodeInfo(node, "xc0"),
this.getNodeInfo(node, "yc0")
);
addPoint(this.getX(node), this.getY(node));
// 2. Draw arc, if this is an internal node (note again that
// we're skipping the root)
if (
!this._tree.isleaf(this._tree.postorderselect(node)) &&
!this._collapsedClades.hasOwnProperty(node)
) {
// An arc will be created for all internal nodes.
// arcs are created by sampling up to 60 small lines along
// the arc spanned by rotating the line (arcx0, arcy0)
// arcendangle - arcstartangle radians. This will create an
// arc that starts at each internal node's rightmost child
// and ends on the leftmost child.
var arcDeltaAngle =
this.getNodeInfo(node, "arcendangle") -
this.getNodeInfo(node, "arcstartangle");
var numSamples = this._numSampToApproximate(arcDeltaAngle);
var sampleAngle = arcDeltaAngle / numSamples;
var sX = this.getNodeInfo(node, "arcx0");
var sY = this.getNodeInfo(node, "arcy0");
for (var line = 0; line < numSamples; line++) {
var x =
sX * Math.cos(line * sampleAngle) -
sY * Math.sin(line * sampleAngle);
var y =
sX * Math.sin(line * sampleAngle) +
sY * Math.cos(line * sampleAngle);
addPoint(x, y);
x =
sX * Math.cos((line + 1) * sampleAngle) -
sY * Math.sin((line + 1) * sampleAngle);
y =
sX * Math.sin((line + 1) * sampleAngle) +
sY * Math.cos((line + 1) * sampleAngle);
addPoint(x, y);
}
}
} else {
addPoint(this.getX(parent), this.getY(parent));
addPoint(this.getX(node), this.getY(node));
}
}
return new Float32Array(coords);
};
Empress.prototype.getTreeColor = function () {
var tree = this._tree;
var coords = [];
var color;
var addPoint = function () {
coords.push(color, color);
};
/* Draw a vertical line, if we're in rectangular layout mode. Note that
* we *don't* draw a horizontal line (with the branch length of the
* root) for the root node, even if it has a nonzero branch length;
* this could be modified in the future if desired. See #141 on GitHub.
*
* (The python code explicitly disallows trees with <= 1 nodes, so
* we're never going to be in the unfortunate situation of having the
* root be the ONLY node in the tree. So this behavior is ok.)
*/
if (this._currentLayout === "Rectangular") {
color = this.getNodeInfo(tree.size, "color");
addPoint();
}
// iterate through the tree in postorder, skip root
for (var node of this._tree.postorderTraversal()) {
if (!this.getNodeInfo(node, "visible")) {
continue;
}
// branch color
color = this.getNodeInfo(node, "color");
if (this._currentLayout === "Rectangular") {
/* Nodes in the rectangular layout can have up to two "parts":
* a horizontal line, and a vertical line at the end of this
* line. These parts are indicated below as AAA... and BBB...,
* respectively. (Child nodes are indicated by CCC...)
*
* BCCCCCCCCCCCC
* B
* AAAAAAAB
* B
* BCCCCCCCCCCCC
*
* All nodes except for the root are drawn with a horizontal
* line, and all nodes except for tips are drawn with a
* vertical line.
*/
// 1. Draw horizontal line (we're already skipping the root)
addPoint();
// 2. Draw vertical line, if this is an internal node
if (this.getNodeInfo(node, "lowestchildyr") !== undefined) {
// skip if node is root of collapsed clade
if (this._collapsedClades.hasOwnProperty(node)) continue;
addPoint();
}
} else if (this._currentLayout === "Circular") {
/* Same deal as above, except instead of a "vertical line" this
* time we draw an "arc".
*/
// 1. Draw line protruding from parent (we're already skipping
// the root so this is ok)
//
// Note that position info for this is stored as two sets of
// coordinates: (xc0, yc0) for start point, (xc1, yc1) for end
// point. The *c1 coordinates are explicitly associated with
// the circular layout so we can just use this.getX() /
// this.getY() for these coordinates.
addPoint();
// 2. Draw arc, if this is an internal node (note again that
// we're skipping the root)
if (
!this._tree.isleaf(this._tree.postorderselect(node)) &&
!this._collapsedClades.hasOwnProperty(node)
) {
// An arc will be created for all internal nodes.
// arcs are created by sampling up to 60 small lines along
// the arc spanned by rotating the line (arcx0, arcy0)
// arcendangle - arcstartangle radians. This will create an
// arc that starts at each internal node's rightmost child
// and ends on the leftmost child.
var arcDeltaAngle =
this.getNodeInfo(node, "arcendangle") -
this.getNodeInfo(node, "arcstartangle");
var numSamples = this._numSampToApproximate(arcDeltaAngle);
for (var line = 0; line < numSamples; line++) {
addPoint();
}
}
} else {
// Draw nodes for the unrooted layout.
// coordinate info for parent
addPoint();
}
}
return new Float32Array(coords);
};
/**
* Creates an SVG string to export the current drawing
* Exports a SVG image of the tree.
*
* @return {String} svg
*/
Empress.prototype.exportTreeSVG = function () {
return ExportUtil.exportTreeSVG(this, this._drawer);
};
/**
* Exports a PNG image of the canvas.
*
* This works a bit differently from the SVG exporting functions -- instead
* of returning a string with the SVG, the specified callback will be
* called with the Blob representation of the PNG. See
* ExportUtil.exportTreePNG() for details.
*
* @param {Function} callback Function that will be called with a Blob
* representing the exported PNG image.
*/
Empress.prototype.exportTreePNG = function (callback) {
ExportUtil.exportTreePNG(this, this._canvas, callback);
};
/**
* Retrieves x coordinate of node in the current layout.
*
* @param {Number} node Postorder position of node.
* @return {Number} x coordinate of node.
*/
Empress.prototype.getX = function (node) {
var xname = "x" + this._layoutToCoordSuffix[this._currentLayout];
return this.getNodeInfo(node, xname);
};
/**
* Retrieves y coordinate of node in the current layout.
*
* @param {Number} node Postorder position of node.
* @return {Number} y coordinate of node.
*/
Empress.prototype.getY = function (node) {
var yname = "y" + this._layoutToCoordSuffix[this._currentLayout];
return this.getNodeInfo(node, yname);
};
/**
* Retrieves the node coordinate info (for drawing node circles).
*
* @return {Array} Node coordinate info, formatted like [x, y, RGB float]
* for every node circle to be drawn.
*/
Empress.prototype.getNodeCoords = function () {
var tree = this._tree;
var coords = [];
var scope = this;
var visible = function (node) {
return scope.getNodeInfo(node, "visible");
};
var comp;
if (this.drawNodeCircles === 0) {
// draw internall node circles
comp = function (node) {
return (
visible(node) && !tree.isleaf(tree.postorderselect(node))
);
};
} else if (this.drawNodeCircles === 1) {
// draw all node circles
comp = function (node) {
return visible(node);
};
} else if (this.drawNodeCircles === 2) {
// hide all node circles
comp = function (node) {
return false;
};
} else if (this.drawNodeCircles === 3) {
// draw node with 1 descendant
comp = function (node) {
var treeNode = tree.postorderselect(node);
return (
visible(node) &&
!tree.isleaf(treeNode) &&
tree.fchild(treeNode) === tree.lchild(treeNode)
);
};
} else {
throw new Error("getNodeCoords() drawNodeCircles is out of range");
}
for (var node of this._tree.postorderTraversal((includeRoot = true))) {
if (!comp(node)) {
continue;
}
// In the past, we only drew circles for nodes with an assigned
// name (i.e. where the name of a node was not null). Now, we
// just draw circles for all nodes.
coords.push(
this.getX(node),
this.getY(node),
this.getNodeInfo(node, "color")
);
}
return new Float32Array(coords);
};
/**
* Returns the number of lines/triangles to approximate an arc/wedge given
* the total angle of the arc/wedge.
*
* @param {Number} totalAngle The total angle of the arc/wedge
* @return {Number} The number of lines/triangles to approximate the arc
* or wedge.
*/
Empress.prototype._numSampToApproximate = function (totalAngle) {
var numSamples = Math.floor(60 * Math.abs(totalAngle / Math.PI));
return numSamples >= 2 ? numSamples : 2;
};
/**
* Returns an Object describing circular layout angle information for a
* node.
*
* @param {Number} node Postorder position of a node in the tree.
* @param {Number} halfAngleRange A number equal to (2pi) / (# leaves in
* the tree), used to determine the lower
* and upper angles. This is accepted as a
* parameter rather than computed here so
* that, if this function is called multiple
* times in succession when drawing a
* barplot layer, this value can be computed
* just once for this layer up front.
*
* @return {Object} angleInfo An Object with the following keys:
* -angle
* -lowerAngle
* -upperAngle
* -angleCos
* -angleSin
* -lowerAngleCos
* -lowerAngleSin
* -upperAngleCos
* -upperAngleSin
* This Object can be passed directly into
* this._addCircularBarCoords() as its angleInfo
* parameter.
*
* @throws {Error} If the current layout is not "Circular".
*/
Empress.prototype._getNodeAngleInfo = function (node, halfAngleRange) {
if (this._currentLayout === "Circular") {
var angle = this.getNodeInfo(node, "angle");
var lowerAngle = angle - halfAngleRange;
var upperAngle = angle + halfAngleRange;
var angleCos = Math.cos(angle);
var angleSin = Math.sin(angle);
var lowerAngleCos = Math.cos(lowerAngle);
var lowerAngleSin = Math.sin(lowerAngle);
var upperAngleCos = Math.cos(upperAngle);
var upperAngleSin = Math.sin(upperAngle);
return {
angle: angle,
lowerAngle: lowerAngle,
upperAngle: upperAngle,
angleCos: angleCos,
angleSin: angleSin,
lowerAngleCos: lowerAngleCos,
lowerAngleSin: lowerAngleSin,
upperAngleCos: upperAngleCos,
upperAngleSin: upperAngleSin,
};
} else {
// We need to throw this error, because if we're not in the
// rectangular layout then nodes will not have a meaningful "angle"
// attribute.
throw new Error(
"_getNodeAngleInfo() called when not in circular layout"
);
}
};
/**
* Adds to an array of coordinates / colors the data needed to draw four
* triangles (two rectangles) for a single bar in a circular layout
* barplot.
*
* Since this only draws two rectangles, the resulting barplots look jagged
* for small trees but look smooth enough for at least moderately-sized
* trees.
*
* For a node with an angle pointing at the bottom-left of the screen, the