@euphrasiologist/lwphylo 1.1.15 → 1.2.1

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,1103 @@
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
+ * Simple wrapper for radial layout:
308
+ * - data: per-node { angle, r, x, y, ... }
309
+ * - radii: per-edge radial spokes (parent.r → child.r)
310
+ * - arcs: per-internal-node arcs spanning its children at parent radius
311
+ */
312
+ function radialLayout(node) {
313
+ const data = {};
314
+ data.data = radialData(node);
315
+ data.radii = getRadii(node);
316
+ data.arcs = getArcs(data.data);
317
+ return data;
318
+ }
319
+
320
+ /**
321
+ * Iterable mean
322
+ * Poached from https://github.com/d3/d3-array/blob/master/src/mean.js
323
+ * (Other array means buggered up the tree)
324
+ */
325
+
326
+ function mean (values, valueof) {
327
+ let count = 0;
328
+ let sum = 0;
329
+ {
330
+ for (let value of values) {
331
+ if (value != null && (value = +value) >= value) {
332
+ ++count, sum += value;
333
+ }
334
+ }
335
+ }
336
+ if (count) return sum / count;
337
+ }
338
+
339
+ /**
340
+ * Rectangle layout: compute per-node x0,x1 and y0=y1
341
+ * - Tip y is assigned by input order (preserves ladderize/order)
342
+ * - Internal node y is mean of child y's
343
+ * - x1 accumulates branch lengths from root
344
+ */
345
+
346
+ function getHorizontal(node) {
347
+ const pd = fortify(node);
348
+
349
+ // Fast lookup from id -> pd index
350
+ const idIndex = new Map(pd.map((d, i) => [d.thisId, i]));
351
+
352
+ // 1) Leaf order from the INPUT TREE (respects your child order / ladderize)
353
+ const leafIds = [];
354
+ (function dfs(n) {
355
+ if (!n.children || n.children.length === 0) { leafIds.push(n.id); return; }
356
+ n.children.forEach(dfs);
357
+ })(node);
358
+
359
+ // Map each leaf id to a vertical slot (1..N)
360
+ const tipSlot = new Map(leafIds.map((id, i) => [id, i + 1]));
361
+
362
+ // 2) Set Y for tips directly from that order; internal node Y via children mean
363
+ (function setY(n) {
364
+ const i = idIndex.get(n.id);
365
+ if (!n.children || n.children.length === 0) {
366
+ const y = tipSlot.get(n.id);
367
+ pd[i].y0 = y; pd[i].y1 = y;
368
+ return y;
369
+ }
370
+ const ys = n.children.map(setY);
371
+ const y = mean(ys);
372
+ pd[i].y0 = y; pd[i].y1 = y;
373
+ return y;
374
+ })(node);
375
+
376
+ // 3) Set X by accumulating branch lengths down the tree
377
+ (function setX(n, xParent) {
378
+ const i = idIndex.get(n.id);
379
+ const bl = pd[i].branchLength ?? 0;
380
+ const x0 = xParent ?? 0;
381
+ const x1 = x0 + bl;
382
+ pd[i].x0 = x0; pd[i].x1 = x1;
383
+ if (n.children && n.children.length) n.children.forEach(c => setX(c, x1));
384
+ })(node, 0);
385
+
386
+ // Clean up: remove fields not needed downstream without triggering no-unused-vars
387
+ return pd.map((row) => {
388
+ const { y: _y, x: _x, angle: _angle, ...item } = row;
389
+ return item;
390
+ });
391
+ }
392
+
393
+ function getVertical(node) {
394
+ const data = getHorizontal(node);
395
+
396
+ // Group rows by parentId (children that share a parent)
397
+ const byParent = new Map();
398
+ for (const row of data) {
399
+ if (row.parentId == null) continue;
400
+ const a = byParent.get(row.parentId);
401
+ if (a) a.push(row); else byParent.set(row.parentId, [row]);
402
+ }
403
+
404
+ const verticals = [];
405
+ for (const [parentId, kids] of byParent.entries()) {
406
+ if (!kids.length) continue;
407
+ // Works for binary and multifurcations:
408
+ const yvals = kids.map(d => d.y0);
409
+ const y0 = Math.min(...yvals);
410
+ const y1 = Math.max(...yvals);
411
+ // All children share the same junction x (their x0)
412
+ const x = kids[0].x0;
413
+
414
+ verticals.push({
415
+ parentId,
416
+ x0: x,
417
+ x1: x,
418
+ y0,
419
+ y1,
420
+ heights: y1 - y0
421
+ });
422
+ }
423
+
424
+ return verticals;
425
+ }
426
+
427
+ /**
428
+ * Build per-child vertical segments for a rectangular tree:
429
+ * For each non-root node (child), draw a vertical from (parent.x, child.y) to (parent.x, parent.y).
430
+ * This yields exactly one vertical per edge (child->parent), making highlighting trivial.
431
+ *
432
+ * Returns an array of:
433
+ * {
434
+ * parentId: number,
435
+ * childId: number,
436
+ * x: number, // x of the parent junction
437
+ * y0: number, // min(child.y, parent.y)
438
+ * y1: number, // max(child.y, parent.y)
439
+ * }
440
+ */
441
+ function getChildVerticals(node) {
442
+ const data = getHorizontal(node); // has parentId, thisId, x0,x1,y0=y1
443
+
444
+ // Build a quick index to access parent's y by id
445
+ const byId = new Map(data.map(d => [d.thisId, d]));
446
+
447
+ const childVerticals = [];
448
+
449
+ for (const d of data) {
450
+ if (d.parentId == null) continue;
451
+ const parent = byId.get(d.parentId);
452
+ if (!parent) continue;
453
+
454
+ const x = d.x0; // child’s vertical sits at parent.x == child.x0
455
+ const yc = d.y0; // child y
456
+ const yp = parent.y0; // parent y
457
+ const y0 = Math.min(yc, yp);
458
+ const y1 = Math.max(yc, yp);
459
+
460
+ childVerticals.push({
461
+ parentId: d.parentId,
462
+ childId: d.thisId,
463
+ x,
464
+ y0,
465
+ y1
466
+ });
467
+ }
468
+
469
+ return childVerticals;
470
+ }
471
+
472
+ /**
473
+ * Rectangle layout wrapper.
474
+ * Returns:
475
+ * - data: per-node rows (x0,x1,y0=y1,...)
476
+ * - vertical_lines: single spanning vertical per parent (baseline draw)
477
+ * - child_vertical_lines: one vertical per edge (for highlighting)
478
+ * - horizontal_lines: per-edge child horizontals (x0->x1 at y), with labels & tip flags
479
+ */
480
+ function rectangleLayout(node) {
481
+ const data = getHorizontal(node); // per-node
482
+ const vertical_lines = getVertical(node); // parent spans
483
+ const child_vertical_lines = getChildVerticals(node); // per-edge verticals
484
+
485
+ // IMPORTANT: include y0 & y1, and carry isTip/labels for the renderer
486
+ new Map(data.map(d => [d.thisId, d]));
487
+ const horizontal_lines = data
488
+ .filter(d => d.parentId != null)
489
+ .map(d => ({
490
+ parentId: d.parentId,
491
+ childId: d.thisId,
492
+ thisId: d.thisId,
493
+ thisLabel: d.thisLabel,
494
+ isTip: d.isTip,
495
+ x0: d.x0,
496
+ x1: d.x1,
497
+ y0: d.y0,
498
+ y1: d.y0
499
+ }));
500
+
501
+ return { data, vertical_lines, child_vertical_lines, horizontal_lines };
502
+ }
503
+
504
+ /**
505
+ * Convert parsed Newick tree from fortify() into data frame of edges
506
+ * this is akin to a "phylo" object in R, where thisID and parentId
507
+ * are the $edge slot. I think.
508
+ */
509
+
510
+ function edges(df, rectangular = false) {
511
+ const rows = [...df].sort((a, b) => a.thisId - b.thisId);
512
+ const byId = new Map(rows.map((r) => [r.thisId, r]));
513
+ const result = [];
514
+
515
+ for (const row of rows) {
516
+ if (row.parentId == null) continue;
517
+ const parent = byId.get(row.parentId);
518
+ if (!parent) continue;
519
+
520
+ if (rectangular) {
521
+ result.push({ x1: row.x, y1: row.y, id1: row.thisId, x2: parent.x, y2: row.y, id2: undefined });
522
+ result.push({ x1: parent.x, y1: row.y, id1: undefined, x2: parent.x, y2: parent.y, id2: row.parentId });
523
+ } else {
524
+ result.push({ x1: row.x, y1: row.y, id1: row.thisId, x2: parent.x, y2: parent.y, id2: row.parentId });
525
+ }
526
+ }
527
+ return result;
528
+ }
529
+
530
+ /**
531
+ * Recursive function for breadth-first search of a tree
532
+ * the root node is visited first.
533
+ */
534
+
535
+ function levelorder(root) {
536
+ const queue = [root], result = [];
537
+ while (queue.length) {
538
+ const curnode = queue.shift(); // <- FIFO
539
+ result.push(curnode);
540
+ for (const child of curnode.children) queue.push(child);
541
+ }
542
+ return result;
543
+ }
544
+
545
+
546
+ /**
547
+ * Count the number of tips that descend from this node
548
+ */
549
+
550
+ function numTips(thisnode) {
551
+ var result = 0;
552
+ for (const node of levelorder(thisnode)) {
553
+ if (node.children.length == 0) result++;
554
+ }
555
+ return (result);
556
+ }
557
+
558
+ /**
559
+ * Equal-angle layout for unrooted trees.
560
+ * - Precomputes ntips in O(n) to avoid repeated subtree counts
561
+ * - Uses angles in "π units" (0..2) to match existing API
562
+ * - Populates x,y positions from branchLength and angle
563
+ */
564
+
565
+ function annotateTipCounts(root) {
566
+ (function post(n) {
567
+ if (!n.children || n.children.length === 0) {
568
+ n.ntips = 1; return 1;
569
+ }
570
+ let sum = 0;
571
+ for (const c of n.children) sum += post(c);
572
+ n.ntips = sum;
573
+ return sum;
574
+ })(root);
575
+ return root;
576
+ }
577
+
578
+ function equalAngleLayout(node) {
579
+ if (node.parent === null) {
580
+ annotateTipCounts(node);
581
+ node.start = 0.; // guarantees no arcs overlap 0
582
+ node.end = 2.; // *π
583
+ node.angle = 0.; // irrelevant at root
584
+ node.ntips = numTips(node); // safe (already computed), left for compatibility
585
+ node.x = 0;
586
+ node.y = 0;
587
+ }
588
+
589
+ let lastStart = node.start;
590
+
591
+ for (let i = 0; i < node.children.length; i++) {
592
+ const child = node.children[i];
593
+ const arc = (node.end - node.start) * (child.ntips / node.ntips);
594
+
595
+ child.start = lastStart;
596
+ child.end = lastStart + arc;
597
+
598
+ // bisect the arc in π-units
599
+ child.angle = child.start + (child.end - child.start) / 2.;
600
+ lastStart = child.end;
601
+
602
+ // map to coordinates (convert π-units to radians by multiplying by Math.PI)
603
+ const theta = child.angle * Math.PI;
604
+ const bl = (child.branchLength ?? 0);
605
+ child.x = node.x + bl * Math.sin(theta);
606
+ child.y = node.y + bl * Math.cos(theta);
607
+
608
+ equalAngleLayout(child);
609
+ }
610
+
611
+ return node;
612
+ }
613
+
614
+ /**
615
+ * Simple wrapper function for equalAngleLayout()
616
+ */
617
+
618
+ function unrooted (node) {
619
+ var data = {};
620
+ // use the Felsenstein equal angle layout algorithm
621
+ var eq = fortify(equalAngleLayout(node));
622
+ data.data = eq;
623
+ // make the edges dataset
624
+ data.edges = edges(eq);
625
+
626
+ return data;
627
+ }
628
+
629
+ /**
630
+ * Parse a Newick tree string into a doubly-linked list of JS Objects.
631
+ * Assigns labels, branch lengths, and node IDs (tips before internals if input emits them that way).
632
+ *
633
+ * Notes / limitations:
634
+ * - Quoted labels and NHX annotations are not fully supported.
635
+ * - Branch lengths in scientific notation are supported (parseFloat).
636
+ */
637
+
638
+ function readTree(text) {
639
+ // Remove all whitespace (space, tabs, newlines)
640
+ text = String(text).replace(/\s+/g, '');
641
+
642
+ const tokens = text.split(/(;|\(|\)|,)/);
643
+ const root = { parent: null, children: [] };
644
+ let curnode = root;
645
+ let nodeId = 0;
646
+
647
+ for (const token of tokens) {
648
+ if (!token || token === ';') continue;
649
+
650
+ if (token === '(') {
651
+ const child = { parent: curnode, children: [] };
652
+ curnode.children.push(child);
653
+ curnode = child; // descend
654
+ } else if (token === ',') {
655
+ // back to parent, then create sibling
656
+ curnode = curnode.parent;
657
+ const child = { parent: curnode, children: [] };
658
+ curnode.children.push(child);
659
+ curnode = child;
660
+ } else if (token === ')') {
661
+ // ascend one level
662
+ curnode = curnode.parent;
663
+ if (curnode === null) break;
664
+ } else {
665
+ // label/branch-length chunk (e.g., "A:0.01" or "A")
666
+ const nodeinfo = token.split(':');
667
+ if (nodeinfo.length === 1) {
668
+ if (token.startsWith(':')) {
669
+ curnode.label = '';
670
+ curnode.branchLength = parseFloat(nodeinfo[0]);
671
+ } else {
672
+ curnode.label = nodeinfo[0];
673
+ curnode.branchLength = null;
674
+ }
675
+ } else if (nodeinfo.length === 2) {
676
+ curnode.label = nodeinfo[0];
677
+ curnode.branchLength = parseFloat(nodeinfo[1]);
678
+ } else {
679
+ console.warn(token, "Unhandled token with multiple ':' characters");
680
+ curnode.label = nodeinfo[0] || '';
681
+ curnode.branchLength = parseFloat(nodeinfo[nodeinfo.length - 1]);
682
+ }
683
+ curnode.id = nodeId++; // assign then increment
684
+ }
685
+ }
686
+
687
+ // Ensure root has an id if not assigned during parsing
688
+ if (root.id == null) root.id = nodeId;
689
+
690
+ return root;
691
+ }
692
+
693
+ function drawPhylogeny(
694
+ treeText,
695
+ {
696
+ layout = "rect", // "rect" or "radial"
697
+ width = 800,
698
+ height = 800,
699
+ margin = { top: 20, right: 300, bottom: 20, left: 50 },
700
+ radialMargin = 80,
701
+ strokeWidth = 1,
702
+ radialMode = "outer" // or "align"
703
+ } = {}
704
+ ) {
705
+ if (layout === "rect") {
706
+ // RECTANGULAR LAYOUT
707
+ const tree_df = rectangleLayout(readTree(treeText));
708
+ const horizontal = tree_df.horizontal_lines;
709
+ const vertical = tree_df.vertical_lines;
710
+ const tips = horizontal.filter((d) => d.isTip);
711
+
712
+ const maxY = d3__namespace.max(horizontal, (d) => d.y1);
713
+ const minY = d3__namespace.min(horizontal, (d) => d.y1);
714
+ const maxX = d3__namespace.max(horizontal, (d) => d.x1);
715
+
716
+ const yScale = d3__namespace
717
+ .scaleLinear()
718
+ .domain([minY - 1, maxY + 1])
719
+ .range([margin.top, height - margin.bottom]);
720
+
721
+ const xScale = d3__namespace
722
+ .scaleLinear()
723
+ .domain([0, maxX])
724
+ .range([margin.left, width - margin.right]);
725
+
726
+ const svg = d3__namespace
727
+ .create("svg")
728
+ .attr("width", width)
729
+ .attr("height", height)
730
+ .attr("font-family", "sans-serif")
731
+ .attr("font-size", 10);
732
+
733
+ const group = svg.append("g");
734
+
735
+ group
736
+ .selectAll(".hline")
737
+ .data(horizontal)
738
+ .join("line")
739
+ .attr("x1", (d) => xScale(d.x0))
740
+ .attr("y1", (d) => yScale(d.y0))
741
+ .attr("x2", (d) => xScale(d.x1))
742
+ .attr("y2", (d) => yScale(d.y1))
743
+ .attr("stroke", "#555")
744
+ .attr("stroke-width", strokeWidth);
745
+
746
+ group
747
+ .selectAll(".vline")
748
+ .data(vertical)
749
+ .join("line")
750
+ .attr("x1", (d) => xScale(d.x0))
751
+ .attr("y1", (d) => yScale(d.y0))
752
+ .attr("x2", (d) => xScale(d.x1))
753
+ .attr("y2", (d) => yScale(d.y1))
754
+ .attr("stroke", "#555")
755
+ .attr("stroke-width", strokeWidth);
756
+
757
+ group
758
+ .selectAll(".tip-dot")
759
+ .data(tips)
760
+ .join("circle")
761
+ .attr("cx", (d) => xScale(d.x1))
762
+ .attr("cy", (d) => yScale(d.y1))
763
+ .attr("r", 2)
764
+ .attr("fill", "black");
765
+
766
+ svg
767
+ .append("g")
768
+ .selectAll("text")
769
+ .data(tips)
770
+ .join("text")
771
+ .attr("x", (d) => xScale(d.x1) + 4)
772
+ .attr("y", (d) => yScale(d.y1))
773
+ .attr("dy", "0.32em")
774
+ .attr("font-size", 10)
775
+ .text((d) => d.thisLabel?.replace(/_/g, " ") ?? "");
776
+
777
+ return svg.node();
778
+ } else if (layout === "radial") {
779
+ const parsedTree = readTree(treeText);
780
+ const rad = radialLayout(parsedTree);
781
+
782
+ // ===== MODE / DEBUG =====
783
+ const TIP_MODE = radialMode; // "align" (shorten to original tips) or "outer" (project to one circle)
784
+ const isOuter = TIP_MODE === "outer";
785
+
786
+ // visuals (0 = let spokes reach the dots)
787
+ const DOT_R = 3;
788
+ const END_CAP = 0;
789
+
790
+ // ===== SCALES / BOUNDS =====
791
+ const maxRadius = d3__namespace.max(rad.data, (d) => d.r) ?? 0;
792
+ const scaleRadial = maxRadius + 2 * radialMargin;
793
+ const w = width,
794
+ h = height;
795
+ const centerX = w / 2,
796
+ centerY = h / 2;
797
+
798
+ const xScaleRadial = d3__namespace
799
+ .scaleLinear()
800
+ .domain([-scaleRadial, scaleRadial])
801
+ .range([0, w]);
802
+ const yScaleRadial = d3__namespace
803
+ .scaleLinear()
804
+ .domain([-scaleRadial, scaleRadial])
805
+ .range([h, 0]);
806
+ const radiusPx = (r) => r * (w / (2 * scaleRadial));
807
+
808
+ // ===== INDEXES / HELPERS =====
809
+ const byId = new Map(rad.data.map((d) => [d.thisId, d]));
810
+ const tips = rad.data.filter((d) => d.isTip);
811
+ const tipMaxR = tips.length ? d3__namespace.max(tips, (d) => d.r) : 0;
812
+
813
+ // Robust child-id extractor (handles multiple shapes)
814
+ function childIdOf(spoke) {
815
+ // prefer explicit child id fields; fall back to thisId; last-ditch id1 (seen in some edge shapes)
816
+ return spoke.childId ?? spoke.thisId ?? spoke.id1 ?? null;
817
+ }
818
+
819
+ // Shorten the *screen-space* end of a spoke by END_CAP px
820
+ function shortenSpokePx(x0, y0, x1, y1) {
821
+ const X0 = xScaleRadial(x0),
822
+ Y0 = yScaleRadial(y0);
823
+ const X1 = xScaleRadial(x1),
824
+ Y1 = yScaleRadial(y1);
825
+ const dx = X1 - X0,
826
+ dy = Y1 - Y0;
827
+ const len = Math.hypot(dx, dy) || 1;
828
+ const t = Math.max(0, (len - END_CAP) / len);
829
+ return { X0, Y0, X1s: X0 + dx * t, Y1s: Y0 + dy * t, len };
830
+ }
831
+
832
+ // ===== SVG ROOT =====
833
+ const svg = d3__namespace
834
+ .create("svg")
835
+ .attr("width", w)
836
+ .attr("height", h)
837
+ .attr("font-family", "sans-serif")
838
+ .attr("font-size", 10);
839
+
840
+ const group = svg.append("g");
841
+
842
+ // ===== ARCS (parent circles) =====
843
+ group
844
+ .append("g")
845
+ .attr("class", "phylo_arcs")
846
+ .selectAll("path")
847
+ .data(rad.arcs)
848
+ .join("path")
849
+ .attr("d", (d) =>
850
+ describeArc(
851
+ centerX,
852
+ centerY,
853
+ Math.max(0, radiusPx(d.radius)),
854
+ d.start,
855
+ d.end
856
+ )
857
+ )
858
+ .attr("fill", "none")
859
+ .attr("stroke", "#777")
860
+ .attr("stroke-width", strokeWidth);
861
+
862
+ // ===== RADII (spokes) =====
863
+ group
864
+ .append("g")
865
+ .attr("class", "phylo_radii")
866
+ .selectAll("line")
867
+ .data(rad.radii)
868
+ .join("line")
869
+ .each(function(s, _) {
870
+ // parent end (data space)
871
+ const x0 = s.x0,
872
+ y0 = s.y0;
873
+
874
+ // child end (data space), shape-agnostic
875
+ const cid = childIdOf(s);
876
+ const node = cid != null ? byId.get(cid) : undefined;
877
+ const isTipSpoke = !!(node && node.isTip);
878
+
879
+ // default to the original child endpoint from the spoke record
880
+ let x1 = s.x1,
881
+ y1 = s.y1;
882
+
883
+ // In "outer" mode, project only *tip* spokes to the common circle
884
+ if (isOuter && isTipSpoke) {
885
+ x1 = tipMaxR * Math.cos(node.angle);
886
+ y1 = tipMaxR * Math.sin(node.angle);
887
+ }
888
+
889
+ // Shorten in screen space so the spoke doesn’t pierce the dot (END_CAP can be 0)
890
+ const { X0, Y0, X1s, Y1s} = shortenSpokePx(x0, y0, x1, y1);
891
+
892
+ d3__namespace.select(this)
893
+ .attr("x1", X0)
894
+ .attr("y1", Y0)
895
+ .attr("x2", X1s)
896
+ .attr("y2", Y1s)
897
+ .attr("stroke", "#777")
898
+ .attr("stroke-width", strokeWidth);
899
+ });
900
+
901
+ // ===== TIP DOTS =====
902
+ group
903
+ .append("g")
904
+ .attr("class", "phylo_tip_dots")
905
+ .selectAll("circle")
906
+ .data(tips)
907
+ .join("circle")
908
+ .each(function(d, _) {
909
+ // dot at original tip (align) or projected circle (outer)
910
+ const x = isOuter ? tipMaxR * Math.cos(d.angle) : d.x;
911
+ const y = isOuter ? tipMaxR * Math.sin(d.angle) : d.y;
912
+
913
+ d3__namespace.select(this)
914
+ .attr("cx", xScaleRadial(x))
915
+ .attr("cy", yScaleRadial(y))
916
+ .attr("r", DOT_R)
917
+ .attr("fill", "black")
918
+ .attr("stroke", "black")
919
+ .attr("stroke-width", 1.5);
920
+ });
921
+
922
+ // ===== LABELS (unchanged) =====
923
+ // Labels — make them follow the tip position used by the current mode
924
+ group
925
+ .append("g")
926
+ .attr("class", "phylo_labels")
927
+ .selectAll("g.label")
928
+ .data(tips) // <— bind only tip nodes
929
+ .join("g")
930
+ .attr("class", "label")
931
+ .attr("transform", (d) => {
932
+ // same tip position rule as dots/spokes:
933
+ // - "outer": snap to common ring (tipMaxR)
934
+ // - otherwise (e.g. "align"/"phylo"): true tip radius
935
+ const r = isOuter ? tipMaxR : d.r;
936
+ const x = r * Math.cos(d.angle);
937
+ const y = r * Math.sin(d.angle);
938
+ return `translate(${xScaleRadial(x)},${yScaleRadial(y)})`;
939
+ })
940
+ .each(function(d) {
941
+ // rotate so text reads outward; flip when on the left side
942
+ let angle = (-d.angle * 180) / Math.PI;
943
+ let xoff = 10; // radial padding for text (px)
944
+ let anchor = "start";
945
+ if (d.angle > Math.PI / 2 && d.angle < (3 * Math.PI) / 2) {
946
+ angle += 180;
947
+ xoff *= -1;
948
+ anchor = "end";
949
+ }
950
+ d3__namespace.select(this)
951
+ .append("g")
952
+ .attr("transform", `rotate(${angle})`)
953
+ .append("text")
954
+ .attr("x", xoff)
955
+ .attr("alignment-baseline", "middle")
956
+ .attr("text-anchor", anchor)
957
+ .attr("font-size", 10)
958
+ .attr("fill", "black")
959
+ .text((d) => d.thisLabel?.replace(/_/g, " ") ?? "");
960
+ });
961
+
962
+ return svg.node();
963
+ } else if (layout === "unrooted") {
964
+ // UNROOTED LAYOUT
965
+ const parsedTree = readTree(treeText);
966
+ const unrootedPhylo = unrooted(parsedTree);
967
+
968
+ const w = width;
969
+ const h = height;
970
+
971
+ // Get spatial extent
972
+ const xExtent = d3__namespace.extent(unrootedPhylo.data, (d) => d.x);
973
+ const yExtent = d3__namespace.extent(unrootedPhylo.data, (d) => d.y);
974
+
975
+ // Find maximum absolute distance from center (0,0)
976
+ const maxX = Math.max(Math.abs(xExtent[0]), Math.abs(xExtent[1]));
977
+ const maxY = Math.max(Math.abs(yExtent[0]), Math.abs(yExtent[1]));
978
+ const maxRadius = Math.max(maxX, maxY);
979
+
980
+ // Add some margin
981
+ const scaleUnroot = maxRadius + 2 * radialMargin;
982
+
983
+ const xScaleUnroot = d3__namespace
984
+ .scaleLinear()
985
+ .domain([-scaleUnroot, scaleUnroot])
986
+ .range([0, w]);
987
+
988
+ const yScaleUnroot = d3__namespace
989
+ .scaleLinear()
990
+ .domain([-scaleUnroot, scaleUnroot])
991
+ .range([h, 0]);
992
+
993
+ const svg = d3__namespace
994
+ .create("svg")
995
+ .attr("width", w)
996
+ .attr("height", h)
997
+ .attr("font-family", "sans-serif")
998
+ .attr("font-size", 10);
999
+
1000
+ const group = svg.append("g");
1001
+
1002
+ // Edges
1003
+ group
1004
+ .append("g")
1005
+ .attr("class", "phylo_lines")
1006
+ .selectAll("line")
1007
+ .data(unrootedPhylo.edges)
1008
+ .join("line")
1009
+ .attr("x1", (d) => xScaleUnroot(d.x1))
1010
+ .attr("y1", (d) => yScaleUnroot(d.y1))
1011
+ .attr("x2", (d) => xScaleUnroot(d.x2))
1012
+ .attr("y2", (d) => yScaleUnroot(d.y2))
1013
+ .attr("stroke-width", strokeWidth)
1014
+ .attr("stroke", "#777");
1015
+
1016
+ // Nodes
1017
+ group
1018
+ .append("g")
1019
+ .attr("class", "phylo_points")
1020
+ .selectAll("circle")
1021
+ .data(unrootedPhylo.data)
1022
+ .join("circle")
1023
+ .attr("class", "dot")
1024
+ .attr("r", (d) => (d.isTip ? 4 : 0))
1025
+ .attr("cx", (d) => xScaleUnroot(d.x))
1026
+ .attr("cy", (d) => yScaleUnroot(d.y))
1027
+ .attr("stroke", "black")
1028
+ .attr("stroke-width", 2)
1029
+ .attr("fill", (d) => (d.isTip ? "black" : "white"));
1030
+
1031
+ // Tip labels
1032
+ const tipEdges = new Map();
1033
+ const nodesById = new Map(unrootedPhylo.data.map((d) => [d.thisId, d]));
1034
+
1035
+ unrootedPhylo.edges.forEach((edge) => {
1036
+ const tipNode = nodesById.get(edge.id1);
1037
+ if (tipNode?.isTip) {
1038
+ tipEdges.set(edge.id1, edge);
1039
+ }
1040
+ });
1041
+
1042
+ group
1043
+ .append("g")
1044
+ .attr("class", "phylo_labels")
1045
+ .selectAll("g")
1046
+ .data(unrootedPhylo.data.filter((d) => d.isTip))
1047
+ .join("g")
1048
+ .attr("transform", (d) => {
1049
+ const x = xScaleUnroot(d.x);
1050
+ const y = yScaleUnroot(d.y);
1051
+ return `translate(${x},${y})`;
1052
+ })
1053
+ .each(function(d) {
1054
+ const edge = tipEdges.get(d.thisId);
1055
+ if (!edge) {
1056
+ console.warn(
1057
+ "No incoming edge found for tip node:",
1058
+ d.thisId,
1059
+ d.thisLabel
1060
+ );
1061
+ return;
1062
+ }
1063
+
1064
+ // Compute angle of the incoming edge (screen coords)
1065
+ const x1 = xScaleUnroot(edge.x1);
1066
+ const y1 = yScaleUnroot(edge.y1);
1067
+ const x2 = xScaleUnroot(edge.x2);
1068
+ const y2 = yScaleUnroot(edge.y2);
1069
+
1070
+ const dx = x2 - x1;
1071
+ const dy = y2 - y1;
1072
+ let angle = (Math.atan2(dy, dx) * 180) / Math.PI;
1073
+
1074
+ // Flip label if upside down
1075
+ let xOffset = -10;
1076
+ let anchor = "end";
1077
+ if (angle > 90 || angle < -90) {
1078
+ angle += 180;
1079
+ anchor = "start";
1080
+ xOffset = 10;
1081
+ }
1082
+
1083
+ // Draw label rotated along branch direction
1084
+ d3__namespace.select(this)
1085
+ .append("g")
1086
+ .attr("transform", `rotate(${angle})`)
1087
+ .append("text")
1088
+ .attr("x", xOffset)
1089
+ .attr("alignment-baseline", "middle")
1090
+ .attr("text-anchor", anchor)
1091
+ .attr("font-size", 10)
1092
+ .attr("fill", "black")
1093
+ .text(d.thisLabel?.replace(/_/g, " ") ?? "");
1094
+ });
1095
+
1096
+ return svg.node();
1097
+ } else {
1098
+ throw new Error("Unsupported layout type. Use 'rect' or 'radial'.");
1099
+ }
1100
+ }
1101
+
1102
+ module.exports = drawPhylogeny;
1103
+ //# sourceMappingURL=drawPhylogeny.cjs.map