-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtree.js.html
1510 lines (1297 loc) · 50.5 KB
/
tree.js.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 lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: tree.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: tree.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>"use strict";
/** @module tree */
import uuid from "uuid";
import {max,timeParse} from "d3";
import {maxIndex,minIndex} from "d3-array";
import {dateToDecimal,isInt} from "./utilities";
// import * as BitSetModule from "bitset";
// const BitSet =BitSetModule.__moduleExports;
// for unique node ids
export const Type = {
DISCRETE : Symbol("DISCRETE"),
BOOLEAN : Symbol("BOOLEAN"),
INTEGER : Symbol("INTEGER"),
FLOAT: Symbol("FLOAT"),
PROBABILITIES: Symbol("PROBABILITIES"),
};
export const CollapseStyles = {
TRIANGLE : Symbol("TRIANGLE"),
BRANCH : Symbol("BRANCH"),
};
/**
* The Tree class
*/
export class Tree {
static DEFAULT_SETTINGS() {
return {
lengthsKnown:true,
heightsKnown:false,
}
}
/**
* The constructor takes an object for the root node. The tree structure is
* defined as nested node objects.
*
* @constructor
* @param {object} rootNode - The root node of the tree as an object.
*/
constructor(rootNode = {},settings={}) {
this.settings = {...Tree.DEFAULT_SETTINGS(), ...settings};
this.heightsKnown = this.settings.heightsKnown;
this.lengthsKnown = this.settings.lengthsKnown;
this.root = makeNode.call(this,{...rootNode,...{length:0,level:0}});
// This converts all the json objects to Node instances
setUpNodes.call(this,this.root);
this.annotations = {};
this._nodeList = [...this.preorder()];
this._nodeList.forEach( (node) => {
if (node.label && node.label.startsWith("#")) {
// an id string has been specified in the newick label.
node._id = node.label.substring(1);
}
const newAnnotations ={};
// if(node.label){
// newAnnotations.label=node.label;
// }
// if(node.name){
// newAnnotations.name=node.name
// }
node.annotations = node.annotations?{...newAnnotations,...node.annotations,}:newAnnotations;
this.addAnnotations(node.annotations);
});
this._nodeMap = new Map(this.nodeList.map( (node) => [node.id, node] ));
this._tipMap = new Map(this.externalNodes.map( (tip) => [tip.name, tip] ));
this.nodesUpdated = false;
// a callback function that is called whenever the tree is changed
this.treeUpdateCallback = () => {};
};
/**
* Gets the root node of the Tree
*
* @returns {Object|*}
*/
get rootNode() {
return this.root;
};
/**
* Gets an array containing all the node objects
*
* @returns {*}
*/
get nodes() {
if(this.nodesUpdated){
setUpArraysAndMaps.call(this);
}
return [...this.preorder()];
};
/**
* get array of node list
* @returns {*}
*/
get nodeList(){
if(this.nodesUpdated){
setUpArraysAndMaps.call(this);
}
return this.nodes
}
/**
* Gets an array containing all the external node objects
*
* @returns {*}
*/
get externalNodes() {
if(this.nodesUpdated){
setUpArraysAndMaps.call(this);
}
return this.nodes.filter((node) => !node.children);
};
/**
* Gets an array containing all the internal node objects
*
* @returns {*}
*/
get internalNodes() {
if(this.nodesUpdated){
setUpArraysAndMaps.call(this);
}
return this.nodes.filter((node) => node.children );
};
get nodeMap(){
if(this.nodesUpdated){
setUpArraysAndMaps.call(this);
}
return this._nodeMap ;
}
get tipMap(){
if(this.nodesUpdated){
setUpArraysAndMaps.call(this);
}
return this._tipMap ;
}
/**
* Returns the sibling of a node (i.e., the first other child of the parent)
*
* @param node
* @returns {object}
*/
getSibling(node) {
if (!node.parent) {
return null;
}
return node.parent.children.find((child) => child !== node);
}
/**
* Returns a node from its id stored.
*
* @param id
* @returns {object}
*/
getNode(id) {
return this.nodeMap.get(id);
}
/**
* Returns an external node (tip) from its name.
*
* @param name
* @returns {object}
*/
getExternalNode(name) {
return this.tipMap.get(name);
}
/**
* If heights are not currently known then calculate heights for all nodes
* then return the height of the specified node.
* @param node
* @returns {number}
*/
getHeight(node) {
return node.height;
}
/**
* A generator function that returns the nodes in a pre-order traversal.
*
* @returns {IterableIterator<IterableIterator<*|*>>}
*/
*preorder(startNode=this.root,filter=()=>true) {
const traverse = function *(node,filter) {
if(filter(node)) {
yield node;
if (node.children) {
for (const child of node.children) {
yield* traverse(child, filter);
}
}
}
};
yield* traverse(startNode,filter);
}
/**
* A generator function that returns the nodes in a post-order traversal
*
* @returns {IterableIterator<IterableIterator<*|*>>}
*/
*postorder(startNode=this.root,filter=()=>true) {
const traverse = function *(node,filter) {
if(filter(node)) {
if (node.children) {
for (const child of node.children) {
yield* traverse(child, filter);
}
}
yield node;
}
};
yield* traverse(startNode,filter);
}
/**
* A generator function that returns the nodes in a path to the root
*
* @returns {IterableIterator<IterableIterator<*|*>>}
*/
static* pathToRoot(node) {
while (node) {
yield node;
node = node.parent;
}
}
/**
* An instance method to return a Newick format string for the Tree. Can be called without a parameter to
* start at the root node. Providing another node will generate a subtree. Labels and branch lengths are
* included if available.
*
* @param {object} node - The node of the tree to be written (defaults as the rootNode).
* @returns {string}
*/
toNewick(node = this.rootNode) {
return (node.children ? `(${node.children.map(child => this.toNewick(child)).join(",")})${node.label ? node.label : ""}` : node.name) + (node.length ? `:${node.length}` : "");
};
/**
* Re-roots the tree at the midway point on the branch above the given node.
*
* @param {object} node - The node to be rooted on.
* @param proportion - proportion along the branch to place the root (default 0.5)
*/
reroot(node, proportion = 0.5) {
if (node === this.rootNode) {
// the node is the root - nothing to do
return;
}
const rootLength = this.rootNode.children[0].length + this.rootNode.children[1].length;
if (node.parent !== this.rootNode) {
// the node is not a child of the existing root so the root is actually changing
let node0 = node;
let parent = node.parent;
let lineage = [ ];
// was the node the first child in the parent's children?
const nodeAtTop = parent.children[0] === node;
const rootChild1 = node;
const rootChild2 = parent;
let oldLength = parent.length;
while (parent.parent) {
// remove the node that will becoming the parent from the children
parent._children = parent.children.filter((child) => child !== node0);
if (parent.parent === this.rootNode) {
const sibling = this.getSibling(parent);
parent._children.push(sibling);
sibling._length = rootLength;
} else {
// swap the parent and parent's parent's length around
[parent.parent._length, oldLength] = [oldLength, parent.parent.length];
// add the new child
parent._children.push(parent.parent);
}
lineage = [parent, ...lineage];
node0 = parent;
parent = parent.parent;
}
// Reuse the root node as root...
// Set the order of the children to be the same as for the original parent of the node.
// This makes for a more visually consistent rerooting graphically.
this.rootNode.children = nodeAtTop ? [rootChild1, rootChild2] : [rootChild2, rootChild1];
// connect all the children to their parents
this.internalNodes
.forEach((node) => {
node.children.forEach((child) => {
child._parent = node;
})
});
const l = rootChild1.length * proportion;
rootChild2._length = l;
rootChild1._length = rootChild1.length - l;
} else {
// the root is staying the same, just the position of the root changing
const l = node.length * (1.0 - proportion);
node._length = l;
this.getSibling(node)._length = rootLength - l;
}
this.heightsKnown = false;
this.treeUpdateCallback();
};
/**
* Reverses the order of the children of the given node. If 'recursive=true' then it will
* descend down the subtree reversing all the sub nodes.
*
* @param node
* @param recursive
*/
rotate(node, recursive = false) {
if (node.children) {
if (recursive) {
for (const child of node.children) {
this.rotate(child, recursive);
}
}
node.children.reverse();
}
this.treeUpdateCallback();
};
/**
* Sorts the child branches of each node in order of increasing or decreasing number
* of tips. This operates recursively from the node given.
*
* @param node - the node to start sorting from
* @param {boolean} increasing - sorting in increasing node order or decreasing?
* @returns {number} - the number of tips below this node
*/
orderByNodeDensity(increasing = true, node = this.rootNode) {
const factor = increasing ? 1 : -1;
orderNodes.call(this, node, (nodeA, countA, nodeB, countB) => {
return (countA - countB) * factor;
});
this.treeUpdateCallback();
return this;
}
/**
* Sorts the child branches of each node in order given by the function. This operates
* recursively from the node given.
*
* @param node - the node to start sorting from
* @param {function} ordering - provides a pairwise sorting order.
* Function signature: (nodeA, childCountNodeA, nodeB, childCountNodeB)
* @returns {number} - the number of tips below this node
*/
order(ordering, node = this.rootNode) {
orderNodes.call(this, node, ordering);
this.treeUpdateCallback();
return this;
}
_order(ordering, node = this.rootNode) {
orderNodes.call(this, node, ordering);
return this;
}
/**
* Get the last common ancestor of two nodes.
* @param node1
* @param node2
* @returns {IterableIterator<*>}
*/
lastCommonAncestor(node1, node2) {
const path1 = [...Tree.pathToRoot(node1)];
const path2 = [...Tree.pathToRoot(node2)];
const sharedAncestors = path1.filter(n1=>path2.map(n2=>n2.id).indexOf(n1.id)>-1);
const lastSharedAncestor = sharedAncestors[maxIndex(sharedAncestors,node=>node.level)];
return lastSharedAncestor;
}
/**
* Get the path length between two nodes
* @param node1
* @param node2
* @returns {number}
*/
pathLength(node1, node2) {
let sum = 0;
const mrca = this.lastCommonAncestor(node1,node2);
for(let node of [node1,node2]){
while(node!=mrca){
sum+=node.length;
node=node.parent;
}
}
return sum;
}
/**
* Returns a new tree instance with only the nodes provided and the path to their MRCA. After this traversal, unspecified
* degree two nodes will be removed. The subtree will consist of the root and then the last common ancestor.
* The nodes of the new tree will be copies of the those in the original, but they will share
* ids, annotations, and names.
* @param chosenNodes
* @return {Tree}
*/
subTree(chosenNodes){
const sharedNodes = [...chosenNodes.map(node=>[...Tree.pathToRoot(node)])] // get all the paths to the root
.reduce((acc,curr)=> [...acc,...curr],[]) // unpack the paths
.filter((node,i,all)=> all.filter(x=>x===node).length===chosenNodes.length) // filter to nodes that appear in every path
.reduce((acc,curr)=> { // reduce to the unique set.
if(!acc.includes(curr)){
acc.push(curr)
}
return acc;
},[]);
const mrca = sharedNodes[maxIndex(sharedNodes,n=>n.level)];
// intermediate nodes with show up as
const subtree = new Tree(mrca.toJS());
subtree.externalNodes.forEach(node=>{
if(!chosenNodes.map(n=>n.id).includes(node.id)){
subtree.removeNode(node);
}
});
return subtree;
}
/**
* Gives the distance from the root to a given tip (external node).
* @param tip - the external node
* @returns {number}
*/
rootToTipLength(tip) {
let length = 0.0;
for (const node of Tree.pathToRoot(tip)) {
if (node.length) {
length += node.length;
}
}
return length;
}
/**
* Returns an array of root-to-tip distances for each tip in the tree.
* @returns {*}
*/
rootToTipLengths() {
return this.externalNodes.map((tip) => this.rootToTipLength(tip));
}
/**
* Splits each branch in multiple segments inserting a new degree 2 nodes. If splitLocations is
* null then it splits each in two at the mid-point
* @param splits
*/
splitBranches(splits = null) {
// split each branch into sections, with a node of
// degree two in the middle. This allows annotation
// of part of a branch.
[...this.preorder()]
.filter((node) => node.parent)
.forEach((node) => {
if (splits !== null) {
if (splits[node.id]) {
let splitNode = node;
splits[node.id].forEach(([time, id]) => {
splitNode = this.splitBranch(splitNode, time);
splitNode._id = id;
})
}
} else {
// if no splitLocations are given then split it in the middle.
this.splitBranch(node, 0.5);
}
});
this.nodesUpdated=true;
this.treeUpdateCallback();
}
/**
* Splits a branch in two inserting a new degree 2 node. The splitLocation should be less than
* the orginal branch length.
* @param node
* @param splitLocation - proportion of branch to split at.
*/
splitBranch(node, splitLocation=0.5) {
const oldLength = node.length;
const splitNode = makeNode.call(this,
{
parent: node.parent,
children: [node],
length: oldLength*splitLocation,
annotations: {
insertedNode: true
}
});
if (node.parent) {
node.parent.children[node.parent.children.indexOf(node)] = splitNode;
} else {
// node is the root so make splitNode the root
this.root = splitNode;
}
node.parent = splitNode;
node._length = oldLength-splitNode.length;
this.nodesUpdated=true;
this.heightsKnown=false;
return splitNode;
}
/**
* Deletes a node from the tree. if the node had children the children are linked to the
* node's parent. This could result in a multifurcating tree.
* The root node can not be deleted.
* @param node
*/
removeNode(node){
if(node===this.root){
return;
}
// remove the node from it's parent's children
node.parent._children=node.parent._children.filter(n=>n!==node);
//update child lengths
if(node._children){
node._children.forEach(child=>{
child._length += node.length;
child.parent = node.parent;// This also updates parent's children array;
})
}
// else if(node.parent._children.length===1){
// console.log("removing parent")
// this.removeNode(node.parent); // if it's a tip then remove it's parent which is now degree two;
// }
this.nodesUpdated = true;
return this;
}
/**
* deletes a node and all it's descendents from the tree;
* @param node
* @return {*}
*/
removeClade(node) {
if(node===this.root){
return;
}
for(const descendent of this.postorder(node)){
this.removeNode(descendent)
}
this.nodesUpdated=true;
this.treeUpdateCallback();
return this;
}
/**
* Set one or more annotations for the tips.
*
* See annotateNode for a description of the annotation structure.
*
* @param annotations a dictionary of annotations keyed by tip label
*/
annotateTips(annotations) {
for (let [key, values] of Object.entries(annotations)) {
const tip = this.getExternalNode(key);
if (!tip) {
throw new Error(`tip with label ${key} not found in tree`);
}
this.annotateNode(tip, values);
}
this.treeUpdateCallback();
}
/**
* This is similar to annotateTips but the annotation objects are keyed by node
* keys (Symbols).
*
* @param annotations a dictionary of annotations keyed by node key
*/
annotateNodes(annotations) {
for (let [key, values] of Object.entries(annotations)) {
const node = this.getNode(key);
if (!node) {
throw new Error(`tip with key ${key} not found in tree`);
}
this.annotateNode(node, values);
}
this.treeUpdateCallback();
}
/**
* Adds the given annotations to a particular node object.
*
* The annotations is an object with properties keyed by external node labels each
* of which is an object with key value pairs for the annotations. The
* key value pairs will be added to a property called 'annotations' in the node.
*
* Boolean or Numerical traits are given as a single value.
* Sets of values with probabilities should be given as an object.
* Discrete values should be given as an array (even if containing only one value)
* or an object with booleans to give the full set of possible trait values.
*
* For example:
*
* {
* 'tip_1': {
* 'trait_1' : true,
* 'trait_4' : 3.141592,
* 'trait_2' : [1, 2], // discrete trait
* 'trait_3' : ["London", "Paris", "New York"], // discrete trait
* 'trait_3' : {"London" : true, "Paris" : false, "New York": false], // discrete trait with full set of values
* 'trait_4' : {"London" : 0.75, "Paris" : 0.20, "New York": 0.05} // probability set
* },
* 'tip_2': {...}
* }
*
* The annotation labels, type and possible values are also added to the tree in a property called 'annotations'.
*
* A reconstruction method such as annotateNodesFromTips can then be used to provide reconstructed values
* for internal nodes. Or annotateNodes can provide annotations for any node in the tree.
*
* @param node
* @param annotations a dictionary of annotations keyed by the annotation name.
*/
annotateNode(node, annotations) {
this.addAnnotations(annotations);
// add the annotations to the existing annotations object for the node object
node.annotations = {...(node.annotations === undefined ? {} : node.annotations), ...annotations};
}
/**
* Adds the annotation information to the tree. This stores the type and possible values
* for each annotation seen in the nodes of the tree.
*
* This methods also checks the values are correct and conform to previous annotations
* in type.
*
* @param annotations
*/
addAnnotations(annotations) {
for (let [key, addValues] of Object.entries(annotations)) {
let annotation = this.annotations[key];
if (!annotation) {
annotation = {};
this.annotations[key] = annotation;
}
if (Array.isArray(addValues)) {
// is a set of values
let type;
if(addValues.map(v=>isNaN(v)).reduce((acc,curr)=>acc&&curr,true)) {
type = Type.DISCRETE;
annotation.type = type;
if (!annotation.values) {
annotation.values = new Set();
}
annotation.values.add(...addValues);
}else if(addValues.map(v=>parseFloat(v)).reduce((acc,curr)=>acc&&Number.isInteger(curr),true)){
type =Type.INTEGER;
}else if(addValues.map(v=>parseFloat(v)).reduce((acc,curr)=>acc&&!Number.isInteger(curr),true)){
type = Type.FLOAT;
}
if (annotation.type && annotation.type !== type) {
if ((type === Type.INTEGER && annotation.type === Type.FLOAT) ||
(type === Type.FLOAT && annotation.type === Type.INTEGER)) {
// upgrade to float
type = Type.FLOAT;
annotation.type = Type.FLOAT;
if(annotation.values){
delete annotation.values;
}else{
throw Error(`existing values of the annotation, ${key}, in the tree is discrete.`);
}
}
}
// annotation.values = annotation.values? [...annotation.values, ...addValues]:[...addValues]
} else if (Object.isExtensible(addValues)) {
// is a set of properties with values
let type = null;
let sum = 0.0;
let keys = [];
for (let [key, value] of Object.entries(addValues)) {
if (keys.includes(key)) {
throw Error(`the states of annotation, ${key}, should be unique`);
}
if (typeof value === typeof 1.0) {
// This is a vector of probabilities of different states
type = (type === undefined) ? Type.PROBABILITIES : type;
if (type === Type.DISCRETE) {
throw Error(`the values of annotation, ${key}, should be all boolean or all floats`);
}
sum += value;
if (sum > 1.01) {
throw Error(`the values of annotation, ${key}, should be probabilities of states and add to 1.0`);
}
} else if (typeof value === typeof true) {
type = (type === undefined) ? Type.DISCRETE : type;
if (type === Type.PROBABILITIES) {
throw Error(`the values of annotation, ${key}, should be all boolean or all floats`);
}
} else {
throw Error(`the values of annotation, ${key}, should be all boolean or all floats`);
}
keys.push(key);
}
if (annotation.type && annotation.type !== type) {
throw Error(`existing values of the annotation, ${key}, in the tree is not of the same type`);
}
annotation.type = type;
annotation.values = annotation.values? [...annotation.values, addValues]:[addValues]
} else {
let type = Type.DISCRETE;
if (typeof addValues === typeof true) {
type = Type.BOOLEAN;
} else if (!isNaN(addValues)) {
type = (addValues % 1 === 0 ? Type.INTEGER : Type.FLOAT);
}
if (annotation.type && annotation.type !== type) {
if ((type === Type.INTEGER && annotation.type === Type.FLOAT) ||
(type === Type.FLOAT && annotation.type === Type.INTEGER)) {
// upgrade to float
type = Type.FLOAT;
} else {
throw Error(`existing values of the annotation, ${key}, in the tree is not of the same type`);
}
}
if (type === Type.DISCRETE) {
if (!annotation.values) {
annotation.values = new Set();
}
annotation.values.add(addValues);
}
annotation.type = type;
}
// overwrite the existing annotation property
this.annotations[key] = annotation;
}
}
/**
* Uses parsimony to label internal nodes to reconstruct the internal node states
* for the annotation 'name'.
*
* @param name
* @param acctrans Use acctrans reconstruction if true, deltrans otherwise
* @param node
*/
annotateNodesFromTips(name, acctran = true) {
fitchParsimony(name, this.rootNode);
reconstructInternalStates(name, [], acctran, this.rootNode);
this.treeUpdateCallback();
}
/**
* A class function that subscribes a to be called when the tree updates.
* @param func - function to be called when the tree updates
*/
subscribeCallback(func){
const currentCallback = this.treeUpdateCallback;
this.treeUpdateCallback = () =>{
currentCallback();
func();
}
}
getClades(tipNameMap=null){
return this.nodeList.filter(n=>n.parent).map(node=>node.getClade(tipNameMap));
}
/**
* A class method to create a Tree instance from a Newick format string (potentially with node
* labels and branch lengths). Taxon labels should be quoted (either " or ') if they contain whitespace
* or any of the tree definitition characters '(),:;' - the quotes (and any whitespace immediately within)
* will be removed.
* @param newickString - the Newick format tree as a string
* @param labelName
* @param datePrefix
* @returns {Tree} - an instance of the Tree class
*/
static parseNewick(newickString, options={}) {
options ={...{labelName: "label",datePrefix:undefined,dateFormat:"decimal",tipNameMap:null},...options}
const tokens = newickString.split(/\s*('[^']+'|"[^"]+"|;|\(|\)|,|:|=|\[&|\]|\{|\})\s*/);
let level = 0;
let currentNode = null;
let nodeStack = [];
let labelNext = false;
let lengthNext = false;
let inAnnotation = false;
let annotationKeyNext = true;
let annotationKey;
let isAnnotationARange=false;
for (const token of tokens.filter(token => token.length > 0)) {
// console.log(`Token ${i}: ${token}, level: ${level}`);
if(inAnnotation){
if(token==="="){
annotationKeyNext=false;
}else if(token===","){
if(!isAnnotationARange){
annotationKeyNext=true;
}
}else if (token==="{"){
isAnnotationARange=true;
currentNode.annotations[annotationKey]=[];
}else if (token==="}"){
isAnnotationARange=false
}
else if(token ==="]"){
// close BEAST annotation
inAnnotation = false;
annotationKeyNext = true;
} else{
// must be annotation
// remove any quoting and then trim whitespace
let annotationToken = token;
if (annotationToken.startsWith("\"") || annotationToken.startsWith("'")) {
annotationToken = annotationToken.substr(1);
}
if (annotationToken.endsWith("\"") || annotationToken.endsWith("'")) {
annotationToken = annotationToken.substr(0, annotationToken.length - 1);
}
if(annotationKeyNext) {
annotationKey = annotationToken.replace(".","_");
}else{
if(isAnnotationARange){
currentNode.annotations[annotationKey].push(annotationToken);
}else{
if(isNaN(annotationToken)){
currentNode.annotations[annotationKey]=annotationToken;
}else{
currentNode.annotations[annotationKey] = parseFloat((annotationToken));
}
}
}
}
} else if (token === "(") {
// an internal node
if (labelNext) {
// if labelNext is set then the last bracket has just closed
// so there shouldn't be an open bracket.
throw new Error("expecting a comma");
}
let node = {
level: level,
parent: currentNode,
children: [],
annotations: {}
};
level += 1;
if (currentNode) {
nodeStack.push(currentNode);
}
currentNode = node;
} else if (token === ",") {
// another branch in an internal node
labelNext = false; // labels are optional
if (lengthNext) {
throw new Error("branch length missing");
}
let parent = nodeStack.pop();
parent.children.push(currentNode);
currentNode = parent;
} else if (token === ")") {
// finished an internal node
labelNext = false; // labels are optional
if (lengthNext) {
throw new Error("branch length missing");
}
// the end of an internal node
let parent = nodeStack.pop();
parent.children.push(currentNode);
level -= 1;
currentNode = parent;
labelNext = true;
} else if (token === ":") {
labelNext = false; // labels are optional
lengthNext = true;
} else if (token === ";") {
// end of the tree, check that we are back at level 0
if (level > 0) {
throw new Error("unexpected semi-colon in tree")
}
break;
} else if(token ==="[&") {
inAnnotation=true;
}
else {
// not any specific token so may be a label, a length, or an external node name
if (lengthNext) {
currentNode.length = parseFloat(token);
lengthNext = false;