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