-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphyleaux.js
1426 lines (1196 loc) · 44.6 KB
/
phyleaux.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
// phyleaux.js (a4)
// Jeremy M. Brown
// A library for phylogenetic illustrations and animations
// *** Requires d3.js ***
// *** jStat.js required for functions involving character histories ***
// ---------------- ** Classes ** ----------------
// Class to store a character history across a tree
class characterHistoryTree {
constructor(tr,model){
this.tr = tr; // Attach states and waiting times to branches of tree
this.model = model;
}
sampleHistory(startState=null){
this.tr.root.states = [];
if (startState != null){
this.tr.root.states.push(startState);
} else {
this.tr.root.states.push(multiDraw(["A","C","G","T"],this.model.bf));
}
for (var i = 0; i < this.tr.root.desc.length; i++){
this.sampleHistoryNode(this.tr.root.desc[i],this.tr.root.states[0]);
}
}
sampleHistoryNode(node,startState){
node.states = [];
node.waitingTimes = [];
node.states.push(startState);
while (sum(node.waitingTimes) < node.brl){
node.waitingTimes.push(this.model.drawWaitingTime(node.states[node.states.length-1]));
if (sum(node.waitingTimes) < node.brl){
node.states.push(this.model.drawNewState(node.states[node.states.length-1]));
}
}
if (node.desc != null){
for (var i = 0; i < node.desc.length; i++){
this.sampleHistoryNode(node.desc[i],node.states[node.states.length-1]);
}
}
}
}
// Class to store the states and waiting times for a single character history
class characterHistory {
constructor(model){
this.model = model;
this.states = [];
this.waitingTimes = [];
}
sampleHistory(brl,startState=null){
this.states = [];
this.waitingTimes = [];
if (startState != null){
this.states = [startState];
} else {
this.states = [multiDraw(["A","C","G","T"],this.model.bf)];
}
while (sum(this.waitingTimes) < brl){
this.waitingTimes.push(this.model.drawWaitingTime(this.states[this.states.length-1]));
if (sum(this.waitingTimes) < brl){
this.states.push(this.model.drawNewState(this.states[this.states.length-1]));
}
}
}
drawHistory(brl,w,h,svg=null,showStates=true,colors=["#ff0000","#3cb371","#ffa500","#0000ff"],id="charHistSVG"){
if (svg === null){
svg = d3.select("body")
.append("svg")
.attr("width",w)
.attr("height",h)
.attr("id",id);
} else {
svg.attr("width",w)
.attr("height",h)
.attr("id",id);
}
var states = this.states;
var waitingTimes = this.waitingTimes;
var model = this.model;
// Can't access the characterHistory object with "this" inside for loop
var currX = 0;
var waitTimeSum = 0;
for (var i = 0; i < states.length; i++){
svg.append("line")
.attr("stroke",colors[model.findStateIndex(states[i])])
.attr("stroke-width",25)
.attr("x1",function(){
if (i === 0){
return 0;
} else {
return currX;
}
})
.attr("x2",function(){
if (i === (states.length-1)){
return w;
} else {
waitTimeSum += waitingTimes[i];
currX = ((waitTimeSum/brl) * w);
return currX;
}
})
.attr("y1",h/2)
.attr("y2",h/2);
if (showStates){
svg.append("text")
.attr("fill","white")
.attr("x",function(){
if (i === (states.length-1)){ // Last state
return currX + ((w-currX)/2);
} else if (i === 0){ // First state
return (((waitingTimes[i]/2)/brl) * w);
} else { // All other states
return currX - (((waitingTimes[i]/2)/brl) * w);
}
})
.attr("y",(h/2)+5)
.attr("text-anchor","middle")
.attr("font-size","14px")
.text(states[i]);
}
}
}
}
// Class for simulating coalescent histories within a single population
class coalescentHistory {
constructor(popSize,nGens,sampleSize){
this.popSize = popSize;
this.nGens = nGens;
this.sampleSize = sampleSize;
this.descMatrix = [];
for (var i = 0; i < nGens; i++){
this.descMatrix.push([]);
for (var j = 0; j < popSize; j++){
this.descMatrix[i].push(new coalescentIndividual(null,j,[],false));
}
}
}
sampleHistory(){
var numSelections = 0;
//if (this.sampleSize < this.popSize){
while (numSelections < this.sampleSize){ // Select individuals from most recent generation
var selectedInd = Math.floor(Math.random() * this.popSize);
if (this.descMatrix[0][selectedInd].selected === false){
this.descMatrix[0][selectedInd].selected = true;
numSelections++;
}
}
for (var g = 1; g < this.nGens; g++){
for (var i = 0; i < this.popSize; i++){
if (this.descMatrix[g-1][i].selected){
var parentIndex = Math.floor(Math.random() * this.popSize);
this.descMatrix[g-1][i].parent = this.descMatrix[g][parentIndex];
this.descMatrix[g][parentIndex].desc.push(this.descMatrix[g-1][i]);
this.descMatrix[g][parentIndex].selected = true;
}
}
}
//}
}
drawSortedHistory(w,h,padding,sectionID){
var coalSVG = d3.select("body") // Create new svg
.select(sectionID)
.append("svg")
.attr("width",w)
.attr("height",h);
for (var g = this.nGens-2; g >= 0; g--){ // Sort so that lines don't cross
var swaps = true;
while (swaps){ // Keep looping when swaps happen, because individuals are reordered
swaps = false;
for (var i = 0; i < (this.popSize-1); i++){
for (var j = i+1; j < this.popSize; j++){
if (this.descMatrix[g][i].selected && this.descMatrix[g][j].selected){
if (((this.descMatrix[g][i].parent.xPos > this.descMatrix[g][j].parent.xPos) &&
(this.descMatrix[g][i].xPos < this.descMatrix[g][j].xPos)) ||
((this.descMatrix[g][i].parent.xPos < this.descMatrix[g][j].parent.xPos) &&
(this.descMatrix[g][i].xPos > this.descMatrix[g][j].xPos))){
var xTemp = this.descMatrix[g][i].xPos;
this.descMatrix[g][i].xPos = this.descMatrix[g][j].xPos;
this.descMatrix[g][j].xPos = xTemp;
this.descMatrix[g][i].swapped = true;
this.descMatrix[g][j].swapped = true;
swaps = true;
}
}
}
}
}
}
for (var gen = 0; gen < this.nGens; gen++){ // Circles
for (var pop = 0; pop < this.popSize; pop++){
var thisInd = this.descMatrix[gen][pop];
if (! thisInd.selected){
coalSVG.append("circle")
.attr("cx",((thisInd.xPos/(this.popSize))*w)+padding+20)
.attr("cy",((gen/this.nGens)*h)+padding)
.attr("r",10)
.attr("fill","blue");
} else if (thisInd.selected){
coalSVG.append("circle")
.attr("cx",((thisInd.xPos/this.popSize)*w)+padding+20)
.attr("cy",((gen/this.nGens)*h)+padding)
.attr("r",10)
.attr("fill","red");
}
}
} // Finish plotting circles for individuals
for (var gen = 0; gen < this.nGens; gen++){ // Lines
for (var pop = 0; pop < this.popSize; pop++){
var thisInd = this.descMatrix[gen][pop];
if (thisInd.selected && gen != (this.nGens-1)){
coalSVG.append("line")
.attr("x1",((thisInd.xPos/this.popSize)*w)+padding+20)
.attr("x2",((thisInd.parent.xPos/this.popSize)*w)+padding+20)
.attr("y1",((gen/this.nGens)*h)+padding)
.attr("y2",(((gen+1)/this.nGens)*h)+padding)
.attr("stroke","red")
.attr("stroke-width",2);
}
}
} // Finish drawing lines of descent
for (var gen = 0; gen < this.nGens; gen++){ // Adds numeric labels for generations
coalSVG.append("text")
.attr("x",10)
.attr("y",((gen/this.nGens)*h)+padding+5)
.attr("text-anchor","middle")
.attr("font-family","Glober")
.attr("font-size","12")
.text(gen+1);
}
var timelineSVG = d3.select("body") // Adding timeline to side of coalescent history
.select(sectionID)
.append("svg")
.attr("width",80)
.attr("height",h);
timelineSVG.append("text")
.attr("x",40)
.attr("y",padding+5)
.attr("text-anchor","middle")
.attr("font-family","Glober")
.attr("font-size","14")
.text("Present");
timelineSVG.append("text")
.attr("x",40)
.attr("y",(((this.nGens-1)/this.nGens)*h)+padding+5)
.attr("text-anchor","middle")
.attr("font-family","Glober")
.attr("font-size","14")
.text("Past");
timelineSVG.append("line")
.attr("x1",40)
.attr("x2",40)
.attr("y1",padding+15)
.attr("y2",(((this.nGens-2)/this.nGens)*h)+padding+5)
.attr("stroke","black")
.attr("stroke-width",1);
timelineSVG.append("line")
.attr("x1",30)
.attr("x2",40)
.attr("y1",(((this.nGens-2.5)/this.nGens)*h)+padding+5)
.attr("y2",(((this.nGens-2)/this.nGens)*h)+padding+5)
.attr("stroke","black")
.attr("stroke-width",1);
timelineSVG.append("line")
.attr("x1",50)
.attr("x2",40)
.attr("y1",(((this.nGens-2.5)/this.nGens)*h)+padding+5)
.attr("y2",(((this.nGens-2)/this.nGens)*h)+padding+5)
.attr("stroke","black")
.attr("stroke-width",1);
}
drawHistory(w,h,padding,sectionID){
var coalSVG = d3.select("body")
.select(sectionID)
.append("svg")
.attr("width",w)
.attr("height",h);
for (var gen = 0; gen < this.nGens; gen++){
for (var pop = 0; pop < this.popSize; pop++){
var thisInd = this.descMatrix[gen][pop];
if (! thisInd.selected){
coalSVG.append("circle")
.attr("cx",((thisInd.xPos/(this.popSize))*w)+padding)
.attr("cy",((gen/this.nGens)*h)+padding)
.attr("r",10)
.attr("fill","blue")
} else if (thisInd.selected){
coalSVG.append("circle")
.attr("cx",((thisInd.xPos/this.popSize)*w)+padding)
.attr("cy",((gen/this.nGens)*h)+padding)
.attr("r",10)
.attr("fill","red");
if (gen != this.nGens-1){
coalSVG.append("line")
.attr("x1",((thisInd.xPos/this.popSize)*w)+padding)
.attr("x2",((thisInd.parent.xPos/this.popSize)*w)+padding)
.attr("y1",((gen/this.nGens)*h)+padding)
.attr("y2",(((gen+1)/this.nGens)*h)+padding)
.attr("stroke","red")
.attr("stroke-width",2);
}
}
}
}
}
}
// Class to represent individuals in coalescent simulations
class coalescentIndividual {
constructor(parent,xPos,desc=[],selected=false){
this.parent = parent;
this.xPos = xPos;
this.desc = desc;
this.selected = selected;
}
}
// Class for a GTR-class model of nucleotide sequence evolution
class Model {
constructor(bf,rates,gammaRates=true,alpha,invSites=false,i,state="A"){
this.bf = bf;
this.rates = rates;
this.alpha = alpha;
this.i = i;
this.r = this.buildRateMatrix();
}
// Function creates the instantaneous rate matrix from the base frequency and relative rate values
buildRateMatrix(){
// Calculate diagonal elements of rate matrix
var Adiag = -1*((rates[0]*bf[1]) + (rates[1]*bf[2]) + (rates[2]*bf[3]));
var Cdiag = -1*((rates[0]*bf[0]) + (rates[3]*bf[2]) + (rates[4]*bf[3]));
var Gdiag = -1*((rates[1]*bf[0]) + (rates[3]*bf[1]) + (rates[5]*bf[3]));
var Tdiag = -1*((rates[2]*bf[0]) + (rates[4]*bf[1]) + (rates[5]*bf[2]));
// Calculate the normalizing factor so that the negative average of the diagonals is 1
var norm = -1 * mean([Adiag,Cdiag,Gdiag,Tdiag]);
// Calculate and return the full matrix as a 2D array (4x4 matrix)
return [[Adiag/norm, (rates[0]*bf[1])/norm, (rates[1]*bf[2])/norm, (rates[2]*bf[3])/norm],
[(rates[0]*bf[0])/norm, Cdiag/norm, (rates[3]*bf[2])/norm, (rates[4]*bf[3])/norm],
[(rates[1]*bf[0])/norm, (rates[3]*bf[1])/norm, Gdiag/norm, (rates[5]*bf[3])/norm],
[(rates[2]*bf[0])/norm, (rates[4]*bf[1])/norm, (rates[5]*bf[2])/norm, Tdiag/norm]];
}
drawNewState(currentState){
var rateVec = this.r[this.findStateIndex(currentState)];
var offDiagSum = 0;
var states = ["A","C","G","T"];
states.splice(states.indexOf(currentState),1);
var probs = [];
for (var i = 0; i < rateVec.length; i++){
if (rateVec[i] > 0){
offDiagSum += rateVec[i];
}
}
for (var j = 0; j < rateVec.length; j++){
if (rateVec[j] > 0){
probs.push(rateVec[j]/offDiagSum);
}
}
return multiDraw(states,probs);
}
drawWaitingTime(currentState){
var stateIndex = this.findStateIndex(currentState);
var time = rexp(-1 * this.r[stateIndex][stateIndex]);
return time;
}
findStateIndex(st){
if (st === "A"){ return 0; }
else if (st === "C"){ return 1; }
else if (st === "G"){ return 2; }
else if (st === "T"){ return 3; }
}
}
// Class for nodes in a phylogenetic tree
class Node {
constructor( nodeStr, hasBrl, parent, name ){
// Terminal Node
if (!nodeStr.includes(")")){
if (!hasBrl){
this.name = nodeStr;
this.desc = null;
this.parent = parent;
this.depth = parent.depth + 1; // Depth = # of nodes from root
} else {
var parsedNodeStr = nodeStr.split(":");
this.name = parsedNodeStr[0];
this.brl = parseFloat(parsedNodeStr[1]);
this.desc = null;
this.parent = parent;
this.depth = parent.depth + 1;
this.rootDist = parent.rootDist + this.brl;
}
}
// Internal Node
else {
this.name = name; // Name the node, if provided
this.parent = parent;
this.desc = []; // Initialize array to hold descendant nodes
// Record branch length and remove from node string
if (hasBrl && name != "root"){
var lastColon = nodeStr.lastIndexOf(":");
this.brl = parseFloat(nodeStr.slice(lastColon+1));
nodeStr = nodeStr.slice(0,lastColon);
} else if (hasBrl && name === "root"){ // No branch length for the root
this.brl = null;
}
if (name === "root"){ // Initiate depth values at root
this.depth = 0;
this.rootDist = 0;
} else {
this.depth = parent.depth + 1;
this.rootDist = parent.rootDist + this.brl;
}
// Remove starting and trailing parentheses
nodeStr = nodeStr.slice(1,nodeStr.length-1);
// Find positions of commas that separate descendants (2 or more)
var commaIndices = findSplitCommas(nodeStr);
// Create descendant nodes
var descStrings = []; // Initialize array -> 1 string per descendant
for (var i = 0; i <= commaIndices.length; i++){
if (i === 0){ // First descendant (need to start at index 0)
descStrings.push(nodeStr.slice(0,commaIndices[i]));
} else { // All other descendants
descStrings.push(nodeStr.slice(commaIndices[i-1]+1,commaIndices[i]));
}
}
// Recursively call Node constructor for each descendant string
for (var j = 0; j < descStrings.length; j++){
// No names for internal nodes right now
this.desc.push(new Node(descStrings[j], hasBrl, this, null));
}
} // ends else
} // ends constructor
}
// Class for an entire phylogenetic tree
class Tree {
constructor( treeStr ){ // Uses Newick string to instantiate a Tree object
// Determining if tree has branch lengths and setting flag
this.hasBrl = false;
if (treeStr.includes(":")){ this.hasBrl = true; }
// Flags used to indicate which x and y coordinates have been set
this.isCladogram = false;
this.isPhylogram = false;
// Remove trailing semi-colon, if present
if (treeStr.endsWith(';')){
treeStr = treeStr.slice(0,treeStr.length-1);
}
// Create tree by passing treeStr to recursive Node constructor
this.root = new Node(treeStr,this.hasBrl,null,"root");
this.root.tree = this;
// Recurses back through tree to calculate number of tips
// - Should move this to be part of Tree construction
this.tipNum = calcTipNum(this.root);
// Recurses back through tree to add numeric labels to nodes
// - Should make this part of Tree construction
labelNodes(this.root,[1,this.tipNum+1]);
}
}
class AnimatedLineOverTree{
// This defines a class for animating a vertical line along a horizontally drawn tree.
// Defining this as a class, rather than a function, in order to be able to have object
// values set interactively by the user.
constructor( tr, w, h, scale=0.9, padding=30, lwd=2, color="orange", moveTime=10000, tipLabels=false ){
this.tr = tr;
this.w = w;
this.h = h;
this.scale = scale;
this.padding = padding;
this.lwd = lwd;
this.color = color;
this.moveTime = moveTime;
drawPhylogram(this.tr,this.w,this.h,"blue",lwd,scale,padding,tipLabels);
if (tr.isCladogram === false && tr.isPhylogram === false){
alert("Tree does not appear to have been drawn.")
}
// Selects existing svg
this.svg = d3.select("body").select("svg");
// Set up "dataset" with x coordinates for all existing lines
// - Probably a way to do this in d3 without this? Avoid selecting all lines?
this.lineX = [];
this.currentLines = document.querySelectorAll("line");
for (var i = 0; i < this.currentLines.length; i++){
this.lineX.push( [ this.currentLines[i].getAttribute("x1"), this.currentLines[i].getAttribute("x2") ] );
}
// Add new line to animate
this.lineX.push([this.tr.root.x + this.padding, this.tr.root.x + this.padding]);
this.yMin = this.padding - (this.padding/2);
this.yMax = (h * this.scale) + (3 * this.padding / 2);
var lineXlen = this.lineX.length;
// Bind x coordinate data to all lines, and draw new line
this.svg.selectAll("line")
.data(this.lineX) // Binds x position to the line
.enter()
.append("line") // Appends initial circle to svg - attributes below
.attr("x1",function(d){
return d[0]; // x position is the bound datum
})
.attr("x2",function(d){
return d[1];
})
.attr("id",function(d,i){
if (i === lineXlen - 1){
return "progressLine";
}
})
.attr("y1",this.yMin)
.attr("y2",this.yMax)
.attr("stroke",this.color)
.attr("stroke-width",this.lwd);
// Find final x-position for line
this.finalX = this.scale * this.w + this.padding;
}
}
class AnimatedLTT{
// Draws an animated lineage-through-time (LTT) plot for a corresponding tree
// Most effective when paired with a visualization along the tree
constructor(tr,w,h,scale=0.9,padding=30,lwd=4,color="orange",plotTime=10000){
this.tr = tr;
this.w = w;
this.h = h;
this.scale = scale;
this.padding = padding;
this.lwd = lwd;
this.color = color;
this.plotTime = plotTime;
this.svg = d3.select("body") // Adds new svg to body
.append("svg")
.attr("width",this.w)
.attr("height",this.h)
.attr("id","LTTsvg");
// Finds the x coordinates of every node in the tree
this.nodeXvals = extractNodeXVals(this.tr.root,[]);
// Removes duplicate x coordinates - most common for tips in an ultrametric tree
// https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array
// Have to use this dummy variable, cleanedXvals, because "this." doesn't work
// inside of filter function.
var cleanedXvals = this.nodeXvals;
cleanedXvals = cleanedXvals.filter(function(item, pos) {
return cleanedXvals.indexOf(item) == pos;
})
this.nodeXvals = cleanedXvals;
// Sorts the x coordinates from left to right
this.nodeXvals = this.nodeXvals.sort(function compare(a,b) { return a - b });
// Counts the number of lineages present immediately to the right of a
// given x coordinate (i.e., the number of lineages that begin at the node(s) with
// that coordinate).
this.lineageCounts = [];
for (var z = 0; z < this.nodeXvals.length; z++){
this.lineageCounts.push(countLineages(this.tr.root,this.nodeXvals[z],0));
}
// Adjusts the lineage count for the final tip node, since there are 0 lineages to
// its right. Makes it the same as the node with the next largest x coordinate.
this.lineageCounts[this.lineageCounts.length - 1] = this.lineageCounts[this.lineageCounts.length - 2];
// Sets up y scale function and axis. Maximum y value is the largest lineage count.
this.yScale = d3.scaleLog()
.base(Math.E)
.domain([1,Math.max(...this.lineageCounts)]) // ... syntax expands array
.range([(this.h * this.scale), this.padding]); // into individual elements.
this.yAxis = d3.axisLeft()
.scale(this.yScale)
.ticks(5)
.tickFormat(d3.format(".2"));
// Sets up x scale function and axis. Ranges from 0 (root) to 1 (final tip node).
this.xScale = d3.scaleLinear()
.domain([0,1])
.range([this.padding, (this.w * this.scale) + this.padding]);
this.xAxis = d3.axisBottom()
.scale(this.xScale)
.ticks(5);
// Adds the x-axis to the svg and translates it to the bottom of the plot
this.svg.append("g")
.attr("class","axis")
.attr("transform","translate(0," + (this.h * this.scale) + ")")
.call(this.xAxis);
// Adds the x-axis label
this.svg.append("text")
.attr("transform","translate(" + w/2 + "," + ((this.h * this.scale)+40) + ")")
.style("text-anchor","middle")
.text("Relative Tree Depth")
// Adds the y-axis to the svg and translates it to the right with padding
this.svg.append("g")
.attr("class","axis")
.attr("transform","translate(" + this.padding + ",0)")
.call(this.yAxis);
// Adds the y-axis label
this.svg.append("text")
.attr("transform","rotate(-90)")
.attr("x",0-this.h/2)
.attr("y",15)
.style("text-anchor","middle")
.text("Number of Lineages (natural log scale)")
// Apparently, x- and y-axes rotate along with text.
// Adds a circle to the y-axis with the initial number of lineages (i.e., those that
// descend from the root).
this.svg.append("circle")
.attr("cx",this.xScale(0))
.attr("cy",this.yScale(this.lineageCounts[0]))
.attr("r",3)
.attr("fill",this.color)
}
}
// ---------- ** Aliases for Probability Functions ** ----------
var rexp = jStat.exponential.sample;
// ---------------- ** Functions ** ----------------
// Function to begin animation of circles down a tree that's been drawn
// Animation begins after click anywhere on svg containing tree.
// Uses recursive calls to moveCirclesCladogram() to accomplish animation
// Scale and padding need to be the same as those used for drawing the tree
function animateCircleDownCladogram(tr,w,h,scale=0.9,padding=30,radius=3,color="black"){
// Selects existing svg
var svg = d3.select("body").select("svg");
// Instantiates nodeset to keep track of nodes with associated shapes down tree
var nodeset = [tr.root];
// Sets up first circle at root
svg.selectAll("circle")
.data(nodeset,key) // Binds nodes to circles - initially just the root
.enter()
.append("circle") // Appends initial circle to svg - attributes below
.attr("cx",function(d){
return (d.x * scale * w) + padding; // d.x and d.y are [0-1]
})
.attr("cy",function(d){
return (d.y * scale * h) + padding;
})
.attr("r",radius)
.attr("fill",color);
// This variable will be used to keep track of x-position for circles as they
// move down the tree.
var currX = 0;
svg.on("click",function(){ // Start animation when click detected anywhere on svg
moveCirclesCladogram(nodeset,svg,currX,tr.tipNum,1500);
});
}
// --------------------------------------------------
// Function to calculate the number of tips in a tree
function calcTipNum(node){
var tipCount = 0;
if (node.desc === null){ // Found tip
tipCount = 1;
} else {
for (var i = 0; i < node.desc.length; i++){ // Internal
tipCount += calcTipNum(node.desc[i]);
}
}
return tipCount;
}
// --------------------------------------------------
// Function to count the number of lineages present immediately to the right of a given
// x coordinate.
// Arguments:
// - node: Initially expects the root node, then recursively moves through tree
// - xVal: The x coordinate for which lineages are being counted
// - count: Counter variable to keep track of number of lineages
function countLineages(node,xVal,count){
if (node.parent === null && node.x === xVal) { // Root
return node.desc.length;
} else if (node.parent != null && node.x > xVal && node.parent.x <= xVal){
count++;
}
if (node.desc != null){
for (var i = 0; i < node.desc.length; i++){
count = countLineages(node.desc[i],xVal,count);
}
}
return count;
}
// --------------------------------------------------
// Utility function to count the number of a particular state (st) in an array (arr)
function countStateInArray(st,arr){
var count = 0;
for (var i = 0; i < arr.length; i++){
if (arr[i] == st){
count++;
}
}
return count;
}
// --------------------------------------------------
// Function to plot a cladogram
// w and h are the width and height of the new svg
// lwd is line width
// tipLabels is bool to specify whether or not tips should be labeled
Tree.prototype.drawCladogram = function(w,h,color="black",lwd=4,scale=0.9,padding=30,tipLabels=false,fSize=6){
var svg = d3.select("body") // Adds svg to body
.append("svg")
.attr("width",w)
.attr("height",h);
// Traverses tree and sets node x and y values on [0-1] scale for plotting
this.setCladogramXY(this.root,0,findMaxNodeDepth(this.root));
// Recursive function to actually draw lines
drawNodeLines(this.root,svg,w,h,color,lwd,scale,padding);
// Adds tip labels, if requested
if (tipLabels){
this.drawTipLabels(this.root,svg,w,h,scale,padding,fSize);
}
}
// --------------------------------------------------
// Function used to draw individual lines on an LTT plot.
// Could be used more generally than just LTTs, though.
function drawLTTLines(x1,x2,y1,y2,svg,xScale,yScale,color="black",lwd=3){
svg.append("line")
.attr("x1",xScale(x1))
.attr("x2",xScale(x2))
.attr("y1",yScale(y1))
.attr("y2",yScale(y2))
.attr("stroke",color)
.attr("stroke-width",lwd)
.attr("stroke-linecap","round")
}
// --------------------------------------------------
// Function to draw square tree on existing svg
// Scale values < 1 keeps total tree size smaller than the svg.
// Padding shifts lines away from svg edges in top-left corner
// w and h are the width and height of the svg, respectively
// lwd is the line width
function drawNodeLines(node,svg,w,h,color,lwd,scale=0.9,padding=30){
if (node.desc != null){ // Operates on internal nodes - lines drawn parent -> desc
for (var i = 0; i < node.desc.length; i++){
svg.append("line") // Vertical lines
.attr("x1",(node.x * w * scale) + padding)
.attr("x2",(node.x * w * scale) + padding)
.attr("y1",(node.y * h * scale) + padding)
.attr("y2",(node.desc[i].y * h * scale) + padding)
.attr("stroke",color)
.attr("stroke-width",lwd);
if (Math.abs(node.x - node.desc[i].x) > 0.001){
svg.append("line") // Horizontal lines
.attr("x1",(node.x * w * scale) + (padding-(lwd/2)))
// Subtracting by lwd/2 for x1 is what keeps line intersections square
.attr("x2",(node.desc[i].x * w * scale) + padding)
.attr("y1",(node.desc[i].y * h * scale) + padding)
.attr("y2",(node.desc[i].y * h * scale) + padding)
.attr("stroke",color)
.attr("stroke-width",lwd);
} else { // Corrects for plotting artifacts with brls < lwd
svg.append("line") // Horizontal lines
.attr("x1",(node.x * w * scale) + (padding-(lwd/2)))
// Subtracting by lwd/2 for x1 is what keeps line intersections square
.attr("x2",(node.x * w * scale) + padding + (lwd/2))
.attr("y1",(node.desc[i].y * h * scale) + padding)
.attr("y2",(node.desc[i].y * h * scale) + padding)
.attr("stroke",color)
.attr("stroke-width",lwd);
}
drawNodeLines(node.desc[i],svg,w,h,color,lwd,scale,padding);
}
}
}
// --------------------------------------------------
// Function to draw square tree on existing svg
// Scale values < 1 keeps total tree size smaller than the svg.
// Padding shifts lines away from svg edges in top-left corner
// w and h are the width and height of the svg, respectively
// lwd is the line width
function drawNodeLinesWithHistory(node,svg,w,h,colors,lwd,scale=0.9,padding=30){
if (node.desc != null){ // Operates on internal nodes - lines drawn parent -> desc
for (var i = 0; i < node.desc.length; i++){
svg.append("line") // Vertical lines
.attr("x1",(node.x * w * scale) + padding)
.attr("x2",(node.x * w * scale) + padding)
.attr("y1",(node.y * h * scale) + padding)
.attr("y2",(node.desc[i].y * h * scale) + padding)
.attr("stroke",colors[findStateIndex(node.states[node.states.length-1])])
.attr("stroke-width",lwd);
var waitTimeSum = 0;
var adj = (node.desc[i].x - node.x)/node.desc[i].brl;
node.desc[i].scaledWaitingTimes = [];
for (var t = 0; t < node.desc[i].waitingTimes.length; t++){
node.desc[i].scaledWaitingTimes.push(node.desc[i].waitingTimes[t] * adj);
}
for (var st = 0; st < node.desc[i].states.length; st++){
if (Math.abs(node.x - node.desc[i].x) > 0.001){
if ((waitTimeSum + node.desc[i].scaledWaitingTimes[st]) < (node.desc[i].x - node.x)){
svg.append("line") // Horizontal lines
.attr("x1",((node.x * w * scale) + (waitTimeSum * w * scale) + (padding-(lwd/2))))
// Subtracting by lwd/2 for x1 is what keeps line intersections square
.attr("x2",((node.x * w * scale) + (waitTimeSum * w * scale) + (node.desc[i].scaledWaitingTimes[st] * w * scale) + padding))
.attr("y1",(node.desc[i].y * h * scale) + padding)
.attr("y2",(node.desc[i].y * h * scale) + padding)
.attr("stroke",colors[findStateIndex(node.desc[i].states[st])])
.attr("stroke-width",lwd);
} else {
svg.append("line") // Horizontal lines
.attr("x1",((node.x * w * scale) + (waitTimeSum * w * scale) + (padding-(lwd/2))))
// Subtracting by lwd/2 for x1 is what keeps line intersections square
.attr("x2",(node.desc[i].x * w * scale) + padding)
.attr("y1",(node.desc[i].y * h * scale) + padding)
.attr("y2",(node.desc[i].y * h * scale) + padding)
.attr("stroke",colors[findStateIndex(node.desc[i].states[st])])
.attr("stroke-width",lwd);
}
} else { // Corrects for plotting artifacts with brls < lwd
svg.append("line") // Horizontal lines
.attr("x1",(node.x * w * scale) + (padding-(lwd/2)))
// Subtracting by lwd/2 for x1 is what keeps line intersections square
.attr("x2",(node.x * w * scale) + padding + (lwd/2))
.attr("y1",(node.desc[i].y * h * scale) + padding)
.attr("y2",(node.desc[i].y * h * scale) + padding)
.attr("stroke",colors[findStateIndex(node.states[node.states.length-1])])
.attr("stroke-width",lwd);
}
waitTimeSum += node.desc[i].scaledWaitingTimes[st];
}
drawNodeLinesWithHistory(node.desc[i],svg,w,h,colors,lwd,scale,padding);
}
}
}
// --------------------------------------------------
// Function to plot a phylogram, if appropriate x and y values available
// w and h are the width and height of the new svg
// lwd is line width
// tipLabels is bool to specify whether or not tips should be labeled
// Make member function of tree?
function drawPhylogram(tr,w,h,color="black",lwd=2,scale=0.9,padding=30,tipLabels=false){
var svg = d3.select("body") // Adds svg to body
.append("svg")
.attr("width",w)
.attr("height",h)
.attr("id","phylosvg");
// Traverses tree and sets node x and y values on [0-1] scale for plotting
setPhylogramXY(tr.root,0,tr.tipNum,findMaxRootDist(tr.root));
// Root
svg.append("line")
.attr("x1",0)
.attr("x2",padding)
.attr("y1",(tr.root.y * scale * h) + padding)
.attr("y2",(tr.root.y * scale * h) + padding)
.attr("stroke",color)
.attr("stroke-width",lwd);
// Recursive function to actually draw lines
drawNodeLines(tr.root,svg,w,h,color,lwd,scale,padding);
// Adds tip labels, if requested
if (tipLabels){
drawTipLabels(tr.root,svg,w,h,scale,padding);
}
}
// --------------------------------------------------
// Function to plot a phylogram, if appropriate x and y values available
// w and h are the width and height of the new svg
// lwd is line width
// tipLabels is bool to specify whether or not tips should be labeled
// Make member function of tree?
function drawPhylogramWithHistory(chHisTr,w,h,colors=["#ff0000","#3cb371","#ffa500","#0000ff"],lwd=4,scale=0.9,padding=30,tipLabels=false){
var svg = d3.select("body") // Adds svg to body
.append("svg")
.attr("width",w)
.attr("height",h)
.attr("id","phylosvg");
// Traverses tree and sets node x and y values on [0-1] scale for plotting
setPhylogramXY(chHisTr.tr.root,0,chHisTr.tr.tipNum,findMaxRootDist(chHisTr.tr.root));
// Root
svg.append("line")
.attr("x1",0)
.attr("x2",padding)
.attr("y1",(chHisTr.tr.root.y * scale * h) + padding)
.attr("y2",(chHisTr.tr.root.y * scale * h) + padding)
.attr("stroke",colors[chHisTr.model.findStateIndex(chHisTr.tr.root.states[0])])
.attr("stroke-width",lwd);
// Recursive function to actually draw lines
drawNodeLinesWithHistory(chHisTr.tr.root,svg,w,h,colors,lwd,scale,padding);
// Adds tip labels, if requested