Table of Contents
- version
- Id
- BranchData
- BranchObject
- DistanceMatrix
- Link
- Branch
- Parameters
- _guid
- id
- length
- depth
- height
- value
- representing
- data
- parent
- children
- addChild
- addParent
- ancestors
- clone
- consolidate
- copy
- count
- descendants
- depthOf
- distanceBetween
- distanceTo
- each
- eachAfter
- eachBefore
- eachChild
- excise
- fixDistances
- fixParenthood
- flip
- getAncestors
- getChild
- getDescendant
- getDescendants
- getLeafs
- getLeaves
- getMRCA
- getRoot
- hasChild
- hasDescendant
- hasLeaf
- invert
- isChildOf
- isConsistent
- isDescendantOf
- isLeaf
- isolate
- isRoot
- leafs
- leaves
- links
- normalize
- path
- remove
- removeIfNoChildren
- replace
- reroot
- rotate
- setLength
- setParent
- simplify
- sort
- sources
- sum
- targets
- toJSON
- toMatrix
- toNewick
- toObject
- toString
- parseJSON
- parseMatrix
- ParseMatrixOptions
- upgma
- parseNewick
version
The SemVer version string of the patristic library
Type: String
Examples
console.log(patristic.version);
Id
A Branch’s identifier. Trees built by parseMatrix without labels use numbers.
| Type: (string | number) |
BranchData
Data a Branch is built from. Its known attributes initialize the Branch’s;
the whole object is kept as the Branch’s data.
nhx
NHX annotations, as read from and written to Newick.
| Type: (Record<string, string> | undefined) |
BranchObject
A serializable representation of a Branch and its descendants.
DistanceMatrix
Patristic distances between leaves, and the ids of the leaves in order.
Link
A link from a parent Branch to one of its children.
Branch
A class for representing Branches in trees. It’s written predominantly for phylogenetic trees (hence the Newick parser, neighbor-joining implementation, etc.), but could conceivably be useful for representing other types of trees as well.
A tree’s data is stored in typed arrays; a Branch is a view onto one entry,
made when it’s first asked for and kept from then on. Its links (parent
and children) can’t disagree: setting either updates both sides.
Parameters
dataObject? An object containing data you wish to assign to this Branch object. In particular, intended to overwrite the default attributes of a Branch, namelyid,parent,length, andchildren.-
children**function (data: BranchData): (Array<Branch>null undefined)?**
_guid
A number unique to this Branch within the loaded library.
Type: number
id
This Branch’s identifier.
Type: Id
Returns Id
length
The length of the edge from this Branch to its parent.
Type: number
Returns number
depth
The number of edges from the root (set by fixDistances).
Type: number
Returns number
height
The greatest number of edges to a leaf below (set by fixDistances).
Type: number
Returns number
value
A value for layouts and sorting (see count, sum and fixDistances).
Type: number
Returns number
representing
How many Branches this one stands for, after excising others into it.
Type: number
Returns number
data
The data this Branch was made from, or an empty object.
Type: BranchData
Returns BranchData
parent
This Branch’s parent, or null for a root. Setting it moves this Branch (with its subtree) to be the last child of the new parent, or detaches it if set to null.
| Type: (Branch | null) |
| Returns **(Branch | null)** |
children
This Branch’s children, as a new array, or undefined for a leaf (as in d3-hierarchy). Changing the array doesn’t change the tree. Assigning an array of Branches makes them the children, in that order; children left out are detached, and assigning null or an empty array makes this Branch a leaf.
| Type: (Array<Branch> | undefined) |
| Returns **(Array<Branch> | undefined)** |
addChild
Adds a new child to this Branch
Parameters
Returns Branch The (possibly new) child Branch
addParent
Adds a new parent to this Branch, inserting it between this Branch and its current parent (if any). This is a bit esoteric and generally not recommended.
Parameters
-
data**(BranchObject)** A Branch object, or the data to attach to one (optional, default {}) siblingsArray An array of Branches to be the children of the new parent Branch (i.e. siblings of this Branch). They are detached from wherever they were in the tree. (optional, default[])
Returns Branch The Branch on which this was called
ancestors
Returns an array of Branches from this Branch to the root. d3-hierarchy compatibility method.
Type: Array
clone
Returns a deep clone of the Branch on which it is called. Note that this does not clone all descendants, rather than providing references to the existing descendant Branches.
Returns Branch A clone of the Branch on which it is called.
consolidate
All descendant Branches with near-zero length are excised
Returns Branch The Branch on which this method was called.
copy
Returns a clone of the Branch on which it is called. Note that this also
clones all descendants, rather than providing references to the existing
descendant Branches. (For a shallow clone, see Branch.clone.
Finally, the cloned Branch will become the root of the cloned tree, having a
parent of null.
d3-hierarchy compatibility method.
Returns Branch A clone of the Branch on which it is called.
count
Sets the value of each Branch to the number of leaves in its subtree (1 for a leaf), as d3-hierarchy’s count does. d3-hierarchy compatibility method.
Returns Branch The Branch on which it was called
descendants
Returns an array pf descendants, starting with this Branch. d3-hierarchy compatibility method.
Type: Array
depthOf
Returns the depth of a given child, relative to the Branch on which it is called.
Parameters
Returns Number The sum of the lengths of all Branches between the Branch on
which it is called and descendant. Throws an error if descendant is not a
descendant of this Branch.
distanceBetween
Computes the patristic distance between descendantA and descendantB.
Parameters
descendantABranch The Branch from which you wish to compute distancedescendantBBranch The Branch to which you wish to compute distance
Returns number The patristic distance between the given descendants.
distanceTo
Computes the patristic distance between cousin and the Branch on which
this method is called.
Parameters
cousinBranch The Branch to which you wish to compute distance
Returns number The patristic distance between cousin and the Branch on
this method is called.
each
Visits each Branch descended from the Branch on which it is called in Breadth First Search order and returns the Branch on which it was called.
Parameters
callbackFunction The function to be run on each Branch
Returns Branch The Branch on which it was called.
eachAfter
Visits each Branch descended from the Branch on which it is called in post-traversal order and returns the Branch on which it was called.
Parameters
callbackFunction Function to run on each Branch
Returns Branch The Branch on which it was called
eachBefore
Visits each Branch descended from the Branch on which it is called in pre-traversal order and returns the Branch on which it was called.
Parameters
callbackFunction [description]
Returns [type] [description]
eachChild
Runs a function on each child of the Branch on which it is called.
Parameters
callbackFunction The function to run on each child.
Returns Branch The Branch on which it was called.
excise
Excises the Branch on which it is called and updates its parent and children. Excising a root Branch with a single child makes that child the new root.
Returns Branch The parent of the excised Branch, or the new root if the excised Branch was the root.
fixDistances
Sets the distance values (height and depth) for each Branch, and sets each Branch’s value to the number of Branches in its subtree (see Branch.count).
Returns Branch The Branch on which it is called.
fixParenthood
Repairs incorrect links by recurively confirming that children reference their parents, and correcting those references if they do not.
If you need to call this, something has messed up the state of your tree and you should be concerned about that. Just FYI. ¯\(ツ)/¯
Parameters
nonrecursiveBoolean Should this just fix the children of the Branch on which it is called, or all descendants?
Returns Branch The Branch on which it was called.
flip
Reverses the order of (all of) the descendants of the Branch.
Returns Branch The Branch on which this was called.
getAncestors
Returns an Array of all the ancestors of the Branch on which it is called. Note that this does not include itself. For all ancestors and itself, see Branch.ancestors
Parameters
includeSelfBoolean Should the Branch on which this is called be included in the results?
Returns Array Every Ancestor of the Branch on which it was called.
getChild
Given an childID, returns the child with that id (or undefined if no such
child is present).
Parameters
childID(String | Number) the ID of the child to return. (Trees built by parseMatrix without labels have numeric ids.)
Returns (Branch | undefined) The desired child Branch, or undefined if the
child doesn’t exist.
getDescendant
Given an id string, returns the descendant Branch with that ID, or
undefined if it doesn’t exist.
Parameters
idString The id string of the Branch to find
Returns (Branch | undefined) The descendant Branch, or undefined if it
doesn’t exist
getDescendants
Returns an array of all Branches which are descendants of this Branch
Parameters
includeSelfBoolean? Is this not the Branch on which the user called the function? This is used internally and should be ignored.
Returns Array An array of all Branches descended from this Branch
getLeafs
Returns an array of all leaves which are descendants of this Branch. Alias of getLeaves for people whose strong suit isn’t spelling.
Returns Array An array of all leaves descended from this Branch
getLeaves
Returns an array of all leaves which are descendants of this Branch See also: getLeafs
Returns Array An array of all leaves descended from this Branch
getMRCA
Traverses the tree upward until it finds the Most Recent Common Ancestor
(i.e. the first Branch for which both the Branch on which it was called and
cousin are descendants). A Branch counts as its own descendant here, so
the MRCA of a Branch and one of its ancestors is that ancestor.
Parameters
cousinBranch
Returns Branch The Most Recent Common Ancestor of both the Branch on
which it was called and the cousin.
getRoot
Traverses the tree upward until it finds the root Branch, and returns the root.
Returns Branch The root Branch of the tree
hasChild
Determines if a given Branch (or ID) is a child of this Branch
Parameters
Returns Boolean
hasDescendant
Checks to see if descendant is a descendant of the Branch on which this
method is called.
Parameters
Returns Boolean True if descendant is descended from the Branch from
which this is called, otherwise false.
hasLeaf
Checks to see if a Branch has a descendant leaf.
Parameters
Returns Boolean True if leaf is both a leaf and a descendant of the Branch on which this method is called, False otherwise.
invert
Swaps the branch on which it is called with its parent. This method is probably only useful as an internal component of Branch.reroot.
Returns Branch The Branch object on which it was called.
isChildOf
Returns whether the Branch on which it is called is a child of a given parent (or parent ID).
Parameters
Returns Boolean True is parent is the parent of this Branch, false
otherwise.
isConsistent
Tests whether this and each descendant Branch holds correct links to both its parent and its children.
Returns Boolean True if consistent, otherwise false
isDescendantOf
Returns whether a given Branch is an ancestor of the Branch on which this method is called.
Parameters
ancestorBranch The Branch to check for ancestorhood
Returns Boolean If this Branch is descended from ancestor
isLeaf
Returns a boolean indicating if this Branch is a leaf (i.e. has no children).
Returns Boolean True is this Branch is a leaf, otherwise false.
isolate
Returns a boolean indicating whether or not this Branch is olate.
…Just kidding!
Isolates a Branch and its subtree (i.e. removes everything above it, making it the root Branch). Similar to Branch.remove, only it returns the Branch on which it is called.
Returns Branch The Branch object on which it was called.
isRoot
Returns a boolean indicating if this Branch is the root of a tree (i.e. has no parents).
Returns Boolean True if this Branch is the root, otherwise false.
leafs
Returns the array of leaf nodes in traversal order; leaves are nodes with no children. Alias of Branch.getLeaves `cuz spelling is hard.
Type: Array
leaves
Returns the array of leaf nodes in traversal order; leaves are nodes with no children. Alias of Branch.getLeaves. d3-hierarchy compatibility method.
Type: Array
links
Returns an Array of links, which are plain javascript objects containing a
source attribute (which is a reference to the parent Branch) and a target
attribute (which is a reference to the child Branch).
d3-hierarchy compatibility method
Returns Array An array of plain Javascript objects
normalize
Normalizes this and all descendant Branches value attributes to between
newmin and newmax. Note that normalize can function as its own inverse
when passed an original range. For example:
Parameters
Examples
tree.normalize().normalize(1, tree.getDescendants().length + 1);
Returns Branch The Branch on which it was called.
path
Gets the path from this Branch to target. If this Branch and target are
the same, returns an array containing only the Branch on which it is called.
Parameters
targetBranch A Branch object
Returns Array An ordered Array of Branches following the path between this
Branch and target
remove
Removes a Branch and its subtree from the tree. Similar to Branch.isolate, only it returns the root Branch of the tree from which this Branch is removed.
Parameters
pruneAncestorsBoolean If true, removes ancestors with no remaining children as well
Returns Branch The root of the remaining tree.
removeIfNoChildren
Removes the branch if it has no children. Then recursively removes all ancestors with no children.
Parameters
nonrecursiveBoolean If true, does not remove ancestors with no children
Returns Branch The root of the modified tree.
replace
Removes a Branch and its subtree from the tree, and replaces it. The replacement is detached from wherever it was, and the replaced Branch becomes the root of its own tree.
Parameters
replacementBranch The branch to replace the branch on which the method is called.
Returns Branch The root of the modified tree.
reroot
Reroots a tree on this Branch. Use with caution, this returns the new root, which should typically supplant the existing root Branch object, but does not replace that root automatically.
Examples
tree = tree.children[0].children[0].reroot();
Returns Branch The new root Branch, which is the Branch on which this was called
rotate
Reverses the order of the children of the branch on which it is called.
Parameters
recursiveboolean?
Returns Branch The Branch on which this was called.
setLength
Set the length of a Branch
Parameters
lengthnumber The new length to assign to the Branch
Returns Branch The Branch object on which this was called
setParent
Sets the parent of the Branch on which it is called.
Parameters
parentBranch The Branch to set as parent
Returns Branch The Branch on which this method was called.
simplify
Collapses each descendant Branch with exactly one child into a single continuous branch. The Branch on which it is called is left in place.
Returns Branch The Branch on which this method was called.
sort
Sorts the Tree from the branch on which it is called downward.
Parameters
comparatorFunction? A Function taking two Branches and returning a numberic value. For details, see MDN Array.sort
Returns Branch The Branch on which it was called
sources
Determines whether this Branch is likelier to be a source of cousin, or
if cousin is a source of this Branch.
Parameters
cousinBranch The other Branch to test
Returns Boolean True if this might be the source of cousin, otherwise false.
sum
Computes the value of each Branch according to some valuator function
Parameters
valueFunction A Function taking a Branch and returning a (numeric?) value.
Returns Branch The Branch on which it was called.
targets
Determines whether this Branch is likelier to be a target of cousin, or
if cousin is a target of this Branch.
Parameters
cousinBranch The other Branch to test
Returns Boolean True if this might be the target of cousin, otherwise false.
toJSON
toJSON is an alias for toObject, enabling the safe use of
JSON.stringify on Branch objects (in spite of their circular references).
Type: Function
Returns Object A serializable Object
toMatrix
Computes a matrix of all patristic distances between all leaves which are descendants of the Branch on which this method is called.
Returns Object An Object containing a matrix (an Array of Arrays) and
Array of ids corresponding to the rows (and columns) of the matrix.
toNewick
Returns the Newick representation of this Branch and its descendants.
Labels containing whitespace, punctuation, brackets or quotes are written
in single quotes, with any single quotes in them doubled. A Branch’s
data.nhx annotations, if any, are written after its length as an NHX
comment.
Parameters
nonterminusBoolean Is this not the terminus of the Newick Tree? This should be falsy when called by a user (i.e. you). It’s used internally to decide whether or not in include a semicolon in the returned string. (optional, defaultfalsy)
Returns String The Newick representation of the Branch.
toObject
Returns a simple Javascript object version of this Branch and its
descendants. This is useful in cases where you want to serialize the tree
(e.g. JSON.stringify(tree)) but can’t because the tree contains circular
references (for simplicity, elegance, and performance reasons, each Branch
tracks both its children and its parent).
Returns Object A serializable bare Javascript Object representing this Branch and its descendants.
toString
Returns a valid JSON-string version of this Branch and its descendants.
Parameters
replacerFunction A replacer function to pass toJSON.stringify.-
width**(stringnumber)?** space(Number | String) A string or number of spaces to use for indenting the output. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Parameters for additional details.
Returns Object A valid JSON string representing this Branch and its descendants.
parseJSON
Parses a hierarchical JSON string (or Object) as a Branch object.
Parameters
json(String | Object) A json string (or Javascript Object) representing hierarchical data.idLabelString The key used in the objects ofjsonto indicate their identifiers. (optional, default"id")lengthLabelString The key used in the objects ofjsonto indicate their length. (optional, default'length')childrenLabelString The key used in the objects ofjsonto indicate their children. (optional, default`children`)
Returns Branch The Branch representing the root of the hierarchy
represented by json.
parseMatrix
Builds a tree from a matrix of distances and returns its root Branch.
By default this is neighbor joining, with RapidNJ’s search, adapted from
Maciej Korzepa’s neighbor-joining,
which is released for modification under the MIT License.
The method option chooses another algorithm:
"bionj": BIONJ (Gascuel 1997), which joins the same way but computes the new node’s distances to reduce their variance, and is usually more accurate than neighbor joining when distances are noisy."upgma": UPGMA, which builds a rooted tree with every leaf the same distance from the root (assuming a molecular clock).
Neighbor joining and BIONJ trees are unrooted at heart; they’re rooted where the last two nodes are joined.
Parameters
matrixArray An array ofnarrays of lengthn. Only the lower triangle is read, and the diagonal is taken to be zero.labelsArray An array ofnstrings, each corresponding to the values inmatrix.optionsObject? See ParseMatrixOptions:methodpicks the algorithm, and{ float32: true }stores distances in half the memory, at single precision.
Returns Branch A Branch object representing the root Branch of the tree
inferred from matrix.
ParseMatrixOptions
Options for parseMatrix.
method
The algorithm: neighbor joining ("nj", the default), BIONJ
("bionj") or UPGMA ("upgma").
Type: ("nj" |
"bionj" |
"upgma" |
undefined) |
float32
Store distances as 32-bit floats, which halves the memory they take (the matrix and each row’s sorted copy) at the cost of precision: distances keep about 7 significant digits. Arithmetic is still done in 64 bits. Defaults to false.
| Type: (boolean | undefined) |
upgma
Builds a tree by UPGMA: repeatedly merges the two closest clusters into a node at half their distance (so every leaf ends up equally far from the root), and takes the merged cluster’s distance to each other cluster to be the size-weighted mean of its parts’. Each row remembers its nearest neighbor, so finding the closest pair is O(n) per merge.
Parameters
Returns Branch
parseNewick
Parses a Newick String and returns a Branch object representing the root of the output Tree.
Labels may be quoted with single or double quotes, which lets them contain
spaces and punctuation; a quote is escaped by doubling it ('O''Brien').
Unquoted labels keep spaces inside them (and underscores as they are), and
whitespace around punctuation is ignored. Comments in square brackets are
skipped, except NHX annotations ([&&NHX:key=value:...]), which are read
into the data.nhx of the Branch they follow (and written back by
toNewick). Parsing stops at the first ;, which may be left out.
Parameters
newickstring A Newick String
- Throws SyntaxError If the parentheses don’t balance, a quoted label or comment isn’t closed, or a comma appears outside parentheses.
Returns Branch A Branch representing the root of the output tree