phylotree 2.6.1 → 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.
package/README.md CHANGED
@@ -136,10 +136,8 @@ import {
136
136
  } from "phylotree";
137
137
 
138
138
  // Example: Identify clusters
139
- const clusters = clusterPicker(tree, {
140
- bootstrap_threshold: 0.9,
141
- distance_threshold: 0.045
142
- });
139
+ // clusterPicker(tree, bootstrap_threshold, diameter_threshold)
140
+ const clusters = clusterPicker(tree, 0.9, 0.045);
143
141
  ```
144
142
 
145
143
  ### Tree Construction
@@ -244,6 +242,52 @@ The following are a list of possible options, along with their types, meanings,
244
242
  ### minimum-per-level-spacing
245
243
  `(Number)` Determines minimum node spacing allocated when laying out top to bottom. Defaults to 10.
246
244
 
245
+ ### show-menu
246
+ `(Boolean)` Whether or not the node menu is shown. Defaults to ``true``.
247
+
248
+ ### menu-trigger
249
+ `(String)` Which mouse action opens the node menu. Defaults to ``"click"``.
250
+
251
+ * ``"click"`` - Left click.
252
+ * ``"contextmenu"`` - Right-click; the browser's own context menu is suppressed on nodes.
253
+ * ``"both"`` - Either.
254
+
255
+ ## Node menu
256
+
257
+ Clicking a node (or right-clicking it, see [menu-trigger](#menu-trigger)) opens a menu with
258
+ the built-in actions enabled by the options above. Add your own items with `addCustomMenu`,
259
+ typically from a node styler:
260
+
261
+ ```javascript
262
+ import { phylotree, addCustomMenu } from "phylotree";
263
+
264
+ const tree = new phylotree(newick);
265
+ tree.render({
266
+ container: "#tree",
267
+ "menu-trigger": "contextmenu",
268
+ "node-styler": (element, node) => {
269
+ addCustomMenu(
270
+ node,
271
+ n => "Show details for " + n.data.name, // label
272
+ (n, event) => showDetails(n), // called when clicked
273
+ n => !n.children // optional: only on leaves
274
+ );
275
+ }
276
+ });
277
+ ```
278
+
279
+ Just before the menu opens, the tree emits `contextMenu` with `(node, event)`. Call
280
+ `event.preventDefault()` in a listener to show your own menu instead of the built-in one:
281
+
282
+ ```javascript
283
+ tree.display.on("contextMenu", (node, event) => {
284
+ event.preventDefault();
285
+ showMyMenu(node, event.clientX, event.clientY);
286
+ });
287
+ ```
288
+
289
+ `tree.display.openNodeMenu(node, event)` opens a node's menu from code.
290
+
247
291
  ## API Reference
248
292
  A complete list of available functions can be found at [API.md](API.md)
249
293
 
@@ -2,8 +2,7 @@
2
2
 
3
3
  const fs = require("fs"),
4
4
  phylotree = require("../dist/phylotree.js"),
5
- { program } = require("commander"),
6
- _ = require("lodash");
5
+ { program } = require("commander");
7
6
 
8
7
  program
9
8
  .arguments("<fasta>", "Input fasta file")
@@ -17,11 +16,11 @@ program
17
16
  fs.readFile(program.args[0], ( err, fastaData ) => {
18
17
 
19
18
  let fasta = phylotree.parseFasta(fastaData);
20
- let nodeList = _.keys(fasta);
19
+ let nodeList = Object.keys(fasta);
21
20
  let distanceMatrix = phylotree.getDistanceMatrix(fasta);
22
- let distanceMatrixArr = _.values(distanceMatrix);
21
+ let distanceMatrixArr = Object.values(distanceMatrix);
23
22
 
24
- let nj = phylotree.neighborJoining(distanceMatrixArr, _.keys(fasta).length, nodeList);
23
+ let nj = phylotree.neighborJoining(distanceMatrixArr, Object.keys(fasta).length, nodeList);
25
24
  console.log(nj.getNewick());
26
25
 
27
26
  });
@@ -28,7 +28,7 @@ if (!options.newick){
28
28
 
29
29
  // Assumes date formatted like 1984-09-20
30
30
  let date_parser = function(tree, node) {
31
- var location = '';
31
+ var location;
32
32
 
33
33
  const default_regexp = /([0-9]{4})-?([0-9]{2})-?([0-9]{2})$/g;
34
34
  if (tree.isLeafNode(node)) {
@@ -4,19 +4,27 @@ const fs = require("fs"),
4
4
  phylotree = require("../dist/phylotree.js"),
5
5
  { program } = require("commander"),
6
6
  _ = require("underscore"),
7
- moment = require("moment"),
8
- winston = require("winston"),
9
- { stringify } = require("csv-stringify");
10
-
11
- const logger = winston.createLogger({
12
- level: "warn",
13
- transports: [
14
- new winston.transports.Console({
15
- format: winston.format.simple()
16
- })
17
- ]
7
+ moment = require("moment");
8
+
9
+ // Logs go to stderr so they don't end up in the CSV on stdout.
10
+ const log_levels = { error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6 };
11
+
12
+ const logger = { level: "warn" };
13
+
14
+ _.each(_.keys(log_levels), name => {
15
+ logger[name] = message => {
16
+ const threshold = _.has(log_levels, logger.level) ? log_levels[logger.level] : log_levels.warn;
17
+ if (log_levels[name] <= threshold) {
18
+ console.error(name + ": " + message);
19
+ }
20
+ };
18
21
  });
19
22
 
23
+ function csv_field(value) {
24
+ const text = value == null ? "" : String(value);
25
+ return /[",\r\n]/.test(text) ? '"' + text.replace(/"/g, '""') + '"' : text;
26
+ }
27
+
20
28
  /*
21
29
  * Computes root-to-tip distance and fits linear regression
22
30
  * Please see the following notebook for more details
@@ -95,7 +103,7 @@ if (options.dateFormat) {
95
103
  let default_date_parser = function(tree, node) {
96
104
  const default_regexp = /([0-9]{4})-?([0-9]{2})-?([0-9]{2})$/g;
97
105
 
98
- var location = "";
106
+ var location;
99
107
 
100
108
  if (tree.isLeafNode(node)) {
101
109
  if ("name" in node.data) {
@@ -117,7 +125,7 @@ let default_date_parser = function(tree, node) {
117
125
 
118
126
  // Example - [0-9]{4}-[0-9]{2}-[0-9]{2}
119
127
  let regex_date_parser = function(tree, regex, format, node) {
120
- var location = "";
128
+ var location;
121
129
 
122
130
  if (tree.isLeafNode(node) && "name" in node.data) {
123
131
 
@@ -201,10 +209,10 @@ fs.readFile(options.newick, (err, newick_data) => {
201
209
  return !_.isNull(d.decimal_date_value);
202
210
  });
203
211
 
204
- stringify(date_and_distances, function(err, output) {
205
- // Pretty print table
206
- console.log("name, date");
207
- console.log(output);
208
- });
212
+ const rows = _.map(date_and_distances, row => _.map(row, csv_field).join(",") + "\n");
213
+
214
+ // Pretty print table
215
+ console.log("name, date");
216
+ console.log(rows.join(""));
209
217
 
210
218
  });
@@ -169,6 +169,11 @@ export interface RenderOptions {
169
169
  zoom?: boolean;
170
170
  /** Show the node context menu */
171
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';
172
177
  /** Show node labels */
173
178
  'show-labels'?: boolean;
174
179
  /** Node styler; same as `TreeRender.style_nodes` */
@@ -304,13 +309,22 @@ declare class TreeRender {
304
309
  nodeLabel(): (node: PhylotreeNode) => string;
305
310
  nodeLabel(accessor: ((node: PhylotreeNode) => string) | null | undefined): this;
306
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;
320
+
307
321
  /** Get/set node styler function */
308
322
  style_nodes(): NodeStyler | null | undefined;
309
323
  style_nodes(styler: NodeStyler | null): this;
310
324
 
311
325
  /** Get/set edge styler function */
312
326
  style_edges(): EdgeStyler | null | undefined;
313
- style_edges(styler: EdgeStyler): this;
327
+ style_edges(styler: EdgeStyler | null): this;
314
328
 
315
329
  /** Mark a node as collapsed (call `update()` to redraw) */
316
330
  collapse_node(node: PhylotreeNode): void;
@@ -350,7 +364,9 @@ declare class TreeRender {
350
364
 
351
365
  /**
352
366
  * Register an event listener. Emitted events: nodeClick, nodeHover,
353
- * branchClick, rendered, selectionChange, collapsed, rerooted, setChange.
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.
354
370
  */
355
371
  on(event: string, callback: (...args: any[]) => void): this;
356
372
 
@@ -449,10 +465,16 @@ declare class TreeRender {
449
465
  addCustomMenu(
450
466
  node: PhylotreeNode,
451
467
  name: (node: PhylotreeNode) => string,
452
- callback: (node: PhylotreeNode, ...args: any[]) => void,
468
+ callback: (node: PhylotreeNode, event: MouseEvent) => void,
453
469
  condition?: (node: PhylotreeNode) => boolean
454
470
  ): void;
455
471
 
472
+ /**
473
+ * Open a node's menu at the position of `event`, emitting `contextMenu`
474
+ * first
475
+ */
476
+ openNodeMenu(node: PhylotreeNode, event: MouseEvent): this;
477
+
456
478
  /**
457
479
  * Get or set the size of the tree as `[height, width]`. Setting only
458
480
  * changes dimensions whose spacing mode is not "fixed-step".
@@ -519,7 +541,7 @@ export class phylotree {
519
541
  get_parsed_tags(): string[];
520
542
 
521
543
  /** Replace the hierarchy */
522
- update(json: PhylotreeNode): void;
544
+ update(json: PhylotreeNode): this;
523
545
 
524
546
  /** Check if every non-root node has a branch length */
525
547
  hasBranchLengths(): boolean;
@@ -594,7 +616,7 @@ export class phylotree {
594
616
  graftANode(graftAt: PhylotreeNode, newChild: string, newParent: string, lengths?: string[]): this;
595
617
 
596
618
  /** Create a node stub for `addChild` */
597
- createNode(name: string, lengths?: unknown[]): { data: { name: string; attribute: unknown }; parent: string };
619
+ createNode(name: string, lengths?: unknown[]): PhylotreeNode;
598
620
 
599
621
  /** Add a child to a node; returns the parent */
600
622
  addChild<T extends object>(parent: T, child: object): T;
@@ -638,6 +660,20 @@ export function getNewick(
638
660
  root?: PhylotreeNode
639
661
  ): string;
640
662
 
663
+ /**
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
669
+ */
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;
676
+
641
677
  /**
642
678
  * Annotate nodes with path lengths for pairwise distance computations
643
679
  * @returns The number of leaves
@@ -678,7 +714,7 @@ export function rootToTip(tree: phylotree): phylotree;
678
714
  * Find the root that maximises the root-to-tip regression r2 (needs dates;
679
715
  * see extractDates). `root` is 0 if the current root is best.
680
716
  */
681
- export function fitRootToTip(tree: phylotree): { root: PhylotreeNode | 0; fit: LinearFit };
717
+ export function fitRootToTip(tree: phylotree): { root: PhylotreeNode; fit: LinearFit | null };
682
718
 
683
719
  /**
684
720
  * Extract dates from nodes and store `date_value` / `decimal_date_value` in their data