@euphrasiologist/lwphylo 1.1.15 → 1.2.2

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.
@@ -0,0 +1,1136 @@
1
+ 'use strict';
2
+
3
+ var d3 = require('d3');
4
+
5
+ function _interopNamespaceDefault(e) {
6
+ var n = Object.create(null);
7
+ if (e) {
8
+ Object.keys(e).forEach(function (k) {
9
+ if (k !== 'default') {
10
+ var d = Object.getOwnPropertyDescriptor(e, k);
11
+ Object.defineProperty(n, k, d.get ? d : {
12
+ enumerable: true,
13
+ get: function () { return e[k]; }
14
+ });
15
+ }
16
+ });
17
+ }
18
+ n.default = e;
19
+ return Object.freeze(n);
20
+ }
21
+
22
+ var d3__namespace = /*#__PURE__*/_interopNamespaceDefault(d3);
23
+
24
+ // src/radial/polarToCartesian.js
25
+ function polarToCartesian (cx, cy, r, t) {
26
+ return { x: cx + r * Math.cos(t), y: cy - r * Math.sin(t) };
27
+ }
28
+
29
+ /**
30
+ * Draw the shortest arc between startAngle and endAngle (radians), CCW.
31
+ * If the CW path is shorter, swap start/end so the CCW path is still shortest.
32
+ * Works with Y-inverted screen coords (polarToCartesian already inverts Y).
33
+ */
34
+ function describeArc(cx, cy, radius, startAngle, endAngle) {
35
+ const TAU = Math.PI * 2;
36
+ const norm = (t) => ((t % TAU) + TAU) % TAU;
37
+ let a0 = norm(startAngle);
38
+ let a1 = norm(endAngle);
39
+
40
+ // CCW and CW spans
41
+ const ccw = (a1 - a0 + TAU) % TAU;
42
+ const cw = (a0 - a1 + TAU) % TAU;
43
+
44
+ // Ensure we always take the shorter span *in CCW* by swapping if needed
45
+ if (cw < ccw) {
46
+ const tmp = a0; a0 = a1; a1 = tmp;
47
+ }
48
+
49
+ const delta = (a1 - a0 + TAU) % TAU; // now the shorter CCW span
50
+ if (delta < 1e-9) {
51
+ const p = polarToCartesian(cx, cy, radius, a0);
52
+ return `M ${p.x} ${p.y}`; // degenerate span → no arc
53
+ }
54
+
55
+ const largeArcFlag = delta > Math.PI ? 1 : 0; // should be 0 for “shortest”, but keep for safety
56
+ const sweepFlag = 0; // CCW
57
+
58
+ const p0 = polarToCartesian(cx, cy, radius, a0);
59
+ const p1 = polarToCartesian(cx, cy, radius, a1);
60
+
61
+ return `M ${p0.x} ${p0.y} A ${radius} ${radius} 0 ${largeArcFlag} ${sweepFlag} ${p1.x} ${p1.y}`;
62
+ }
63
+
64
+ /**
65
+ * Recursive function for pre-order traversal of tree (returns array)
66
+ */
67
+ function preorder(node, list = []) {
68
+ list.push(node);
69
+ for (let i = 0; i < (node.children?.length || 0); i++) {
70
+ list = preorder(node.children[i], list);
71
+ }
72
+ return list;
73
+ }
74
+
75
+ /**
76
+ * Convert parsed Newick tree from readTree() into data
77
+ * frame.
78
+ * this is akin to a "phylo" object in R.
79
+ */
80
+
81
+ function fortify (tree, sort = true) {
82
+ var df = [];
83
+
84
+ for (const node of preorder(tree)) {
85
+ if (node.parent === null) {
86
+ df.push({
87
+ 'parentId': null,
88
+ 'parentLabel': null,
89
+ 'thisId': node.id,
90
+ 'thisLabel': node.label,
91
+ 'children': node.children.map(x => x.id),
92
+ 'branchLength': 0.,
93
+ 'isTip': false,
94
+ 'x': node.x,
95
+ 'y': node.y,
96
+ 'angle': node.angle
97
+ });
98
+ }
99
+ else {
100
+ df.push({
101
+ 'parentId': node.parent.id,
102
+ 'parentLabel': node.parent.label,
103
+ 'thisId': node.id,
104
+ 'thisLabel': node.label,
105
+ 'children': node.children.map(x => x.id),
106
+ 'branchLength': node.branchLength,
107
+ 'isTip': (node.children.length == 0),
108
+ 'x': node.x,
109
+ 'y': node.y,
110
+ 'angle': node.angle
111
+ });
112
+ }
113
+ }
114
+
115
+ if (sort) {
116
+ df = df.sort(function (a, b) {
117
+ return a.thisId - b.thisId;
118
+ });
119
+ }
120
+ return (df);
121
+ }
122
+
123
+ /**
124
+ * Compute per-node polar coordinates for radial layout:
125
+ * - Tip angles: evenly spaced 0..2π in tip DFS order
126
+ * - Internal angles: circular mean of child angles
127
+ * - Radii: cumulative branch length from root
128
+ * - x,y: cartesian projection
129
+ *
130
+ * Returns the fortified array with added {angle, r, x, y}.
131
+ */
132
+ function radialData(node) {
133
+ const TAU = Math.PI * 2;
134
+ const norm = (t) => ((t % TAU) + TAU) % TAU;
135
+
136
+ const pd = fortify(node, /*sort*/ true);
137
+ const byId = new Map(pd.map(d => [d.thisId, d]));
138
+ const kids = new Map(pd.map(d => [d.thisId, d.children || []]));
139
+
140
+ // Find root id
141
+ let root = null;
142
+ for (const d of pd) {
143
+ if (d.parentId == null) { root = d.thisId; break; }
144
+ }
145
+
146
+ // Collect tip ids in DFS left->right order to preserve input ordering
147
+ const tipIds = [];
148
+ (function dfs(id) {
149
+ const c = kids.get(id) || [];
150
+ if (c.length === 0) {
151
+ tipIds.push(id);
152
+ return;
153
+ }
154
+ for (const ch of c) dfs(ch);
155
+ })(root);
156
+
157
+ // Assign tip angles evenly spaced 0..2π
158
+ const N = Math.max(1, tipIds.length);
159
+ const angle = new Map();
160
+ tipIds.forEach((id, i) => {
161
+ angle.set(id, (i / N) * TAU);
162
+ });
163
+
164
+ // Internal node angles: circular mean of child angles (post-order)
165
+ (function setInternalAngles(id) {
166
+ const c = kids.get(id) || [];
167
+ for (const ch of c) setInternalAngles(ch);
168
+ if (c.length > 0) {
169
+ let sx = 0, sy = 0;
170
+ for (const ch of c) {
171
+ const th = angle.get(ch);
172
+ sx += Math.cos(th);
173
+ sy += Math.sin(th);
174
+ }
175
+ angle.set(id, norm(Math.atan2(sy, sx)));
176
+ }
177
+ })(root);
178
+
179
+ // Radii: cumulative branch lengths from root (root r=0)
180
+ const radius = new Map();
181
+ radius.set(root, 0);
182
+ (function setR(id) {
183
+ const c = kids.get(id) || [];
184
+ const r0 = radius.get(id) || 0;
185
+ for (const ch of c) {
186
+ const child = byId.get(ch);
187
+ const bl = child?.branchLength ?? 0;
188
+ radius.set(ch, r0 + bl);
189
+ setR(ch);
190
+ }
191
+ })(root);
192
+
193
+ // Enrich pd rows with angle, r, x, y
194
+ for (const d of pd) {
195
+ const th = angle.get(d.thisId) ?? 0;
196
+ const r = radius.get(d.thisId) ?? 0;
197
+ d.angle = th;
198
+ d.r = r;
199
+ d.x = r * Math.cos(th);
200
+ d.y = r * Math.sin(th);
201
+ }
202
+
203
+ return pd;
204
+ }
205
+
206
+ /**
207
+ * Per-edge radial segments (for highlighting and drawing).
208
+ * For each non-root node, draw a radial line from the parent radius to the child radius
209
+ * at the CHILD'S angle.
210
+ *
211
+ * Output: [{ parentId, childId, x0, y0, x1, y1, isTip }]
212
+ */
213
+ function getRadii(node) {
214
+ const data = radialData(node);
215
+ const byId = new Map(data.map(d => [d.thisId, d]));
216
+ const root = data.find(d => d.parentId == null)?.thisId;
217
+
218
+ const segments = [];
219
+ for (const d of data) {
220
+ if (d.thisId === root) continue;
221
+ const parent = byId.get(d.parentId);
222
+ if (!parent) continue;
223
+
224
+ const theta = d.angle;
225
+ const r0 = parent.r;
226
+ const r1 = d.r;
227
+
228
+ segments.push({
229
+ parentId: parent.thisId,
230
+ childId: d.thisId,
231
+ x0: r0 * Math.cos(theta),
232
+ y0: r0 * Math.sin(theta),
233
+ x1: r1 * Math.cos(theta),
234
+ y1: r1 * Math.sin(theta),
235
+ isTip: !!d.isTip
236
+ });
237
+ }
238
+ return segments;
239
+ }
240
+
241
+ /**
242
+ * Build arc descriptors for each internal parent:
243
+ * - One arc per internal node at radius = parent.r
244
+ * - Start/end angles choose the *shortest* wrap-aware span covering the children
245
+ * - Skips degenerate spans (delta ~ 0)
246
+ */
247
+ function getArcs(pd) {
248
+ const TAU = Math.PI * 2;
249
+ const norm = (t) => ((t % TAU) + TAU) % TAU;
250
+ const EPS = 1e-6;
251
+
252
+ // Quick lookups
253
+ new Map(pd.map(d => [d.thisId, d]));
254
+ const childrenByParent = new Map();
255
+ let root = null;
256
+
257
+ for (const d of pd) {
258
+ if (d.parentId == null) root = d.thisId;
259
+ if (!childrenByParent.has(d.parentId)) childrenByParent.set(d.parentId, []);
260
+ childrenByParent.get(d.parentId).push(d);
261
+ }
262
+
263
+ const arcs = [];
264
+
265
+ for (const parent of pd) {
266
+ const pid = parent.thisId;
267
+ if (pid === root) continue; // no arc above root
268
+ const kids = childrenByParent.get(pid) || [];
269
+ if (kids.length < 2) continue; // need at least two children
270
+
271
+ // Collect & sort child angles
272
+ const A = kids.map(k => norm(k.angle)).sort((a, b) => a - b);
273
+ const aMin = A[0], aMax = A[A.length - 1];
274
+
275
+ // Two candidate spans: direct (aMin -> aMax) and wrapped (aMax -> aMin across 2π)
276
+ const direct = aMax - aMin;
277
+ const wrapped = TAU - direct;
278
+
279
+ // Choose the shorter span. We'll draw **CCW** (sweepFlag = 0) in describeArc.
280
+ let start, end, span;
281
+ if (direct <= wrapped) {
282
+ start = aMin;
283
+ end = aMax;
284
+ span = direct;
285
+ } else {
286
+ // wrapped is shorter: go CCW from aMax up through 2π to aMin
287
+ start = aMax;
288
+ end = aMin;
289
+ span = wrapped;
290
+ }
291
+
292
+ if (span < EPS || !isFinite(parent.r) || parent.r <= 0) continue;
293
+
294
+ arcs.push({
295
+ start,
296
+ end,
297
+ radius: parent.r,
298
+ thisId: pid,
299
+ parentId: parent.parentId
300
+ });
301
+ }
302
+
303
+ return arcs;
304
+ }
305
+
306
+ /**
307
+ * Per-child "half" arcs for radial trees.
308
+ *
309
+ * For each non-root node (child), emit an arc at the PARENT's radius that
310
+ * spans between the parent's angle and the child's angle. This is the arc
311
+ * segment that meets the child's spoke and is ideal for root→tip highlighting.
312
+ *
313
+ * Input: pd — the array returned by radialData(node) (each row has .thisId, .parentId, .angle, .r)
314
+ * Output: [{ parentId, childId, radius, start, end }]
315
+ */
316
+ function getChildArcs(pd) {
317
+ const byId = new Map(pd.map(d => [d.thisId, d]));
318
+ const arcs = [];
319
+
320
+ for (const child of pd) {
321
+ if (child.parentId == null) continue; // skip root
322
+ const parent = byId.get(child.parentId);
323
+ if (!parent) continue;
324
+
325
+ arcs.push({
326
+ parentId: parent.thisId,
327
+ childId: child.thisId,
328
+ radius: parent.r, // draw on the parent's circle
329
+ start: parent.angle, // start at parent's angle
330
+ end: child.angle // end at child's angle (describeArc will choose the shortest CCW span)
331
+ });
332
+ }
333
+
334
+ return arcs;
335
+ }
336
+
337
+ /**
338
+ * Simple wrapper for radial layout:
339
+ * - data: per-node { angle, r, x, y, ... }
340
+ * - radii: per-edge radial spokes (parent.r → child.r)
341
+ * - arcs: per-parent arcs spanning all children at parent's radius
342
+ * - child_arcs: per-child half-arcs (parent.angle → child.angle) at parent's radius
343
+ */
344
+ function radialLayout(node) {
345
+ const data = {};
346
+ data.data = radialData(node);
347
+ data.radii = getRadii(node);
348
+ data.arcs = getArcs(data.data);
349
+ data.child_arcs = getChildArcs(data.data);
350
+ return data;
351
+ }
352
+
353
+ /**
354
+ * Iterable mean
355
+ * Poached from https://github.com/d3/d3-array/blob/master/src/mean.js
356
+ * (Other array means buggered up the tree)
357
+ */
358
+
359
+ function mean (values, valueof) {
360
+ let count = 0;
361
+ let sum = 0;
362
+ {
363
+ for (let value of values) {
364
+ if (value != null && (value = +value) >= value) {
365
+ ++count, sum += value;
366
+ }
367
+ }
368
+ }
369
+ if (count) return sum / count;
370
+ }
371
+
372
+ /**
373
+ * Rectangle layout: compute per-node x0,x1 and y0=y1
374
+ * - Tip y is assigned by input order (preserves ladderize/order)
375
+ * - Internal node y is mean of child y's
376
+ * - x1 accumulates branch lengths from root
377
+ */
378
+
379
+ function getHorizontal(node) {
380
+ const pd = fortify(node);
381
+
382
+ // Fast lookup from id -> pd index
383
+ const idIndex = new Map(pd.map((d, i) => [d.thisId, i]));
384
+
385
+ // 1) Leaf order from the INPUT TREE (respects your child order / ladderize)
386
+ const leafIds = [];
387
+ (function dfs(n) {
388
+ if (!n.children || n.children.length === 0) { leafIds.push(n.id); return; }
389
+ n.children.forEach(dfs);
390
+ })(node);
391
+
392
+ // Map each leaf id to a vertical slot (1..N)
393
+ const tipSlot = new Map(leafIds.map((id, i) => [id, i + 1]));
394
+
395
+ // 2) Set Y for tips directly from that order; internal node Y via children mean
396
+ (function setY(n) {
397
+ const i = idIndex.get(n.id);
398
+ if (!n.children || n.children.length === 0) {
399
+ const y = tipSlot.get(n.id);
400
+ pd[i].y0 = y; pd[i].y1 = y;
401
+ return y;
402
+ }
403
+ const ys = n.children.map(setY);
404
+ const y = mean(ys);
405
+ pd[i].y0 = y; pd[i].y1 = y;
406
+ return y;
407
+ })(node);
408
+
409
+ // 3) Set X by accumulating branch lengths down the tree
410
+ (function setX(n, xParent) {
411
+ const i = idIndex.get(n.id);
412
+ const bl = pd[i].branchLength ?? 0;
413
+ const x0 = xParent ?? 0;
414
+ const x1 = x0 + bl;
415
+ pd[i].x0 = x0; pd[i].x1 = x1;
416
+ if (n.children && n.children.length) n.children.forEach(c => setX(c, x1));
417
+ })(node, 0);
418
+
419
+ // Clean up: remove fields not needed downstream without triggering no-unused-vars
420
+ return pd.map((row) => {
421
+ const { y: _y, x: _x, angle: _angle, ...item } = row;
422
+ return item;
423
+ });
424
+ }
425
+
426
+ function getVertical(node) {
427
+ const data = getHorizontal(node);
428
+
429
+ // Group rows by parentId (children that share a parent)
430
+ const byParent = new Map();
431
+ for (const row of data) {
432
+ if (row.parentId == null) continue;
433
+ const a = byParent.get(row.parentId);
434
+ if (a) a.push(row); else byParent.set(row.parentId, [row]);
435
+ }
436
+
437
+ const verticals = [];
438
+ for (const [parentId, kids] of byParent.entries()) {
439
+ if (!kids.length) continue;
440
+ // Works for binary and multifurcations:
441
+ const yvals = kids.map(d => d.y0);
442
+ const y0 = Math.min(...yvals);
443
+ const y1 = Math.max(...yvals);
444
+ // All children share the same junction x (their x0)
445
+ const x = kids[0].x0;
446
+
447
+ verticals.push({
448
+ parentId,
449
+ x0: x,
450
+ x1: x,
451
+ y0,
452
+ y1,
453
+ heights: y1 - y0
454
+ });
455
+ }
456
+
457
+ return verticals;
458
+ }
459
+
460
+ /**
461
+ * Build per-child vertical segments for a rectangular tree:
462
+ * For each non-root node (child), draw a vertical from (parent.x, child.y) to (parent.x, parent.y).
463
+ * This yields exactly one vertical per edge (child->parent), making highlighting trivial.
464
+ *
465
+ * Returns an array of:
466
+ * {
467
+ * parentId: number,
468
+ * childId: number,
469
+ * x: number, // x of the parent junction
470
+ * y0: number, // min(child.y, parent.y)
471
+ * y1: number, // max(child.y, parent.y)
472
+ * }
473
+ */
474
+ function getChildVerticals(node) {
475
+ const data = getHorizontal(node); // has parentId, thisId, x0,x1,y0=y1
476
+
477
+ // Build a quick index to access parent's y by id
478
+ const byId = new Map(data.map(d => [d.thisId, d]));
479
+
480
+ const childVerticals = [];
481
+
482
+ for (const d of data) {
483
+ if (d.parentId == null) continue;
484
+ const parent = byId.get(d.parentId);
485
+ if (!parent) continue;
486
+
487
+ const x = d.x0; // child’s vertical sits at parent.x == child.x0
488
+ const yc = d.y0; // child y
489
+ const yp = parent.y0; // parent y
490
+ const y0 = Math.min(yc, yp);
491
+ const y1 = Math.max(yc, yp);
492
+
493
+ childVerticals.push({
494
+ parentId: d.parentId,
495
+ childId: d.thisId,
496
+ x,
497
+ y0,
498
+ y1
499
+ });
500
+ }
501
+
502
+ return childVerticals;
503
+ }
504
+
505
+ /**
506
+ * Rectangle layout wrapper.
507
+ * Returns:
508
+ * - data: per-node rows (x0,x1,y0=y1,...)
509
+ * - vertical_lines: single spanning vertical per parent (baseline draw)
510
+ * - child_vertical_lines: one vertical per edge (for highlighting)
511
+ * - horizontal_lines: per-edge child horizontals (x0->x1 at y), with labels & tip flags
512
+ */
513
+ function rectangleLayout(node) {
514
+ const data = getHorizontal(node); // per-node
515
+ const vertical_lines = getVertical(node); // parent spans
516
+ const child_vertical_lines = getChildVerticals(node); // per-edge verticals
517
+
518
+ // IMPORTANT: include y0 & y1, and carry isTip/labels for the renderer
519
+ new Map(data.map(d => [d.thisId, d]));
520
+ const horizontal_lines = data
521
+ .filter(d => d.parentId != null)
522
+ .map(d => ({
523
+ parentId: d.parentId,
524
+ childId: d.thisId,
525
+ thisId: d.thisId,
526
+ thisLabel: d.thisLabel,
527
+ isTip: d.isTip,
528
+ x0: d.x0,
529
+ x1: d.x1,
530
+ y0: d.y0,
531
+ y1: d.y0
532
+ }));
533
+
534
+ return { data, vertical_lines, child_vertical_lines, horizontal_lines };
535
+ }
536
+
537
+ /**
538
+ * Convert parsed Newick tree from fortify() into data frame of edges
539
+ * this is akin to a "phylo" object in R, where thisID and parentId
540
+ * are the $edge slot. I think.
541
+ */
542
+
543
+ function edges(df, rectangular = false) {
544
+ const rows = [...df].sort((a, b) => a.thisId - b.thisId);
545
+ const byId = new Map(rows.map((r) => [r.thisId, r]));
546
+ const result = [];
547
+
548
+ for (const row of rows) {
549
+ if (row.parentId == null) continue;
550
+ const parent = byId.get(row.parentId);
551
+ if (!parent) continue;
552
+
553
+ if (rectangular) {
554
+ result.push({ x1: row.x, y1: row.y, id1: row.thisId, x2: parent.x, y2: row.y, id2: undefined });
555
+ result.push({ x1: parent.x, y1: row.y, id1: undefined, x2: parent.x, y2: parent.y, id2: row.parentId });
556
+ } else {
557
+ result.push({ x1: row.x, y1: row.y, id1: row.thisId, x2: parent.x, y2: parent.y, id2: row.parentId });
558
+ }
559
+ }
560
+ return result;
561
+ }
562
+
563
+ /**
564
+ * Recursive function for breadth-first search of a tree
565
+ * the root node is visited first.
566
+ */
567
+
568
+ function levelorder(root) {
569
+ const queue = [root], result = [];
570
+ while (queue.length) {
571
+ const curnode = queue.shift(); // <- FIFO
572
+ result.push(curnode);
573
+ for (const child of curnode.children) queue.push(child);
574
+ }
575
+ return result;
576
+ }
577
+
578
+
579
+ /**
580
+ * Count the number of tips that descend from this node
581
+ */
582
+
583
+ function numTips(thisnode) {
584
+ var result = 0;
585
+ for (const node of levelorder(thisnode)) {
586
+ if (node.children.length == 0) result++;
587
+ }
588
+ return (result);
589
+ }
590
+
591
+ /**
592
+ * Equal-angle layout for unrooted trees.
593
+ * - Precomputes ntips in O(n) to avoid repeated subtree counts
594
+ * - Uses angles in "π units" (0..2) to match existing API
595
+ * - Populates x,y positions from branchLength and angle
596
+ */
597
+
598
+ function annotateTipCounts(root) {
599
+ (function post(n) {
600
+ if (!n.children || n.children.length === 0) {
601
+ n.ntips = 1; return 1;
602
+ }
603
+ let sum = 0;
604
+ for (const c of n.children) sum += post(c);
605
+ n.ntips = sum;
606
+ return sum;
607
+ })(root);
608
+ return root;
609
+ }
610
+
611
+ function equalAngleLayout(node) {
612
+ if (node.parent === null) {
613
+ annotateTipCounts(node);
614
+ node.start = 0.; // guarantees no arcs overlap 0
615
+ node.end = 2.; // *π
616
+ node.angle = 0.; // irrelevant at root
617
+ node.ntips = numTips(node); // safe (already computed), left for compatibility
618
+ node.x = 0;
619
+ node.y = 0;
620
+ }
621
+
622
+ let lastStart = node.start;
623
+
624
+ for (let i = 0; i < node.children.length; i++) {
625
+ const child = node.children[i];
626
+ const arc = (node.end - node.start) * (child.ntips / node.ntips);
627
+
628
+ child.start = lastStart;
629
+ child.end = lastStart + arc;
630
+
631
+ // bisect the arc in π-units
632
+ child.angle = child.start + (child.end - child.start) / 2.;
633
+ lastStart = child.end;
634
+
635
+ // map to coordinates (convert π-units to radians by multiplying by Math.PI)
636
+ const theta = child.angle * Math.PI;
637
+ const bl = (child.branchLength ?? 0);
638
+ child.x = node.x + bl * Math.sin(theta);
639
+ child.y = node.y + bl * Math.cos(theta);
640
+
641
+ equalAngleLayout(child);
642
+ }
643
+
644
+ return node;
645
+ }
646
+
647
+ /**
648
+ * Simple wrapper function for equalAngleLayout()
649
+ */
650
+
651
+ function unrooted (node) {
652
+ var data = {};
653
+ // use the Felsenstein equal angle layout algorithm
654
+ var eq = fortify(equalAngleLayout(node));
655
+ data.data = eq;
656
+ // make the edges dataset
657
+ data.edges = edges(eq);
658
+
659
+ return data;
660
+ }
661
+
662
+ /**
663
+ * Parse a Newick tree string into a doubly-linked list of JS Objects.
664
+ * Assigns labels, branch lengths, and node IDs (tips before internals if input emits them that way).
665
+ *
666
+ * Notes / limitations:
667
+ * - Quoted labels and NHX annotations are not fully supported.
668
+ * - Branch lengths in scientific notation are supported (parseFloat).
669
+ */
670
+
671
+ function readTree(text) {
672
+ // Remove all whitespace (space, tabs, newlines)
673
+ text = String(text).replace(/\s+/g, '');
674
+
675
+ const tokens = text.split(/(;|\(|\)|,)/);
676
+ const root = { parent: null, children: [] };
677
+ let curnode = root;
678
+ let nodeId = 0;
679
+
680
+ for (const token of tokens) {
681
+ if (!token || token === ';') continue;
682
+
683
+ if (token === '(') {
684
+ const child = { parent: curnode, children: [] };
685
+ curnode.children.push(child);
686
+ curnode = child; // descend
687
+ } else if (token === ',') {
688
+ // back to parent, then create sibling
689
+ curnode = curnode.parent;
690
+ const child = { parent: curnode, children: [] };
691
+ curnode.children.push(child);
692
+ curnode = child;
693
+ } else if (token === ')') {
694
+ // ascend one level
695
+ curnode = curnode.parent;
696
+ if (curnode === null) break;
697
+ } else {
698
+ // label/branch-length chunk (e.g., "A:0.01" or "A")
699
+ const nodeinfo = token.split(':');
700
+ if (nodeinfo.length === 1) {
701
+ if (token.startsWith(':')) {
702
+ curnode.label = '';
703
+ curnode.branchLength = parseFloat(nodeinfo[0]);
704
+ } else {
705
+ curnode.label = nodeinfo[0];
706
+ curnode.branchLength = null;
707
+ }
708
+ } else if (nodeinfo.length === 2) {
709
+ curnode.label = nodeinfo[0];
710
+ curnode.branchLength = parseFloat(nodeinfo[1]);
711
+ } else {
712
+ console.warn(token, "Unhandled token with multiple ':' characters");
713
+ curnode.label = nodeinfo[0] || '';
714
+ curnode.branchLength = parseFloat(nodeinfo[nodeinfo.length - 1]);
715
+ }
716
+ curnode.id = nodeId++; // assign then increment
717
+ }
718
+ }
719
+
720
+ // Ensure root has an id if not assigned during parsing
721
+ if (root.id == null) root.id = nodeId;
722
+
723
+ return root;
724
+ }
725
+
726
+ function drawPhylogeny(
727
+ treeText,
728
+ {
729
+ layout = "rect", // "rect" or "radial"
730
+ width = 800,
731
+ height = 800,
732
+ margin = { top: 20, right: 300, bottom: 20, left: 50 },
733
+ radialMargin = 80,
734
+ strokeWidth = 1,
735
+ radialMode = "outer" // or "align"
736
+ } = {}
737
+ ) {
738
+ if (layout === "rect") {
739
+ // RECTANGULAR LAYOUT
740
+ const tree_df = rectangleLayout(readTree(treeText));
741
+ const horizontal = tree_df.horizontal_lines;
742
+ const vertical = tree_df.vertical_lines;
743
+ const tips = horizontal.filter((d) => d.isTip);
744
+
745
+ const maxY = d3__namespace.max(horizontal, (d) => d.y1);
746
+ const minY = d3__namespace.min(horizontal, (d) => d.y1);
747
+ const maxX = d3__namespace.max(horizontal, (d) => d.x1);
748
+
749
+ const yScale = d3__namespace
750
+ .scaleLinear()
751
+ .domain([minY - 1, maxY + 1])
752
+ .range([margin.top, height - margin.bottom]);
753
+
754
+ const xScale = d3__namespace
755
+ .scaleLinear()
756
+ .domain([0, maxX])
757
+ .range([margin.left, width - margin.right]);
758
+
759
+ const svg = d3__namespace
760
+ .create("svg")
761
+ .attr("width", width)
762
+ .attr("height", height)
763
+ .attr("font-family", "sans-serif")
764
+ .attr("font-size", 10);
765
+
766
+ const group = svg.append("g");
767
+
768
+ group
769
+ .selectAll(".hline")
770
+ .data(horizontal)
771
+ .join("line")
772
+ .attr("x1", (d) => xScale(d.x0))
773
+ .attr("y1", (d) => yScale(d.y0))
774
+ .attr("x2", (d) => xScale(d.x1))
775
+ .attr("y2", (d) => yScale(d.y1))
776
+ .attr("stroke", "#555")
777
+ .attr("stroke-width", strokeWidth);
778
+
779
+ group
780
+ .selectAll(".vline")
781
+ .data(vertical)
782
+ .join("line")
783
+ .attr("x1", (d) => xScale(d.x0))
784
+ .attr("y1", (d) => yScale(d.y0))
785
+ .attr("x2", (d) => xScale(d.x1))
786
+ .attr("y2", (d) => yScale(d.y1))
787
+ .attr("stroke", "#555")
788
+ .attr("stroke-width", strokeWidth);
789
+
790
+ group
791
+ .selectAll(".tip-dot")
792
+ .data(tips)
793
+ .join("circle")
794
+ .attr("cx", (d) => xScale(d.x1))
795
+ .attr("cy", (d) => yScale(d.y1))
796
+ .attr("r", 2)
797
+ .attr("fill", "black");
798
+
799
+ svg
800
+ .append("g")
801
+ .selectAll("text")
802
+ .data(tips)
803
+ .join("text")
804
+ .attr("x", (d) => xScale(d.x1) + 4)
805
+ .attr("y", (d) => yScale(d.y1))
806
+ .attr("dy", "0.32em")
807
+ .attr("font-size", 10)
808
+ .text((d) => d.thisLabel?.replace(/_/g, " ") ?? "");
809
+
810
+ return svg.node();
811
+ } else if (layout === "radial") {
812
+ const parsedTree = readTree(treeText);
813
+ const rad = radialLayout(parsedTree);
814
+
815
+ // ===== MODE =====
816
+ const TIP_MODE = radialMode; // "align" (shorten to original tips) or "outer" (project to one circle)
817
+ const isOuter = TIP_MODE === "outer";
818
+
819
+ // visuals (0 = let spokes reach the dots)
820
+ const DOT_R = 3;
821
+ const END_CAP = 0;
822
+
823
+ // ===== SCALES / BOUNDS =====
824
+ const maxRadius = d3__namespace.max(rad.data, (d) => d.r) ?? 0;
825
+ const scaleRadial = maxRadius + 2 * radialMargin;
826
+ const w = width,
827
+ h = height;
828
+ const centerX = w / 2,
829
+ centerY = h / 2;
830
+
831
+ const xScaleRadial = d3__namespace
832
+ .scaleLinear()
833
+ .domain([-scaleRadial, scaleRadial])
834
+ .range([0, w]);
835
+ const yScaleRadial = d3__namespace
836
+ .scaleLinear()
837
+ .domain([-scaleRadial, scaleRadial])
838
+ .range([h, 0]);
839
+ const radiusPx = (r) => r * (w / (2 * scaleRadial));
840
+
841
+ // ===== INDEXES / HELPERS =====
842
+ const byId = new Map(rad.data.map((d) => [d.thisId, d]));
843
+ const tips = rad.data.filter((d) => d.isTip);
844
+ const tipMaxR = tips.length ? d3__namespace.max(tips, (d) => d.r) : 0;
845
+
846
+ // Robust child-id extractor (handles multiple shapes)
847
+ function childIdOf(spoke) {
848
+ // prefer explicit child id fields; fall back to thisId; last-ditch id1 (seen in some edge shapes)
849
+ return spoke.childId ?? spoke.thisId ?? spoke.id1 ?? null;
850
+ }
851
+
852
+ // Shorten the *screen-space* end of a spoke by END_CAP px
853
+ function shortenSpokePx(x0, y0, x1, y1) {
854
+ const X0 = xScaleRadial(x0),
855
+ Y0 = yScaleRadial(y0);
856
+ const X1 = xScaleRadial(x1),
857
+ Y1 = yScaleRadial(y1);
858
+ const dx = X1 - X0,
859
+ dy = Y1 - Y0;
860
+ const len = Math.hypot(dx, dy) || 1;
861
+ const t = Math.max(0, (len - END_CAP) / len);
862
+ return { X0, Y0, X1s: X0 + dx * t, Y1s: Y0 + dy * t, len };
863
+ }
864
+
865
+ // ===== SVG ROOT =====
866
+ const svg = d3__namespace
867
+ .create("svg")
868
+ .attr("width", w)
869
+ .attr("height", h)
870
+ .attr("font-family", "sans-serif")
871
+ .attr("font-size", 10);
872
+
873
+ const group = svg.append("g");
874
+
875
+ // ===== ARCS (parent circles) =====
876
+ group
877
+ .append("g")
878
+ .attr("class", "phylo_arcs")
879
+ .selectAll("path")
880
+ .data(rad.arcs)
881
+ .join("path")
882
+ .attr("d", (d) =>
883
+ describeArc(
884
+ centerX,
885
+ centerY,
886
+ Math.max(0, radiusPx(d.radius)),
887
+ d.start,
888
+ d.end
889
+ )
890
+ )
891
+ .attr("fill", "none")
892
+ .attr("stroke", "#777")
893
+ .attr("stroke-width", strokeWidth);
894
+
895
+ // ===== RADII (spokes) =====
896
+ group
897
+ .append("g")
898
+ .attr("class", "phylo_radii")
899
+ .selectAll("line")
900
+ .data(rad.radii)
901
+ .join("line")
902
+ .each(function(s, _) {
903
+ // parent end (data space)
904
+ const x0 = s.x0,
905
+ y0 = s.y0;
906
+
907
+ // child end (data space), shape-agnostic
908
+ const cid = childIdOf(s);
909
+ const node = cid != null ? byId.get(cid) : undefined;
910
+ const isTipSpoke = !!(node && node.isTip);
911
+
912
+ // default to the original child endpoint from the spoke record
913
+ let x1 = s.x1,
914
+ y1 = s.y1;
915
+
916
+ // In "outer" mode, project only *tip* spokes to the common circle
917
+ if (isOuter && isTipSpoke) {
918
+ x1 = tipMaxR * Math.cos(node.angle);
919
+ y1 = tipMaxR * Math.sin(node.angle);
920
+ }
921
+
922
+ // Shorten in screen space so the spoke doesn’t pierce the dot (END_CAP can be 0)
923
+ const { X0, Y0, X1s, Y1s} = shortenSpokePx(x0, y0, x1, y1);
924
+
925
+ d3__namespace.select(this)
926
+ .attr("x1", X0)
927
+ .attr("y1", Y0)
928
+ .attr("x2", X1s)
929
+ .attr("y2", Y1s)
930
+ .attr("stroke", "#777")
931
+ .attr("stroke-width", strokeWidth);
932
+ });
933
+
934
+ // ===== TIP DOTS =====
935
+ group
936
+ .append("g")
937
+ .attr("class", "phylo_tip_dots")
938
+ .selectAll("circle")
939
+ .data(tips)
940
+ .join("circle")
941
+ .each(function(d, _) {
942
+ // dot at original tip (align) or projected circle (outer)
943
+ const x = isOuter ? tipMaxR * Math.cos(d.angle) : d.x;
944
+ const y = isOuter ? tipMaxR * Math.sin(d.angle) : d.y;
945
+
946
+ d3__namespace.select(this)
947
+ .attr("cx", xScaleRadial(x))
948
+ .attr("cy", yScaleRadial(y))
949
+ .attr("r", DOT_R)
950
+ .attr("fill", "black")
951
+ .attr("stroke", "black")
952
+ .attr("stroke-width", 1.5);
953
+ });
954
+
955
+ // ===== LABELS (unchanged) =====
956
+ // Labels — make them follow the tip position used by the current mode
957
+ group
958
+ .append("g")
959
+ .attr("class", "phylo_labels")
960
+ .selectAll("g.label")
961
+ .data(tips) // <— bind only tip nodes
962
+ .join("g")
963
+ .attr("class", "label")
964
+ .attr("transform", (d) => {
965
+ // same tip position rule as dots/spokes:
966
+ // - "outer": snap to common ring (tipMaxR)
967
+ // - otherwise (e.g. "align"/"phylo"): true tip radius
968
+ const r = isOuter ? tipMaxR : d.r;
969
+ const x = r * Math.cos(d.angle);
970
+ const y = r * Math.sin(d.angle);
971
+ return `translate(${xScaleRadial(x)},${yScaleRadial(y)})`;
972
+ })
973
+ .each(function(d) {
974
+ // rotate so text reads outward; flip when on the left side
975
+ let angle = (-d.angle * 180) / Math.PI;
976
+ let xoff = 10; // radial padding for text (px)
977
+ let anchor = "start";
978
+ if (d.angle > Math.PI / 2 && d.angle < (3 * Math.PI) / 2) {
979
+ angle += 180;
980
+ xoff *= -1;
981
+ anchor = "end";
982
+ }
983
+ d3__namespace.select(this)
984
+ .append("g")
985
+ .attr("transform", `rotate(${angle})`)
986
+ .append("text")
987
+ .attr("x", xoff)
988
+ .attr("alignment-baseline", "middle")
989
+ .attr("text-anchor", anchor)
990
+ .attr("font-size", 10)
991
+ .attr("fill", "black")
992
+ .text((d) => d.thisLabel?.replace(/_/g, " ") ?? "");
993
+ });
994
+
995
+ return svg.node();
996
+ } else if (layout === "unrooted") {
997
+ // UNROOTED LAYOUT
998
+ const parsedTree = readTree(treeText);
999
+ const unrootedPhylo = unrooted(parsedTree);
1000
+
1001
+ const w = width;
1002
+ const h = height;
1003
+
1004
+ // Get spatial extent
1005
+ const xExtent = d3__namespace.extent(unrootedPhylo.data, (d) => d.x);
1006
+ const yExtent = d3__namespace.extent(unrootedPhylo.data, (d) => d.y);
1007
+
1008
+ // Find maximum absolute distance from center (0,0)
1009
+ const maxX = Math.max(Math.abs(xExtent[0]), Math.abs(xExtent[1]));
1010
+ const maxY = Math.max(Math.abs(yExtent[0]), Math.abs(yExtent[1]));
1011
+ const maxRadius = Math.max(maxX, maxY);
1012
+
1013
+ // Add some margin
1014
+ const scaleUnroot = maxRadius + 2 * radialMargin;
1015
+
1016
+ const xScaleUnroot = d3__namespace
1017
+ .scaleLinear()
1018
+ .domain([-scaleUnroot, scaleUnroot])
1019
+ .range([0, w]);
1020
+
1021
+ const yScaleUnroot = d3__namespace
1022
+ .scaleLinear()
1023
+ .domain([-scaleUnroot, scaleUnroot])
1024
+ .range([h, 0]);
1025
+
1026
+ const svg = d3__namespace
1027
+ .create("svg")
1028
+ .attr("width", w)
1029
+ .attr("height", h)
1030
+ .attr("font-family", "sans-serif")
1031
+ .attr("font-size", 10);
1032
+
1033
+ const group = svg.append("g");
1034
+
1035
+ // Edges
1036
+ group
1037
+ .append("g")
1038
+ .attr("class", "phylo_lines")
1039
+ .selectAll("line")
1040
+ .data(unrootedPhylo.edges)
1041
+ .join("line")
1042
+ .attr("x1", (d) => xScaleUnroot(d.x1))
1043
+ .attr("y1", (d) => yScaleUnroot(d.y1))
1044
+ .attr("x2", (d) => xScaleUnroot(d.x2))
1045
+ .attr("y2", (d) => yScaleUnroot(d.y2))
1046
+ .attr("stroke-width", strokeWidth)
1047
+ .attr("stroke", "#777");
1048
+
1049
+ // Nodes
1050
+ group
1051
+ .append("g")
1052
+ .attr("class", "phylo_points")
1053
+ .selectAll("circle")
1054
+ .data(unrootedPhylo.data)
1055
+ .join("circle")
1056
+ .attr("class", "dot")
1057
+ .attr("r", (d) => (d.isTip ? 4 : 0))
1058
+ .attr("cx", (d) => xScaleUnroot(d.x))
1059
+ .attr("cy", (d) => yScaleUnroot(d.y))
1060
+ .attr("stroke", "black")
1061
+ .attr("stroke-width", 2)
1062
+ .attr("fill", (d) => (d.isTip ? "black" : "white"));
1063
+
1064
+ // Tip labels
1065
+ const tipEdges = new Map();
1066
+ const nodesById = new Map(unrootedPhylo.data.map((d) => [d.thisId, d]));
1067
+
1068
+ unrootedPhylo.edges.forEach((edge) => {
1069
+ const tipNode = nodesById.get(edge.id1);
1070
+ if (tipNode?.isTip) {
1071
+ tipEdges.set(edge.id1, edge);
1072
+ }
1073
+ });
1074
+
1075
+ group
1076
+ .append("g")
1077
+ .attr("class", "phylo_labels")
1078
+ .selectAll("g")
1079
+ .data(unrootedPhylo.data.filter((d) => d.isTip))
1080
+ .join("g")
1081
+ .attr("transform", (d) => {
1082
+ const x = xScaleUnroot(d.x);
1083
+ const y = yScaleUnroot(d.y);
1084
+ return `translate(${x},${y})`;
1085
+ })
1086
+ .each(function(d) {
1087
+ const edge = tipEdges.get(d.thisId);
1088
+ if (!edge) {
1089
+ console.warn(
1090
+ "No incoming edge found for tip node:",
1091
+ d.thisId,
1092
+ d.thisLabel
1093
+ );
1094
+ return;
1095
+ }
1096
+
1097
+ // Compute angle of the incoming edge (screen coords)
1098
+ const x1 = xScaleUnroot(edge.x1);
1099
+ const y1 = yScaleUnroot(edge.y1);
1100
+ const x2 = xScaleUnroot(edge.x2);
1101
+ const y2 = yScaleUnroot(edge.y2);
1102
+
1103
+ const dx = x2 - x1;
1104
+ const dy = y2 - y1;
1105
+ let angle = (Math.atan2(dy, dx) * 180) / Math.PI;
1106
+
1107
+ // Flip label if upside down
1108
+ let xOffset = -10;
1109
+ let anchor = "end";
1110
+ if (angle > 90 || angle < -90) {
1111
+ angle += 180;
1112
+ anchor = "start";
1113
+ xOffset = 10;
1114
+ }
1115
+
1116
+ // Draw label rotated along branch direction
1117
+ d3__namespace.select(this)
1118
+ .append("g")
1119
+ .attr("transform", `rotate(${angle})`)
1120
+ .append("text")
1121
+ .attr("x", xOffset)
1122
+ .attr("alignment-baseline", "middle")
1123
+ .attr("text-anchor", anchor)
1124
+ .attr("font-size", 10)
1125
+ .attr("fill", "black")
1126
+ .text(d.thisLabel?.replace(/_/g, " ") ?? "");
1127
+ });
1128
+
1129
+ return svg.node();
1130
+ } else {
1131
+ throw new Error("Unsupported layout type. Use 'rect' or 'radial'.");
1132
+ }
1133
+ }
1134
+
1135
+ module.exports = drawPhylogeny;
1136
+ //# sourceMappingURL=drawPhylogeny.cjs.map