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