phylotree 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +49 -5
  2. package/bin/phylotree-neighbor-join.js +4 -5
  3. package/bin/root-to-tip.js +1 -1
  4. package/bin/tip-date-extractor.js +26 -18
  5. package/dist/phylotree-menus.css +93 -0
  6. package/dist/phylotree.d.ts +509 -241
  7. package/dist/phylotree.js +5023 -1515
  8. package/dist/phylotree.min.js +1 -1
  9. package/package.json +25 -27
  10. package/src/branches.js +58 -34
  11. package/src/clustering/cluster-picker.js +18 -2
  12. package/src/clustering/phylopart.js +14 -6
  13. package/src/export.js +1 -1
  14. package/src/extract-dates.js +3 -3
  15. package/src/formats/beast.js +5 -1
  16. package/src/formats/newick.js +43 -7
  17. package/src/formats/nexml.js +87 -30
  18. package/src/formats/nexus.js +112 -32
  19. package/src/formats/phyloxml.js +74 -15
  20. package/src/formats/registry.js +5 -1
  21. package/src/index.js +1 -0
  22. package/src/main.js +76 -25
  23. package/src/metrics/center-of-tree.js +4 -2
  24. package/src/metrics/compute-midpoint.js +7 -1
  25. package/src/metrics/pairwise-distances.js +4 -2
  26. package/src/metrics/root-to-tip.js +43 -10
  27. package/src/metrics/sackins.js +7 -1
  28. package/src/msa-parsers/fasta.js +9 -12
  29. package/src/neighbor-join.js +107 -75
  30. package/src/nodes.js +43 -31
  31. package/src/render/clades.js +16 -4
  32. package/src/render/draw.js +128 -86
  33. package/src/render/edges.js +17 -8
  34. package/src/render/events.js +2 -3
  35. package/src/render/menus.js +110 -10
  36. package/src/render/nodes.js +42 -16
  37. package/src/render/options.js +3 -1
  38. package/src/render/selection-sets.js +30 -14
  39. package/src/render/unrooted.js +90 -12
  40. package/src/rooting.js +12 -3
  41. package/src/traversal.js +4 -3
@@ -1,116 +1,247 @@
1
1
  // Type definitions for phylotree
2
2
  // Project: https://github.com/veg/phylotree.js
3
+ //
4
+ // Every declaration here mirrors code in src/. Run `yarn typecheck` after
5
+ // changing this file; it compiles test/types/usage.ts against it.
3
6
 
4
- import { HierarchyNode, HierarchyLink } from 'd3-hierarchy';
7
+ import type * as d3 from 'd3';
5
8
 
6
9
  /**
7
- * Node data stored in the phylogenetic tree
10
+ * Node data stored in the phylogenetic tree (the `data` field of each node)
8
11
  */
9
12
  export interface PhylotreeNodeData {
10
13
  name: string;
14
+ /** Branch length as parsed from the input, as a string */
11
15
  attribute?: string;
16
+ /** Annotation parsed from `{...}` (or `[...]`) after the node name */
12
17
  annotation?: string;
18
+ /** Internal node label, kept when bootstrap values are parsed */
19
+ bootstrap_values?: string;
13
20
  [key: string]: any;
14
21
  }
15
22
 
16
23
  /**
17
- * A node in the phylogenetic tree (D3 hierarchy node with phylotree data)
24
+ * A node in the phylogenetic tree (D3 hierarchy node with phylotree state)
18
25
  */
19
- export type PhylotreeNode = HierarchyNode<PhylotreeNodeData> & {
26
+ export interface PhylotreeNode extends d3.HierarchyNode<PhylotreeNodeData> {
27
+ /** Default selection attribute; see `TreeRender.selectionLabel` */
20
28
  selected?: boolean;
21
29
  tag?: boolean;
22
30
  collapsed?: boolean;
23
31
  hidden?: boolean;
24
32
  notshown?: boolean;
33
+ /** Name of the selection set this node belongs to (multi-set mode) */
34
+ _selectionSet?: string;
25
35
  screen_x?: number;
26
36
  screen_y?: number;
27
37
  text_angle?: number;
28
38
  text_align?: string;
29
39
  angle?: number;
30
40
  radius?: number;
31
- };
41
+ }
32
42
 
33
43
  /**
34
44
  * A link/branch in the phylogenetic tree
35
45
  */
36
- export type PhylotreeLink = HierarchyLink<PhylotreeNodeData> & {
46
+ export interface PhylotreeLink extends d3.HierarchyLink<PhylotreeNodeData> {
37
47
  source: PhylotreeNode;
38
48
  target: PhylotreeNode;
39
- };
49
+ /** Default selection attribute, mirrored from `target` */
50
+ selected?: boolean;
51
+ tag?: boolean;
52
+ }
53
+
54
+ /**
55
+ * Node styler: called with a selection of the node's `<g>` element.
56
+ */
57
+ export type NodeStyler = (
58
+ element: d3.Selection<SVGGElement, PhylotreeNode, null, undefined>,
59
+ node: PhylotreeNode
60
+ ) => void;
61
+
62
+ /**
63
+ * Edge styler: called with a selection of the branch's `<path>` element.
64
+ * `transition` is passed while the tree is being drawn, not on refresh.
65
+ */
66
+ export type EdgeStyler = (
67
+ element: d3.Selection<SVGPathElement, PhylotreeLink, null, undefined>,
68
+ link: PhylotreeLink,
69
+ transition?: boolean
70
+ ) => void;
71
+
72
+ /** Names accepted by `modifySelection` when `restricted-selectable` is on */
73
+ export type PredefinedSelector = 'all' | 'none' | 'all-leaf-nodes' | 'all-internal-nodes';
74
+
75
+ /** Keys of the CSS class map (see `css-classes` and `TreeRender.css`) */
76
+ export type CssClassKey =
77
+ | 'tree-container'
78
+ | 'tree-scale-bar'
79
+ | 'node'
80
+ | 'internal-node'
81
+ | 'tagged-node'
82
+ | 'selected-node'
83
+ | 'collapsed-node'
84
+ | 'root-node'
85
+ | 'branch'
86
+ | 'selected-branch'
87
+ | 'tagged-branch'
88
+ | 'tree-selection-brush'
89
+ | 'branch-tracer'
90
+ | 'clade'
91
+ | 'node_text';
92
+
93
+ /** A named, coloured selection set for `selection-mode: "multi-set"` */
94
+ export interface SelectionSetDefinition {
95
+ name: string;
96
+ color: string;
97
+ }
40
98
 
