A Node.js module that parses strings into graphs according to the Newick tree format, and writes graphs as Newick tree strings.
This module minimally requires ECMAScript 2015 (ES6), since it uses Set
objects.
npm install newick-js --save
yarn add newick-js
To import the functions in JavaScript:
const { parse, write } = require("newick-js")
To import the functions in TypeScript:
import { parse, write } from "newick-js"
To import separately (minimizing file size for tree-shaking):
import { parse } from "newick-js/dist/parse"
import { write } from "newick-js/dist/write"
(The type declarations are written in TypeScript.)
A vertex is a plain object with an optional label
field.
interface Vertex {
label?: string
}
An arc is an array which includes, in order:
- a head vertex (the parent),
- a tail vertex (the child), and
- a weight (a number, possibly
NaN
).
type Arc = [Vertex, Vertex, number]
A graph is an array which includes, in order:
- a set of vertices, and
- a set of arcs.
type Graph = [Set<Vertex>, Set<Arc>]
The parse()
function takes a string and yields a parse result, including a graph, a root vertex, and a weight for the root vertex (possibly NaN
).
declare function parse(s: string): ParseResult
interface ParseResult {
graph: Graph
root: Vertex
rootWeight: number
}
The write()
method takes a graph and yields a Newick tree string.
declare function write(graph: Graph, rootWeight?: number): string
(JavaScript or TypeScript, after importing the functions)
const result = parse("(Pongo:15.76,(Gorilla:9.06,(Pan:6.65,Homo:6.65):2.41)Homininae:6.70)Hominidae:4.43;")
console.log(`Root: ${result.root.label}`)
console.log(`Root Weight: ${result.rootWeight}`)
const vertices = result.graph[0]
console.log(`Number of Vertices: ${vertices.size}`)
const arcs = result.graph[1]
console.log(`Number of Arcs: ${arcs.size}`)
console.log(write(result.graph, result.rootWeight))
Output:
> Root: Hominidae
> Root Weight: 4.43
> Number of Vertices: 7
> Number of Arcs: 6
> ((Homo:6.65,Pan:6.65):2.41,Gorilla:9.06)Homininae:6.7,(Pongo:15.76)Hominidae:4.43;
See src/index.spec.ts
for further examples.
define(function (require, exports, module) {
var newick = require("newick-js")
})
yarn test