41
99
  /**
42
- * Options for rendering a phylogenetic tree
100
+ * Options for rendering a phylogenetic tree (defaults in src/render/draw.js)
43
101
  */
44
102
  export interface RenderOptions {
45
103
  /** CSS selector or DOM element for the container */
46
104
  container?: string | HTMLElement;
47
- /** Width of the SVG in pixels */
105
+ /** Width of the SVG in pixels (default 800) */
48
106
  width?: number;
49
- /** Height of the SVG in pixels */
107
+ /** Height of the SVG in pixels (default 600) */
50
108
  height?: number;
51
- /** Enable zoom/pan behavior */
52
- zoom?: boolean;
53
- /** Tree layout: "left-to-right" or "right-to-left" */
109
+ /** Tree layout direction */
54
110
  layout?: 'left-to-right' | 'right-to-left';
55
- /** Use radial/circular layout */
56
- 'is-radial'?: boolean;
57
- /** Use unrooted (equal-angle) layout */
58
- 'is-unrooted'?: boolean;
59
- /** Align tip labels */
60
- 'align-tips'?: boolean;
61
- /** Show node labels */
62
- 'show-labels'?: boolean;
63
- /** Show scale bar */
64
- 'show-scale'?: boolean;
65
- /** Draw size bubbles on nodes */
66
- 'draw-size-bubbles'?: boolean;
111
+ /** Logger instance */
112
+ logger?: Console;
113
+ branches?: string;
114
+ /** Scale branches by length */
115
+ scaling?: boolean;
116
+ bootstrap?: boolean;
117
+ 'color-fill'?: boolean;
118
+ /** Font size for labels */
119
+ 'font-size'?: number;
67
120
  /** Show internal node names */
68
121
  'internal-names'?: boolean | ((node: PhylotreeNode) => boolean);
69
122
  /** Enable node selection */
70
123
  selectable?: boolean;
124
+ /** Only allow selection through the predefined selector names */
125
+ 'restricted-selectable'?: false | PredefinedSelector[];
71
126
  /** Enable collapsing of clades */
72
127
  collapsible?: boolean;
73
- /** Enable brushing for selection */
74
- brush?: boolean;
128
+ /** Horizontal spacing mode */
129
+ 'left-right-spacing'?: 'fixed-step' | 'fit-to-size';
130
+ /** Vertical spacing mode */
131
+ 'top-bottom-spacing'?: 'fixed-step' | 'fit-to-size';
75
132
  /** Left offset in pixels */
76
133
  'left-offset'?: number;
77
- /** Spacing mode for top-bottom */
78
- 'top-bottom-spacing'?: 'fixed-step' | 'fit';
79
- /** Spacing mode for left-right */
80
- 'left-right-spacing'?: 'fixed-step' | 'fit';
81
- /** Font size for labels */
82
- 'font-size'?: number;
83
- /** Maximum label width in characters */
84
- 'max-label-width'?: number;
85
- /** Bubble styler function */
134
+ /** Show scale bar (only top placement is implemented) */
135
+ 'show-scale'?: boolean | 'top';
136
+ /** Draw size bubbles on nodes */
137
+ 'draw-size-bubbles'?: boolean;
138
+ /** Bubble size for a node, used when `draw-size-bubbles` is on */
86
139
  'bubble-styler'?: (node: PhylotreeNode) => number;
87
- /** Restrict which nodes can be selected */
88
- 'restricted-selectable'?: string | ((link: PhylotreeLink) => boolean);
89
- /** Logger instance */
90
- logger?: Console;
140
+ 'binary-selectable'?: boolean;
141
+ /** Attributes cleared by binary selection */
142
+ 'attribute-list'?: string[];
143
+ /** Use radial/circular layout */
144
+ 'is-radial'?: boolean;
145
+ /** Use unrooted (equal-angle) layout */
146
+ 'is-unrooted'?: boolean;
147
+ 'max-radius'?: number;
148
+ 'annular-limit'?: number;
149
+ /** Compression applied to collapsed clades */
150
+ compression?: number;
151
+ /** Align tip labels */
152
+ 'align-tips'?: boolean;
153
+ 'maximum-per-node-spacing'?: number;
154
+ 'minimum-per-node-spacing'?: number;
155
+ 'maximum-per-level-spacing'?: number;
156
+ 'minimum-per-level-spacing'?: number;
157
+ /** Node circle radius accessor */
158
+ node_circle_size?: (node: PhylotreeNode) => number;
159
+ /** Force transitions on or off; null picks based on tree size */
160
+ transitions?: boolean | null;
161
+ /** Enable brushing for selection */
162
+ brush?: boolean;
163
+ /** Offer "reroot" in the node menu */
164
+ reroot?: boolean;
165
+ /** Offer "hide" in the node menu */
166
+ hide?: boolean;
167
+ 'label-nodes-with-name'?: boolean;
168
+ /** Enable zoom/pan behavior */
169
+ zoom?: boolean;
170
+ /** Show the node context menu */
171
+ 'show-menu'?: boolean;
172
+ /**
173
+ * Which mouse action opens the node menu: a left click (default), a
174
+ * right-click, or either
175
+ */
176
+ 'menu-trigger'?: 'click' | 'contextmenu' | 'both';
177
+ /** Show node labels */
178
+ 'show-labels'?: boolean;
179
+ /** Node styler; same as `TreeRender.style_nodes` */
180
+ 'node-styler'?: NodeStyler | null;
181
+ /** Edge styler; same as `TreeRender.style_edges` */
182
+ 'edge-styler'?: EdgeStyler | null;
183
+ /** Vertical span of each node */
184
+ 'node-span'?: ((node: PhylotreeNode) => number) | null;
185
+ /** Scale the SVG with its container using a viewBox */
186
+ responsive?: boolean;
187
+ /** `preserveAspectRatio` used when `responsive` is on */
188
+ 'preserve-aspect-ratio'?: string;
189
+ /** Single selection or several named selection sets */
190
+ 'selection-mode'?: 'single' | 'multi-set';
191
+ /** Selection sets for multi-set mode */
192
+ 'selection-sets'?: SelectionSetDefinition[];
193
+ /** Names of nodes to select after the first render */
194
+ 'initial-selection'?: string[];
195
+ /** Set name to node names, applied after the first render (multi-set mode) */
196
+ 'initial-sets'?: { [setName: string]: string[] };
197
+ /** Override CSS class names */
198
+ 'css-classes'?: Partial<Record<CssClassKey, string>>;
91
199
  }
92
200
 
93
201
  /**
94
202
  * Options for parsing tree input
95
203
  */
96
204
  export interface ParseOptions {
97
- /** Enable bootstrap value parsing */
98
- bootstrap_values?: boolean;
99
- /** Format type: "newick", "phyloxml", "nexus" */
100
- type?: string | ((input: string, options: ParseOptions) => any);
205
+ /** A registered format name, or a custom parser function */
206
+ type?:
207
+ | 'nexml'
208
+ | 'phyloxml'
209
+ | 'nexus'
210
+ | 'nwk'
211
+ | 'nhx'
212
+ | 'beast'
213
+ | ((input: any, options: ParseOptions) => { json: object | null; error: string | null });
214
+ /** Newick annotation delimiters (default `{` and `}`) */
215
+ left_delimiter?: string;
216
+ right_delimiter?: string;
101
217
  /** Logger instance */
102
218
  logger?: Console;
103
219
  }
104
220
 
221
+ /** Branch length accessor; called with a second argument to set a length */
222
+ export type BranchLengthAccessor = (node: PhylotreeNode, new_length?: number) => number | undefined;
223
+
224
+ /** Result of the linear fit used by `fitRootToTip` */
225
+ export interface LinearFit {
226
+ intercept: number;
227
+ slope: number;
228
+ r2: number;
229
+ 'var (intercept)': number;
230
+ 'var (slope)': number;
231
+ }
232
+
105
233
  /**
106
- * The TreeRender class handles visualization of the tree
234
+ * The TreeRender class handles visualization of the tree.
235
+ *
236
+ * Type-only: the class is not exported at runtime, so create instances with
237
+ * `phylotree.render()` rather than `new TreeRender()` or `instanceof`.
107
238
  */
108
- export class TreeRender {
239
+ declare class TreeRender {
109
240
  /** The phylotree instance this renderer belongs to */
110
- phylotree: Phylotree;
241
+ phylotree: phylotree;
111
242
  /** The SVG element */
112
- svg: d3.Selection<SVGSVGElement, unknown, null, undefined>;
113
- /** Rendering options */
243
+ svg: d3.Selection<SVGSVGElement, undefined, null, undefined>;
244
+ /** Rendering options, merged with the defaults */
114
245
  options: RenderOptions;
115
246
  /** Current zoom transform */
116
247
  currentZoomTransform: d3.ZoomTransform | null;
@@ -119,66 +250,164 @@ export class TreeRender {
119
250
  /** Rightmost leaf x position */
120
251
  right_most_leaf: number;
121
252
  /** The container element */
122
- container: string | HTMLElement;
253
+ container: string | HTMLElement | undefined;
254
+ /** Width of the SVG in pixels */
255
+ width: number;
256
+ /** Height of the SVG in pixels */
257
+ height: number;
258
+ /** Links being drawn */
259
+ links: PhylotreeLink[];
260
+ /** Label font size */
261
+ font_size: number;
262
+ /** Scale bar font size */
263
+ scale_bar_font_size: number;
264
+ /** CSS class names in use */
265
+ css_classes: Record<CssClassKey, string>;
266
+ /** Selection attribute name; see `selectionLabel` */
267
+ selection_attribute_name: string;
268
+ /** Current node styler */
269
+ node_styler: NodeStyler | null | undefined;
270
+ /** Current edge styler */
271
+ edge_styler: EdgeStyler | null | undefined;
272
+ /** Vertical span of each node */
273
+ nodeSpan: (node: PhylotreeNode) => number;
274
+ /** Extra spacing between a node and the previous one */
275
+ separation: (node: PhylotreeNode, previous: PhylotreeNode) => number;
123
276
 
124
- constructor(phylotree: Phylotree, options?: RenderOptions);
277
+ constructor(phylotree: phylotree, options?: RenderOptions);
125
278
 
126
279
  /** Get the SVG element */
127
280
  show(): SVGSVGElement;
128
281
 
129
282
  /** Update the tree display */
130
- update(): this;
283
+ update(transitions?: boolean): this;
131
284
 
132
- /** Update layout coordinates */
133
- update_layout(tree: PhylotreeNode): this;
285
+ /** Re-run the layout and redraw */
286
+ update_layout(new_json: object, do_hierarchy?: boolean): void;
134
287
 
135
288
  /** Get/set radial mode */
136
- radial(value?: boolean): boolean | this;
289
+ radial(): boolean;
290
+ radial(value: boolean): this;
137
291
 
138
292
  /** Get/set unrooted (equal-angle) layout mode */
139
- unrooted(value?: boolean): boolean | this;
293
+ unrooted(): boolean;
294
+ unrooted(value: boolean): this;
140
295
 
141
296
  /** Get/set align tips mode */
142
- alignTips(value?: boolean): boolean | this;
143
-
144
- /** Get/set selection label */
145
- selectionLabel(label?: string): string | this;
146
-
147
- /** Get/set node label accessor */
148
- nodeLabel(accessor?: (node: PhylotreeNode) => string): ((node: PhylotreeNode) => string) | this;
297
+ alignTips(): boolean;
298
+ alignTips(value: boolean): this;
299
+
300
+ /** Get/set whether internal node names are shown */
301
+ internalNames(): boolean | ((node: PhylotreeNode) => boolean);
302
+ internalNames(value: boolean | ((node: PhylotreeNode) => boolean)): this;
303
+
304
+ /** Get/set the selection attribute name */
305
+ selectionLabel(): string;
306
+ selectionLabel(label: string): this;
307
+
308
+ /** Get/set node label accessor (a falsy value restores the default) */
309
+ nodeLabel(): (node: PhylotreeNode) => string;
310
+ nodeLabel(accessor: ((node: PhylotreeNode) => string) | null | undefined): this;
311
+
312
+ /** Get the label font size */
313
+ fontSize(): number;
314
+ /** Set the label font size (`undefined` resets it to 12) */
315
+ fontSize(size: number | undefined): this;
316
+ /** Get the scale bar font size */
317
+ scaleBarFontSize(): number;
318
+ /** Set the scale bar font size (`undefined` resets it to 12) */
319
+ scaleBarFontSize(size: number | undefined): this;
149
320
 
150
321
  /** Get/set node styler function */
151
- nodeStyler(styler?: (element: d3.Selection<any, PhylotreeNode, any, any>, node: PhylotreeNode) => void): this;
322
+ style_nodes(): NodeStyler | null | undefined;
323
+ style_nodes(styler: NodeStyler | null): this;
152
324
 
153
325
  /** Get/set edge styler function */
154
- edgeStyler(styler?: (element: d3.Selection<any, PhylotreeLink, any, any>, link: PhylotreeLink) => void): this;
326
+ style_edges(): EdgeStyler | null | undefined;
327
+ style_edges(styler: EdgeStyler | null): this;
328
+
329
+ /** Mark a node as collapsed (call `update()` to redraw) */
330
+ collapse_node(node: PhylotreeNode): void;
155
331
 
156
- /** Collapse a node */
157
- collapse_node(node: PhylotreeNode): this;
332
+ /** Collapse or expand a node and lay out the tree again */
333
+ toggleCollapse(node: PhylotreeNode): this;
158
334
 
159
- /** Modify selection based on a callback */
160
- modifySelection(callback: (link: PhylotreeLink, callback: (selected: boolean) => void) => boolean): this;
335
+ /**
336
+ * Modify the selection.
337
+ * @param node_selecter A predicate over links; an array of nodes to change;
338
+ * or, when `restricted-selectable` is set, a predefined selector name
339
+ * (any other value is then ignored and nothing is returned)
340
+ * @param attr Selection attribute to modify (default: `selectionLabel()`)
341
+ * @param place Whether to call `placenodes` afterwards
342
+ * @param skip_refresh Whether to skip the refresh
343
+ * @param mode For an array of nodes: toggle them, or set to true / false
344
+ */
345
+ modifySelection(
346
+ node_selecter: ((link: PhylotreeLink) => boolean) | PhylotreeNode[] | PredefinedSelector,
347
+ attr?: string,
348
+ place?: boolean,
349
+ skip_refresh?: boolean,
350
+ mode?: 'toggle' | 'true' | 'false'
351
+ ): this;
161
352
 
162
353
  /** Get selected nodes */
163
354
  getSelection(): PhylotreeNode[];
164
355
 
165
- /** Get selected branches */
166
- getSelectedBranches(): PhylotreeLink[];
356
+ /** Select nodes by name */
357
+ selectNodes(names: string[]): this;
358
+
359
+ /** Deselect nodes by name */
360
+ deselectNodes(names: string[]): this;
361
+
362
+ /** Clear the selection */
363
+ clearSelection(): this;
167
364
 
168
- /** Register event listener */
365
+ /**
366
+ * Register an event listener. Emitted events: nodeClick, nodeHover,
367
+ * branchClick, contextMenu, rendered, selectionChange, collapsed, rerooted,
368
+ * setChange. `contextMenu` receives `(node, event)` when a node's menu is
369
+ * about to open; call `event.preventDefault()` to skip the built-in menu.
370
+ */
169
371
  on(event: string, callback: (...args: any[]) => void): this;
170
372
 
373
+ /** Remove an event listener */
374
+ off(event: string, callback: (...args: any[]) => void): this;
375
+
171
376
  /** Emit an event */
172
377
  emit(event: string, ...args: any[]): this;
173
378
 
174
- /** Selection callback setter */
379
+ /** Get/set the selection callback */
380
+ selectionCallback(): ((selection: PhylotreeNode[]) => void) | null;
175
381
  selectionCallback(callback: (selection: PhylotreeNode[]) => void): this;
176
382
 
383
+ /** Make a set's members the target of node/branch clicks (multi-set mode) */
384
+ setActiveSet(name: string): this;
385
+
386
+ /** Name of the active selection set */
387
+ getActiveSet(): string | null | undefined;
388
+
389
+ /** Nodes in a selection set */
390
+ getSetMembers(setName: string): PhylotreeNode[];
391
+
392
+ /** Add a node (or node name) to a selection set, removing it from the others */
393
+ addToSet(node: PhylotreeNode | string, setName: string): this;
394
+
395
+ /** Remove a node (or node name) from a selection set */
396
+ removeFromSet(node: PhylotreeNode | string, setName: string): this;
397
+
398
+ /** Whether a node is in a selection set */
399
+ isInSet(node: PhylotreeNode, setName: string): boolean;
400
+
401
+ /** Name of the selection set a node belongs to */
402
+ getNodeSet(node: PhylotreeNode): string | null;
403
+
404
+ /** Set up selection sets (called by the constructor in multi-set mode) */
405
+ initializeSelectionSets(sets: SelectionSetDefinition[]): void;
406
+
177
407
  /**
178
408
  * Get or set spacing in the x-direction (horizontal spacing between nodes)
179
409
  * @param attr The new spacing value if setting
180
410
  * @param skip_render Whether to skip re-rendering after setting
181
- * @returns The current spacing_x value if getting, or the TreeRender instance if setting
182
411
  */
183
412
  spacing_x(): number;
184
413
  spacing_x(attr: number, skip_render?: boolean): this;
@@ -187,121 +416,95 @@ export class TreeRender {
187
416
  * Get or set spacing in the y-direction (vertical spacing between levels)
188
417
  * @param attr The new spacing value if setting
189
418
  * @param skip_render Whether to skip re-rendering after setting
190
- * @returns The current spacing_y value if getting, or the TreeRender instance if setting
191
419
  */
192
420
  spacing_y(): number;
193
421
  spacing_y(attr: number, skip_render?: boolean): this;
194
422
 
195
- /**
196
- * Get or set the font size for labels
197
- * @param attr The new font size if setting
198
- * @returns The current font size if getting, or the TreeRender instance if setting
199
- */
200
- font_size(): number;
201
- font_size(attr: number): this;
423
+ /** Get the node circle radius accessor, or set a constant radius */
424
+ node_circle_size(): (node: PhylotreeNode) => number;
425
+ node_circle_size(attr: number): this;
202
426
 
203
- /**
204
- * Get or set the scale bar font size
205
- * @param attr The new font size if setting
206
- * @returns The current scale bar font size if getting, or the TreeRender instance if setting
207
- */
208
- scale_bar_font_size(): number;
209
- scale_bar_font_size(attr: number): this;
427
+ /** Get or set this tree's CSS class names (kept across reroot) */
428
+ css(): Record<CssClassKey, string>;
429
+ css(opt: Partial<Record<CssClassKey, string>>): this;
210
430
 
211
- /**
212
- * Get or set the node circle size
213
- * @param attr The new circle size if setting
214
- * @param attr2 Optional second parameter
215
- * @returns The current node circle size if getting, or the TreeRender instance if setting
216
- */
217
- node_circle_size(): number;
218
- node_circle_size(attr: number, attr2?: number): this;
219
-
220
- /**
221
- * Get or set CSS classes
222
- * @param opt CSS class options
223
- * @returns The current CSS classes if getting, or the TreeRender instance if setting
224
- */
225
- css(): { [key: string]: string };
226
- css(opt: { [key: string]: string }): this;
227
-
228
- /**
229
- * Get or set transitions
230
- * @param arg Transition settings
231
- * @returns The current transition settings if getting, or the TreeRender instance if setting
232
- */
233
- transitions(): boolean | null;
234
- transitions(arg: boolean): this;
431
+ /** Whether transitions are used: `arg` if given, else the option, else size-based */
432
+ transitions(arg?: boolean): boolean;
235
433
 
236
- /**
237
- * Layout the tree
238
- * @param transitions Whether to use transitions
239
- * @returns The TreeRender instance
240
- */
434
+ /** Lay out the tree */
241
435
  layout(transitions?: boolean): this;
242
436
 
243
- /** Refresh the tree display */
437
+ /** Re-apply classes and the edge styler to the drawn edges */
244
438
  refresh(): this;
245
439
 
246
- /** Place nodes in the layout */
440
+ /** Compute node positions */
247
441
  placenodes(): this;
248
442
 
249
443
  /**
250
- * Set the separation function for node spacing
251
- * @param callback Function that returns additional spacing between nodes
252
- * @returns The TreeRender instance
444
+ * Set internal node selection from their children
445
+ * @param callback Called with an internal node's children; returns its selection state
446
+ * @param respect_existing Whether to keep existing internal selections
253
447
  */
254
- separation(callback: (node: PhylotreeNode, previous: PhylotreeNode) => number): this;
448
+ internalLabel(callback: (children: PhylotreeNode[]) => boolean, respect_existing?: boolean): void;
255
449
 
256
- /**
257
- * Set internal node labels based on children
258
- * @param callback Function that determines label based on children
259
- * @param respect_existing Whether to respect existing selections
260
- * @returns The TreeRender instance
261
- */
262
- internalLabel(callback: (children: PhylotreeNode[]) => boolean, respect_existing?: boolean): this;
450
+ /** Get or set the selection count handler */
451
+ countHandler(): (counts: { [attr: string]: number }) => void;
452
+ countHandler(callback: (counts: { [attr: string]: number }) => void): this;
453
+
454
+ /** Get or set the layout handler */
455
+ layoutHandler(): (tree: TreeRender) => void;
456
+ layoutHandler(callback: (tree: TreeRender) => void): this;
263
457
 
264
458
  /**
265
- * Get or set the count handler callback
266
- * @param callback Function called with selection count
267
- * @returns The current handler if getting, or the TreeRender instance if setting
459
+ * Add an item to a node's context menu
460
+ * @param node The node
461
+ * @param name Returns the menu item label
462
+ * @param callback Called when the item is clicked
463
+ * @param condition Optional; the item is shown only if it returns true
268
464
  */
269
- countHandler(): ((count: number) => void) | null;
270
- countHandler(callback: (count: number) => void): this;
465
+ addCustomMenu(
466
+ node: PhylotreeNode,
467
+ name: (node: PhylotreeNode) => string,
468
+ callback: (node: PhylotreeNode, event: MouseEvent) => void,
469
+ condition?: (node: PhylotreeNode) => boolean
470
+ ): void;
271
471
 
272
472
  /**
273
- * Update the selection key name
274
- * @param old_key The old key name
275
- * @param new_key The new key name
276
- * @returns The TreeRender instance
473
+ * Open a node's menu at the position of `event`, emitting `contextMenu`
474
+ * first
277
475
  */
278
- updateKeyName(old_key: string, new_key: string | null): this;
476
+ openNodeMenu(node: PhylotreeNode, event: MouseEvent): this;
279
477
 
280
478
  /**
281
- * Set the size of the tree display
282
- * @param attr Size as [width, height]
283
- * @returns The current size if getting, or the TreeRender instance if setting
479
+ * Get or set the size of the tree as `[height, width]`. Setting only
480
+ * changes dimensions whose spacing mode is not "fixed-step".
284
481
  */
285
482
  set_size(): [number, number];
286
483
  set_size(attr: [number, number]): this;
287
484
  }
288
485
 
486
+ export type { TreeRender };
487
+
289
488
  /**
290
- * Main Phylotree class for creating and manipulating phylogenetic trees
489
+ * Main phylotree class for creating and manipulating phylogenetic trees
291
490
  */
292
491
  export class phylotree {
293
- /** Hierarchical tree structure (D3 hierarchy) */
492
+ /** Root of the hierarchy (D3 hierarchy) */
294
493
  nodes: PhylotreeNode;
295
494
  /** Links between nodes */
296
495
  links: PhylotreeLink[];
297
496
  /** Parsed annotation tags */
298
497
  parsed_tags: string[];
299
498
  /** The tree renderer (set after calling render()) */
300
- display: TreeRender | null;
499
+ display?: TreeRender;
301
500
  /** Original Newick string */
302
501
  newick_string: string;
303
502
  /** Selection attribute name */
304
503
  selection_attribute_name: string;
504
+ /** Branch length accessor in use */
505
+ branch_length: BranchLengthAccessor;
506
+ /** Logger instance */
507
+ logger: Console;
305
508
 
306
509
  /**
307
510
  * Create a new phylogenetic tree
@@ -320,52 +523,58 @@ export class phylotree {
320
523
  /**
321
524
  * Traverse the tree and compute values at each node
322
525
  * @param callback Function called on each node
323
- * @param traversal_type "pre-order", "post-order", or "in-order"
526
+ * @param traversal_type "pre-order", "post-order" (default), or "in-order"
324
527
  * @param root_node Optional starting node
325
- * @param backtrack Optional function to stop traversal
528
+ * @param backtrack Optional; returning true skips a node and its subtree
326
529
  */
327
530
  traverse_and_compute(
328
531
  callback: (node: PhylotreeNode) => void,
329
532
  traversal_type?: 'pre-order' | 'post-order' | 'in-order',
330
- root_node?: PhylotreeNode,
533
+ root_node?: PhylotreeNode | null,
331
534
  backtrack?: (node: PhylotreeNode) => boolean
332
- ): void;
535
+ ): this;
333
536
 
334
- /** Export tree to JSON string */
335
- json(traversal_type?: string): string;
537
+ /** Export the nodes to a JSON string, in the given traversal order */
538
+ json(traversal_type?: 'pre-order' | 'post-order' | 'in-order'): string;
336
539
 
337
540
  /** Get parsed annotation tags */
338
541
  get_parsed_tags(): string[];
339
542
 
340
- /** Update tree from JSON */
341
- update(json: object): this;
543
+ /** Replace the hierarchy */
544
+ update(json: PhylotreeNode): this;
342
545
 
343
- /** Check if tree has branch lengths */
546
+ /** Check if every non-root node has a branch length */
344
547
  hasBranchLengths(): boolean;
345
548
 
346
549
  /** Get all branch lengths */
347
- getBranchLengths(): number[];
550
+ getBranchLengths(): Array<number | undefined>;
348
551
 
349
- /** Set branch length accessor */
350
- setBranchLength(accessor: (node: PhylotreeNode) => number): this;
552
+ /** Get or set the branch length accessor (a falsy value restores the default) */
553
+ setBranchLength(): BranchLengthAccessor;
554
+ setBranchLength(accessor: BranchLengthAccessor | null | undefined): this;
351
555
 
352
- /** Normalize branch lengths */
353
- normalizeBranchLengths(attr?: string): this;
556
+ /** Rescale branch lengths to [0, 1] */
557
+ normalizeBranchLengths(): this;
354
558
 
355
- /** Scale branch lengths by a factor */
356
- scaleBranchLengths(scale: number): this;
559
+ /** Transform every branch length with a function */
560
+ scaleBranchLengths(scale_by: (length: number) => number): this;
357
561
 
358
- /** Get branch name accessor */
359
- branchName(accessor?: (node: PhylotreeNode) => string): string | this;
562
+ /** Get or set the branch name accessor */
563
+ branchName(): ((node: PhylotreeNode) => string) | undefined;
564
+ branchName(accessor: (node: PhylotreeNode) => string): this;
360
565
 
361
- /** Get Newick representation of tree */
362
- getNewick(annotator?: (node: PhylotreeNode) => string): string;
566
+ /**
567
+ * Get Newick representation of the tree
568
+ * @param annotator Returns a label to write after each node name
569
+ * @param root Start at this node (default: the root)
570
+ */
571
+ getNewick(annotator?: ((node: PhylotreeNode) => string) | null, root?: PhylotreeNode): string;
363
572
 
364
- /** Get tagged Newick representation */
365
- getTaggedNewick(): string;
573
+ /** Get Newick with `{tag}` annotations on selected nodes (or set names) */
574
+ getTaggedNewick(options?: { tag?: string; multiSet?: boolean }): string;
366
575
 
367
- /** Find most recent common ancestor of nodes */
368
- mrca(nodes: (PhylotreeNode | string)[]): PhylotreeNode;
576
+ /** Find most recent common ancestor of nodes (given as nodes or names) */
577
+ mrca(nodes: Array<PhylotreeNode | string>): PhylotreeNode | undefined;
369
578
 
370
579
  /** Check if a node is a leaf */
371
580
  isLeafNode(node: PhylotreeNode): boolean;
@@ -379,44 +588,56 @@ export class phylotree {
379
588
  /** Get root node */
380
589
  getRootNode(): PhylotreeNode;
381
590
 
382
- /** Get all nodes */
383
- getNodes(): PhylotreeNode[];
591
+ /** Get the root of the hierarchy (same as getRootNode) */
592
+ getNodes(): PhylotreeNode;
384
593
 
385
594
  /** Get node by name */
386
595
  getNodeByName(name: string): PhylotreeNode | undefined;
387
596
 
388
- /** Select all descendants of a node */
597
+ /** Get the descendants of a node */
389
598
  selectAllDescendants(node: PhylotreeNode, terminal?: boolean, internal?: boolean): PhylotreeNode[];
390
599
 
391
- /** Reroot the tree at a node */
600
+ /** Reroot the tree on the branch above a node */
392
601
  reroot(node: PhylotreeNode, fraction?: number): this;
393
602
 
394
- /** Get path from a node to the root */
603
+ /** Get the path from a node to the root, starting with the node */
395
604
  pathToRoot(node: PhylotreeNode): PhylotreeNode[];
396
605
 
397
- /** Resort children of nodes */
606
+ /** Re-sort children of nodes */
398
607
  resortChildren(comparator: (a: PhylotreeNode, b: PhylotreeNode) => number): this;
399
608
 
400
- /** Graft a new node */
401
- graftANode(graftAt: PhylotreeNode, newChild: PhylotreeNode, newParent?: PhylotreeNode, lengths?: { new_child: number; new_parent: number }): void;
609
+ /**
610
+ * Graft a new leaf next to a node
611
+ * @param graftAt The node to graft next to
612
+ * @param newChild Name of the new leaf
613
+ * @param newParent Name of the new internal node
614
+ * @param lengths Branch lengths for `[graftAt, newChild, newParent]`
615
+ */
616
+ graftANode(graftAt: PhylotreeNode, newChild: string, newParent: string, lengths?: string[]): this;
617
+
618
+ /** Create a node stub for `addChild` */
619
+ createNode(name: string, lengths?: unknown[]): PhylotreeNode;
620
+
621
+ /** Add a child to a node; returns the parent */
622
+ addChild<T extends object>(parent: T, child: object): T;
402
623
 
403
- /** Add a child node */
404
- addChild(parent: PhylotreeNode, child: PhylotreeNode): void;
624
+ /** Delete a node, given the node or its index in `nodes.descendants()` */
625
+ deleteANode(index: number | PhylotreeNode): this;
405
626
 
406
- /** Delete a node */
407
- deleteANode(index: number): void;
627
+ /** Store attributes in the `annotations` field of the nodes named by the keys */
628
+ assignAttributes(attributes: { [name: string]: unknown }): void;
408
629
 
409
- /** Assign attributes to nodes */
410
- assignAttributes(attributes: object): this;
630
+ /** Get tips and their branch lengths, longest first */
631
+ getTipLengths(): Array<{ name: string; length: number }>;
411
632
 
412
- /** Get tip lengths for date extraction */
413
- getTipLengths(): { [name: string]: number };
633
+ /** Maximum parsimony reconstruction of a selection attribute; needs a rendered tree */
634
+ maxParsimony(respect_existing: boolean, attr_name: string): void;
414
635
 
415
- /** Maximum parsimony ancestral state reconstruction */
416
- maxParsimony(attr: string, states: string[]): this;
636
+ /** Clear selection of internal nodes (unless `respect` is true) */
637
+ clearInternalNodes(respect?: boolean): void;
417
638
 
418
- /** Clear internal node selections */
419
- clearInternalNodes(respect?: boolean): this;
639
+ /** Rename (or, with a null new_key, delete) a key on every node */
640
+ updateKeyName(old_key: string, new_key: string | null): this;
420
641
  }
421
642
 
422
643
  // Utility functions
@@ -424,22 +645,46 @@ export class phylotree {
424
645
  /**
425
646
  * Parse a Newick format string
426
647
  */
427
- export function newickParser(newick: string, options?: ParseOptions): { json: object; error: string | null };
648
+ export function newickParser(
649
+ newick: string,
650
+ options?: { left_delimiter?: string; right_delimiter?: string }
651
+ ): { json: object | null; error: string | null };
652
+
653
+ /**
654
+ * Get Newick string from a tree; must be called with a phylotree as `this`
655
+ * (prefer `tree.getNewick()`)
656
+ */
657
+ export function getNewick(
658
+ this: phylotree,
659
+ annotator?: ((node: PhylotreeNode) => string) | null,
660
+ root?: PhylotreeNode
661
+ ): string;
428
662
 
429
663
  /**
430
- * Get Newick string from tree
664
+ * Add an item to a node's context menu; same as `TreeRender.addCustomMenu`
665
+ * @param node The node
666
+ * @param name Returns the menu item label
667
+ * @param callback Called when the item is clicked
668
+ * @param condition Optional; the item is shown only if it returns true
431
669
  */
432
- export function getNewick(tree: PhylotreeNode, annotator?: (node: PhylotreeNode) => string): string;
670
+ export function addCustomMenu(
671
+ node: PhylotreeNode,
672
+ name: (node: PhylotreeNode) => string,
673
+ callback: (node: PhylotreeNode, event: MouseEvent) => void,
674
+ condition?: (node: PhylotreeNode) => boolean
675
+ ): void;
433
676
 
434
677
  /**
435
- * Compute pairwise distances between nodes
678
+ * Annotate nodes with path lengths for pairwise distance computations
679
+ * @returns The number of leaves
436
680
  */
437
- export function pairwise_distances(tree: phylotree): number[][];
681
+ export function pairwise_distances(tree: phylotree): number;
438
682
 
439
683
  /**
440
- * Compute pairwise distances between nodes (camelCase alias)
684
+ * Annotate nodes with path lengths for pairwise distance computations (camelCase alias)
685
+ * @returns The number of leaves
441
686
  */
442
- export function pairwiseDistances(tree: phylotree): number[][];
687
+ export function pairwiseDistances(tree: phylotree): number;
443
688
 
444
689
  /**
445
690
  * Compute Sackin's index (tree balance measure)
@@ -447,91 +692,110 @@ export function pairwiseDistances(tree: phylotree): number[][];
447
692
  export function sackin(tree: phylotree): number;
448
693
 
449
694
  /**
450
- * Find center of tree
695
+ * Find the center of the tree (minimises the sum of distances^power to the leaves)
451
696
  */
452
- export function centerOfTree(tree: phylotree): PhylotreeNode;
697
+ export function centerOfTree(tree: phylotree, power?: number): {
698
+ location: PhylotreeNode;
699
+ breakpoint: number;
700
+ distance: number;
701
+ };
453
702
 
454
703
  /**
455
- * Compute midpoint for rooting
704
+ * Compute the midpoint for rooting
456
705
  */
457
- export function computeMidpoint(tree: phylotree): { node: PhylotreeNode; fraction: number };
706
+ export function computeMidpoint(tree: phylotree): { location: PhylotreeNode; breakpoint: number };
458
707
 
459
708
  /**
460
- * Root to tip regression
709
+ * Store root-to-tip distances on the nodes; returns the tree
461
710
  */
462
- export function rootToTip(tree: phylotree, attr?: string): {
463
- slope: number;
464
- intercept: number;
465
- r2: number;
466
- data: Array<{ date: number; distance: number; name: string }>;
467
- };
711
+ export function rootToTip(tree: phylotree): phylotree;
468
712
 
469
713
  /**
470
- * Fit root to tip (find optimal root)
714
+ * Find the root that maximises the root-to-tip regression r2 (needs dates;
715
+ * see extractDates). `root` is 0 if the current root is best.
471
716
  */
472
- export function fitRootToTip(tree: phylotree, attr?: string): {
473
- node: PhylotreeNode;
474
- fraction: number;
475
- r2: number;
476
- };
717
+ export function fitRootToTip(tree: phylotree): { root: PhylotreeNode; fit: LinearFit | null };
477
718
 
478
719
  /**
479
- * Extract dates from tip names
720
+ * Extract dates from nodes and store `date_value` / `decimal_date_value` in their data
480
721
  */
481
- export function extract_dates(tree: phylotree, pattern?: RegExp): { [name: string]: number };
722
+ export function extract_dates(
723
+ tree: phylotree,
724
+ date_getter?: (node: PhylotreeNode) => string | null,
725
+ date_converter?: (date: string) => Date | null
726
+ ): phylotree;
482
727
 
483
728
  /**
484
- * Extract dates from tip names (camelCase alias)
729
+ * Extract dates from nodes (camelCase alias)
485
730
  */
486
- export function extractDates(tree: phylotree, pattern?: RegExp): { [name: string]: number };
731
+ export function extractDates(
732
+ tree: phylotree,
733
+ date_getter?: (node: PhylotreeNode) => string | null,
734
+ date_converter?: (date: string) => Date | null
735
+ ): phylotree;
487
736
 
488
737
  /**
489
738
  * Cluster Picker algorithm
490
739
  */
491
- export function clusterPicker(tree: phylotree, options?: {
492
- bootstrap_threshold?: number;
493
- distance_threshold?: number;
494
- }): PhylotreeNode[][];
740
+ export function clusterPicker(
741
+ tree: phylotree,
742
+ bootstrap_threshold: number,
743
+ diameter_threshold: number,
744
+ root_node?: PhylotreeNode | null,
745
+ missing_bootstrap_value?: number
746
+ ): Array<{ root: PhylotreeNode; diameter: number; bootstrap: number; members: PhylotreeNode[] }>;
495
747
 
496
748
  /**
497
749
  * PhyloPart clustering algorithm
498
750
  */
499
- export function phylopart(tree: phylotree, options?: {
500
- bootstrap_threshold?: number;
501
- }): PhylotreeNode[][];
751
+ export function phylopart(
752
+ tree: phylotree,
753
+ bootstrap_threshold: number,
754
+ percentile_threshold: number,
755
+ missing_bootstrap_value?: number,
756
+ resolution?: number
757
+ ): Array<{ root: PhylotreeNode; median: number; bootstrap: number; members: PhylotreeNode[] }>;
502
758
 
503
759
  /**
504
- * Parse FASTA format
760
+ * Parse FASTA format into a map of sequence name to sequence
505
761
  */
506
- export function parseFasta(fasta: string): Array<{ name: string; seq: string }>;
762
+ export function parseFasta(fasta: string): { [name: string]: string };
507
763
 
508
764
  /**
509
765
  * Neighbor joining tree construction
766
+ * @param matrix The n x n distance matrix
767
+ * @param n The dimension of the matrix
768
+ * @param labels Row names (modified in place)
510
769
  */
511
- export function neighborJoining(matrix: number[][], labels: string[]): object;
770
+ export function neighborJoining(matrix: number[][], n: number, labels: string[]): phylotree | null;
512
771
 
513
772
  /**
514
- * Get distance matrix from sequences
773
+ * Pairwise (gap-masked) distances between aligned sequences
515
774
  */
516
- export function getDistanceMatrix(sequences: Array<{ name: string; seq: string }>): {
517
- matrix: number[][];
518
- labels: string[];
519
- };
775
+ export function getDistanceMatrix(sequences: { [name: string]: string }): { [name: string]: number[] };
520
776
 
521
777
  /**
522
- * Load annotations from NEXUS file
778
+ * Store `annotations.matrix[name]` in the `test` field of each tip's data
523
779
  */
524
- export function loadAnnotations(nexus: string): object;
780
+ export function loadAnnotations(
781
+ tree: phylotree,
782
+ label: string,
783
+ annotations: { matrix: { [name: string]: unknown } }
784
+ ): void;
525
785
 
526
786
  /**
527
- * Parse annotations from NEXUS
787
+ * Parse the DATA block of a NEXUS string ('' if there is none)
528
788
  */
529
- export function parseAnnotations(nexus: string): object;
789
+ export function parseAnnotations(nexus: string): '' | {
790
+ dimensions: { [key: string]: string };
791
+ format: { symbols: string[]; [key: string]: string | string[] };
792
+ matrix: { [name: string]: string[] };
793
+ };
530
794
 
531
795
  // Tree traversal functions
532
796
 
533
797
  /**
534
- * In-order traversal
798
+ * Level-order traversal (exported as inOrder)
535
799
  */
536
800
  export function inOrder(node: PhylotreeNode, callback: (node: PhylotreeNode) => void, backtrack?: (node: PhylotreeNode) => boolean): void;
537
801
 
@@ -546,6 +810,10 @@ export function preOrder(node: PhylotreeNode, callback: (node: PhylotreeNode) =>
546
810
  export function postOrder(node: PhylotreeNode, callback: (node: PhylotreeNode) => void, backtrack?: (node: PhylotreeNode) => boolean): void;
547
811
 
548
812
  /**
549
- * Left-child right-sibling traversal
813
+ * Edge list of the multi-way tree encoded by a left-child right-sibling binary tree
550
814
  */
551
- export function leftChildRightSibling(node: PhylotreeNode, callback: (node: PhylotreeNode) => void): void;
815
+ export function leftChildRightSibling(root: PhylotreeNode): Array<{
816
+ source: PhylotreeNode | null | undefined;
817
+ target: PhylotreeNode;
818
+ name: string;
819
+ }>;