@ggterm/core 0.2.17 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/cli-plot.js +3128 -118
  2. package/dist/cli.js +2287 -23
  3. package/dist/geoms/biplot.d.ts +35 -0
  4. package/dist/geoms/biplot.d.ts.map +1 -0
  5. package/dist/geoms/bland-altman.d.ts +50 -0
  6. package/dist/geoms/bland-altman.d.ts.map +1 -0
  7. package/dist/geoms/control.d.ts +118 -0
  8. package/dist/geoms/control.d.ts.map +1 -0
  9. package/dist/geoms/dendrogram.d.ts +74 -0
  10. package/dist/geoms/dendrogram.d.ts.map +1 -0
  11. package/dist/geoms/ecdf.d.ts +66 -0
  12. package/dist/geoms/ecdf.d.ts.map +1 -0
  13. package/dist/geoms/forest.d.ts +45 -0
  14. package/dist/geoms/forest.d.ts.map +1 -0
  15. package/dist/geoms/funnel.d.ts +78 -0
  16. package/dist/geoms/funnel.d.ts.map +1 -0
  17. package/dist/geoms/heatmap.d.ts +34 -0
  18. package/dist/geoms/heatmap.d.ts.map +1 -0
  19. package/dist/geoms/index.d.ts +15 -1
  20. package/dist/geoms/index.d.ts.map +1 -1
  21. package/dist/geoms/kaplan-meier.d.ts +39 -0
  22. package/dist/geoms/kaplan-meier.d.ts.map +1 -0
  23. package/dist/geoms/ma.d.ts +77 -0
  24. package/dist/geoms/ma.d.ts.map +1 -0
  25. package/dist/geoms/manhattan.d.ts +29 -0
  26. package/dist/geoms/manhattan.d.ts.map +1 -0
  27. package/dist/geoms/qq.d.ts +51 -59
  28. package/dist/geoms/qq.d.ts.map +1 -1
  29. package/dist/geoms/roc.d.ts +44 -0
  30. package/dist/geoms/roc.d.ts.map +1 -0
  31. package/dist/geoms/scree.d.ts +97 -0
  32. package/dist/geoms/scree.d.ts.map +1 -0
  33. package/dist/geoms/upset.d.ts +63 -0
  34. package/dist/geoms/upset.d.ts.map +1 -0
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +2315 -25
  38. package/dist/pipeline/pipeline.d.ts.map +1 -1
  39. package/dist/pipeline/render-geoms.d.ts +4 -0
  40. package/dist/pipeline/render-geoms.d.ts.map +1 -1
  41. package/dist/serve.d.ts +8 -0
  42. package/dist/serve.d.ts.map +1 -0
  43. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -3708,6 +3708,96 @@ function renderGeomVolcano(data, geom, aes, scales, canvas) {
3708
3708
  }
3709
3709
  if (nLabels > 0 && aes.label) {
3710
3710
  const significantPoints = points.filter((p) => p.status !== "ns" && p.label).sort((a, b) => b.significance - a.significance).slice(0, nLabels);
3711
+ const labelColor = { r: 255, g: 255, b: 255, a: 1 };
3712
+ for (const point of significantPoints) {
3713
+ const cx = Math.round(scales.x.map(point.x));
3714
+ const cy = Math.round(scales.y.map(point.y));
3715
+ const label = point.label;
3716
+ const labelX = cx + 1;
3717
+ const labelY = cy;
3718
+ for (let i = 0;i < label.length; i++) {
3719
+ canvas.drawChar(labelX + i, labelY, label[i], labelColor);
3720
+ }
3721
+ }
3722
+ }
3723
+ }
3724
+ function renderGeomMA(data, geom, aes, scales, canvas) {
3725
+ const fcThreshold = geom.params.fc_threshold ?? 1;
3726
+ const pThreshold = geom.params.p_threshold ?? 0.05;
3727
+ const pCol = geom.params.p_col;
3728
+ const xIsLog2 = geom.params.x_is_log2 ?? false;
3729
+ const upColor = parseColorToRgba(geom.params.up_color ?? "#e41a1c");
3730
+ const downColor = parseColorToRgba(geom.params.down_color ?? "#377eb8");
3731
+ const nsColor = parseColorToRgba(geom.params.ns_color ?? "#999999");
3732
+ const showBaseline = geom.params.show_baseline ?? true;
3733
+ const showThresholds = geom.params.show_thresholds ?? true;
3734
+ const nLabels = geom.params.n_labels ?? 0;
3735
+ const pointChar = geom.params.point_char ?? "●";
3736
+ const points = [];
3737
+ for (const row of data) {
3738
+ let xVal = Number(row[aes.x]);
3739
+ const yVal = Number(row[aes.y]);
3740
+ if (isNaN(xVal) || isNaN(yVal))
3741
+ continue;
3742
+ if (xVal <= 0)
3743
+ continue;
3744
+ if (!xIsLog2) {
3745
+ xVal = Math.log2(xVal);
3746
+ }
3747
+ let status = "ns";
3748
+ const passesFcThreshold = Math.abs(yVal) >= fcThreshold;
3749
+ let passesPThreshold = true;
3750
+ if (pCol && row[pCol] !== undefined) {
3751
+ const pVal = Number(row[pCol]);
3752
+ passesPThreshold = !isNaN(pVal) && pVal < pThreshold;
3753
+ }
3754
+ if (passesFcThreshold && passesPThreshold) {
3755
+ status = yVal > 0 ? "up" : "down";
3756
+ }
3757
+ const label = aes.label ? String(row[aes.label] ?? "") : undefined;
3758
+ points.push({
3759
+ row,
3760
+ x: xVal,
3761
+ y: yVal,
3762
+ absM: Math.abs(yVal),
3763
+ status,
3764
+ label
3765
+ });
3766
+ }
3767
+ const lineColor = { r: 150, g: 150, b: 150, a: 0.7 };
3768
+ const startX = Math.round(scales.x.range[0]);
3769
+ const endX = Math.round(scales.x.range[1]);
3770
+ if (showBaseline) {
3771
+ const cy = Math.round(scales.y.map(0));
3772
+ for (let x = startX;x <= endX; x++) {
3773
+ canvas.drawChar(x, cy, "─", lineColor);
3774
+ }
3775
+ }
3776
+ if (showThresholds) {
3777
+ const cyUp = Math.round(scales.y.map(fcThreshold));
3778
+ const cyDown = Math.round(scales.y.map(-fcThreshold));
3779
+ for (let x = startX;x <= endX; x += 2) {
3780
+ canvas.drawChar(x, cyUp, "─", lineColor);
3781
+ canvas.drawChar(x, cyDown, "─", lineColor);
3782
+ }
3783
+ }
3784
+ for (const point of points) {
3785
+ if (point.status === "ns") {
3786
+ const cx = Math.round(scales.x.map(point.x));
3787
+ const cy = Math.round(scales.y.map(point.y));
3788
+ canvas.drawPoint(cx, cy, nsColor, pointChar);
3789
+ }
3790
+ }
3791
+ for (const point of points) {
3792
+ if (point.status !== "ns") {
3793
+ const cx = Math.round(scales.x.map(point.x));
3794
+ const cy = Math.round(scales.y.map(point.y));
3795
+ const color = point.status === "up" ? upColor : downColor;
3796
+ canvas.drawPoint(cx, cy, color, pointChar);
3797
+ }
3798
+ }
3799
+ if (nLabels > 0 && aes.label) {
3800
+ const significantPoints = points.filter((p) => p.status !== "ns" && p.label).sort((a, b) => b.absM - a.absM).slice(0, nLabels);
3711
3801
  const labelColor = { r: 50, g: 50, b: 50, a: 1 };
3712
3802
  for (const point of significantPoints) {
3713
3803
  const cx = Math.round(scales.x.map(point.x));
@@ -3721,6 +3811,1385 @@ function renderGeomVolcano(data, geom, aes, scales, canvas) {
3721
3811
  }
3722
3812
  }
3723
3813
  }
3814
+ function renderGeomManhattan(data, geom, aes, scales, canvas) {
3815
+ const params = geom.params || {};
3816
+ const suggestiveThreshold = Number(params.suggestive_threshold ?? 0.00001);
3817
+ const genomeWideThreshold = Number(params.genome_wide_threshold ?? 0.00000005);
3818
+ const yIsNegLog10 = Boolean(params.y_is_neglog10 ?? false);
3819
+ const chrColors = params.chr_colors ?? ["#1f78b4", "#a6cee3"];
3820
+ const highlightColor = String(params.highlight_color ?? "#e41a1c");
3821
+ const suggestiveColor = String(params.suggestive_color ?? "#ff7f00");
3822
+ const showThresholds = Boolean(params.show_thresholds ?? true);
3823
+ const nLabels = Number(params.n_labels ?? 0);
3824
+ const pointChar = String(params.point_char ?? "●");
3825
+ const chrGap = Number(params.chr_gap ?? 0.02);
3826
+ if (!Array.isArray(data) || data.length === 0)
3827
+ return;
3828
+ const parseHex = (hex) => {
3829
+ const r = parseInt(hex.slice(1, 3), 16);
3830
+ const g = parseInt(hex.slice(3, 5), 16);
3831
+ const b = parseInt(hex.slice(5, 7), 16);
3832
+ return { r, g, b, a: 1 };
3833
+ };
3834
+ const chrColorsParsed = chrColors.map((c) => parseHex(c));
3835
+ const highlightColorParsed = parseHex(highlightColor);
3836
+ const suggestiveColorParsed = parseHex(suggestiveColor);
3837
+ const suggestiveLine = -Math.log10(suggestiveThreshold);
3838
+ const genomeWideLine = -Math.log10(genomeWideThreshold);
3839
+ const xField = aes.x;
3840
+ const yField = aes.y;
3841
+ const labelField = aes.label;
3842
+ const points = [];
3843
+ const chrMap = new Map;
3844
+ for (const row of data) {
3845
+ let chr;
3846
+ let pos;
3847
+ const rawX = row[xField];
3848
+ const rawY = row[yField];
3849
+ if (typeof rawX === "string" && rawX.includes(":")) {
3850
+ const parts = rawX.split(":");
3851
+ chr = parts[0];
3852
+ pos = parseFloat(parts[1]);
3853
+ } else {
3854
+ chr = aes.color ? String(row[aes.color] ?? "1") : "1";
3855
+ pos = typeof rawX === "number" ? rawX : parseFloat(String(rawX));
3856
+ }
3857
+ const pval = typeof rawY === "number" ? rawY : parseFloat(String(rawY));
3858
+ if (isNaN(pos) || isNaN(pval) || pval <= 0)
3859
+ continue;
3860
+ const negLogP = yIsNegLog10 ? pval : -Math.log10(pval);
3861
+ const label = labelField ? String(row[labelField] ?? "") : undefined;
3862
+ const point = {
3863
+ chr,
3864
+ pos,
3865
+ pval: yIsNegLog10 ? Math.pow(10, -pval) : pval,
3866
+ negLogP,
3867
+ cumPos: 0,
3868
+ label,
3869
+ chrIndex: 0
3870
+ };
3871
+ if (!chrMap.has(chr)) {
3872
+ chrMap.set(chr, []);
3873
+ }
3874
+ chrMap.get(chr).push(point);
3875
+ points.push(point);
3876
+ }
3877
+ if (points.length === 0)
3878
+ return;
3879
+ const chrOrder = Array.from(chrMap.keys()).sort((a, b) => {
3880
+ const aNum = parseInt(String(a).replace(/^chr/i, ""));
3881
+ const bNum = parseInt(String(b).replace(/^chr/i, ""));
3882
+ if (!isNaN(aNum) && !isNaN(bNum))
3883
+ return aNum - bNum;
3884
+ if (!isNaN(aNum))
3885
+ return -1;
3886
+ if (!isNaN(bNum))
3887
+ return 1;
3888
+ return String(a).localeCompare(String(b));
3889
+ });
3890
+ let cumOffset = 0;
3891
+ const chrOffsets = new Map;
3892
+ for (let i = 0;i < chrOrder.length; i++) {
3893
+ const chr = chrOrder[i];
3894
+ chrOffsets.set(chr, cumOffset);
3895
+ const chrPoints = chrMap.get(chr);
3896
+ const maxPos = Math.max(...chrPoints.map((p) => p.pos));
3897
+ for (const point of chrPoints) {
3898
+ point.cumPos = cumOffset + point.pos;
3899
+ point.chrIndex = i;
3900
+ }
3901
+ cumOffset += maxPos * (1 + chrGap);
3902
+ }
3903
+ const minX = Math.min(...points.map((p) => p.cumPos));
3904
+ const maxX = Math.max(...points.map((p) => p.cumPos));
3905
+ const minY = 0;
3906
+ const maxY = Math.max(...points.map((p) => p.negLogP)) * 1.1;
3907
+ const plotLeft = Math.round(scales.x.range[0]);
3908
+ const plotRight = Math.round(scales.x.range[1]);
3909
+ const plotTop = Math.round(scales.y.range[1]);
3910
+ const plotBottom = Math.round(scales.y.range[0]);
3911
+ const mapX = (v) => plotLeft + (v - minX) / (maxX - minX) * (plotRight - plotLeft);
3912
+ const mapY = (v) => plotBottom - (v - minY) / (maxY - minY) * (plotBottom - plotTop);
3913
+ if (showThresholds) {
3914
+ const lineColor = { r: 150, g: 150, b: 150, a: 1 };
3915
+ if (suggestiveLine <= maxY) {
3916
+ const sy = Math.round(mapY(suggestiveLine));
3917
+ for (let x = plotLeft;x <= plotRight; x += 2) {
3918
+ canvas.drawChar(x, sy, "─", lineColor);
3919
+ }
3920
+ }
3921
+ if (genomeWideLine <= maxY) {
3922
+ const gy = Math.round(mapY(genomeWideLine));
3923
+ for (let x = plotLeft;x <= plotRight; x += 2) {
3924
+ canvas.drawChar(x, gy, "─", highlightColorParsed);
3925
+ }
3926
+ }
3927
+ }
3928
+ for (const point of points) {
3929
+ if (point.pval >= suggestiveThreshold) {
3930
+ const cx = Math.round(mapX(point.cumPos));
3931
+ const cy = Math.round(mapY(point.negLogP));
3932
+ const color = chrColorsParsed[point.chrIndex % chrColorsParsed.length];
3933
+ canvas.drawPoint(cx, cy, color, pointChar);
3934
+ }
3935
+ }
3936
+ for (const point of points) {
3937
+ if (point.pval < suggestiveThreshold && point.pval >= genomeWideThreshold) {
3938
+ const cx = Math.round(mapX(point.cumPos));
3939
+ const cy = Math.round(mapY(point.negLogP));
3940
+ canvas.drawPoint(cx, cy, suggestiveColorParsed, pointChar);
3941
+ }
3942
+ }
3943
+ for (const point of points) {
3944
+ if (point.pval < genomeWideThreshold) {
3945
+ const cx = Math.round(mapX(point.cumPos));
3946
+ const cy = Math.round(mapY(point.negLogP));
3947
+ canvas.drawPoint(cx, cy, highlightColorParsed, pointChar);
3948
+ }
3949
+ }
3950
+ if (nLabels > 0) {
3951
+ const labelColor = { r: 50, g: 50, b: 50, a: 1 };
3952
+ const topPoints = points.filter((p) => p.label && p.pval < suggestiveThreshold).sort((a, b) => a.pval - b.pval).slice(0, nLabels);
3953
+ for (const point of topPoints) {
3954
+ const cx = Math.round(mapX(point.cumPos));
3955
+ const cy = Math.round(mapY(point.negLogP));
3956
+ const label = point.label;
3957
+ for (let i = 0;i < label.length; i++) {
3958
+ canvas.drawChar(cx + 1 + i, cy, label[i], labelColor);
3959
+ }
3960
+ }
3961
+ }
3962
+ }
3963
+ function renderGeomHeatmap(data, geom, aes, scales, canvas) {
3964
+ const params = geom.params || {};
3965
+ const valueCol = String(params.value_col ?? "value");
3966
+ const lowColor = String(params.low_color ?? "#313695");
3967
+ const midColor = String(params.mid_color ?? "#ffffbf");
3968
+ const highColor = String(params.high_color ?? "#a50026");
3969
+ const naColor = String(params.na_color ?? "#808080");
3970
+ const clusterRows = Boolean(params.cluster_rows ?? false);
3971
+ const clusterCols = Boolean(params.cluster_cols ?? false);
3972
+ const showRowLabels = Boolean(params.show_row_labels ?? true);
3973
+ const showColLabels = Boolean(params.show_col_labels ?? true);
3974
+ const cellChar = String(params.cell_char ?? "█");
3975
+ const scaleMethod = String(params.scale ?? "none");
3976
+ if (!Array.isArray(data) || data.length === 0)
3977
+ return;
3978
+ const xField = typeof aes.x === "string" ? aes.x : "x";
3979
+ const yField = typeof aes.y === "string" ? aes.y : "y";
3980
+ const fillField = typeof aes.fill === "string" ? aes.fill : valueCol;
3981
+ const parseHex = (hex) => {
3982
+ const r = parseInt(hex.slice(1, 3), 16);
3983
+ const g = parseInt(hex.slice(3, 5), 16);
3984
+ const b = parseInt(hex.slice(5, 7), 16);
3985
+ return { r, g, b, a: 1 };
3986
+ };
3987
+ const lowRgb = parseHex(lowColor);
3988
+ const midRgb = parseHex(midColor);
3989
+ const highRgb = parseHex(highColor);
3990
+ const naRgb = parseHex(naColor);
3991
+ const rowSet = new Set;
3992
+ const colSet = new Set;
3993
+ const valueMap = new Map;
3994
+ for (const row of data) {
3995
+ const rowKey = String(row[yField] ?? "");
3996
+ const colKey = String(row[xField] ?? "");
3997
+ const val = row[fillField];
3998
+ if (rowKey && colKey) {
3999
+ rowSet.add(rowKey);
4000
+ colSet.add(colKey);
4001
+ if (typeof val === "number" && !isNaN(val)) {
4002
+ valueMap.set(`${rowKey}|${colKey}`, val);
4003
+ }
4004
+ }
4005
+ }
4006
+ let rowKeys = Array.from(rowSet);
4007
+ let colKeys = Array.from(colSet);
4008
+ if (rowKeys.length === 0 || colKeys.length === 0)
4009
+ return;
4010
+ const clusterOrder = (keys, getDistance) => {
4011
+ if (keys.length <= 2)
4012
+ return keys;
4013
+ const remaining = [...keys];
4014
+ const result = [];
4015
+ let minAvg = Infinity;
4016
+ let startIdx = 0;
4017
+ for (let i = 0;i < remaining.length; i++) {
4018
+ let sum = 0;
4019
+ for (let j = 0;j < remaining.length; j++) {
4020
+ if (i !== j)
4021
+ sum += getDistance(remaining[i], remaining[j]);
4022
+ }
4023
+ const avg = sum / (remaining.length - 1);
4024
+ if (avg < minAvg) {
4025
+ minAvg = avg;
4026
+ startIdx = i;
4027
+ }
4028
+ }
4029
+ result.push(remaining.splice(startIdx, 1)[0]);
4030
+ while (remaining.length > 0) {
4031
+ let minDist = Infinity;
4032
+ let minIdx = 0;
4033
+ for (let i = 0;i < remaining.length; i++) {
4034
+ const dist = getDistance(result[result.length - 1], remaining[i]);
4035
+ if (dist < minDist) {
4036
+ minDist = dist;
4037
+ minIdx = i;
4038
+ }
4039
+ }
4040
+ result.push(remaining.splice(minIdx, 1)[0]);
4041
+ }
4042
+ return result;
4043
+ };
4044
+ if (clusterRows) {
4045
+ const rowDistance = (a, b) => {
4046
+ let sum = 0;
4047
+ let count = 0;
4048
+ for (const col of colKeys) {
4049
+ const va = valueMap.get(`${a}|${col}`);
4050
+ const vb = valueMap.get(`${b}|${col}`);
4051
+ if (va !== undefined && vb !== undefined) {
4052
+ sum += (va - vb) ** 2;
4053
+ count++;
4054
+ }
4055
+ }
4056
+ return count > 0 ? Math.sqrt(sum / count) : Infinity;
4057
+ };
4058
+ rowKeys = clusterOrder(rowKeys, rowDistance);
4059
+ }
4060
+ if (clusterCols) {
4061
+ const colDistance = (a, b) => {
4062
+ let sum = 0;
4063
+ let count = 0;
4064
+ for (const row of rowKeys) {
4065
+ const va = valueMap.get(`${row}|${a}`);
4066
+ const vb = valueMap.get(`${row}|${b}`);
4067
+ if (va !== undefined && vb !== undefined) {
4068
+ sum += (va - vb) ** 2;
4069
+ count++;
4070
+ }
4071
+ }
4072
+ return count > 0 ? Math.sqrt(sum / count) : Infinity;
4073
+ };
4074
+ colKeys = clusterOrder(colKeys, colDistance);
4075
+ }
4076
+ const values = Array.from(valueMap.values());
4077
+ let minVal = Math.min(...values);
4078
+ let maxVal = Math.max(...values);
4079
+ const scaledValues = new Map;
4080
+ if (scaleMethod === "row") {
4081
+ for (const rowKey of rowKeys) {
4082
+ const rowVals = colKeys.map((c) => valueMap.get(`${rowKey}|${c}`)).filter((v) => v !== undefined);
4083
+ if (rowVals.length > 0) {
4084
+ const mean = rowVals.reduce((a, b) => a + b, 0) / rowVals.length;
4085
+ const std = Math.sqrt(rowVals.reduce((a, b) => a + (b - mean) ** 2, 0) / rowVals.length) || 1;
4086
+ for (const colKey of colKeys) {
4087
+ const v = valueMap.get(`${rowKey}|${colKey}`);
4088
+ if (v !== undefined) {
4089
+ scaledValues.set(`${rowKey}|${colKey}`, (v - mean) / std);
4090
+ }
4091
+ }
4092
+ }
4093
+ }
4094
+ } else if (scaleMethod === "column") {
4095
+ for (const colKey of colKeys) {
4096
+ const colVals = rowKeys.map((r) => valueMap.get(`${r}|${colKey}`)).filter((v) => v !== undefined);
4097
+ if (colVals.length > 0) {
4098
+ const mean = colVals.reduce((a, b) => a + b, 0) / colVals.length;
4099
+ const std = Math.sqrt(colVals.reduce((a, b) => a + (b - mean) ** 2, 0) / colVals.length) || 1;
4100
+ for (const rowKey of rowKeys) {
4101
+ const v = valueMap.get(`${rowKey}|${colKey}`);
4102
+ if (v !== undefined) {
4103
+ scaledValues.set(`${rowKey}|${colKey}`, (v - mean) / std);
4104
+ }
4105
+ }
4106
+ }
4107
+ }
4108
+ }
4109
+ const finalValues = scaleMethod === "none" ? valueMap : scaledValues;
4110
+ if (scaleMethod !== "none") {
4111
+ const scaled = Array.from(finalValues.values());
4112
+ minVal = Math.min(...scaled);
4113
+ maxVal = Math.max(...scaled);
4114
+ }
4115
+ const interpolateColor2 = (val) => {
4116
+ if (isNaN(val))
4117
+ return naRgb;
4118
+ const t = (val - minVal) / (maxVal - minVal || 1);
4119
+ if (t <= 0.5) {
4120
+ const t2 = t * 2;
4121
+ return {
4122
+ r: Math.round(lowRgb.r + (midRgb.r - lowRgb.r) * t2),
4123
+ g: Math.round(lowRgb.g + (midRgb.g - lowRgb.g) * t2),
4124
+ b: Math.round(lowRgb.b + (midRgb.b - lowRgb.b) * t2),
4125
+ a: 1
4126
+ };
4127
+ } else {
4128
+ const t2 = (t - 0.5) * 2;
4129
+ return {
4130
+ r: Math.round(midRgb.r + (highRgb.r - midRgb.r) * t2),
4131
+ g: Math.round(midRgb.g + (highRgb.g - midRgb.g) * t2),
4132
+ b: Math.round(midRgb.b + (highRgb.b - midRgb.b) * t2),
4133
+ a: 1
4134
+ };
4135
+ }
4136
+ };
4137
+ const plotLeft = Math.round(scales.x.range[0]);
4138
+ const plotRight = Math.round(scales.x.range[1]);
4139
+ const plotTop = Math.round(scales.y.range[1]);
4140
+ const plotBottom = Math.round(scales.y.range[0]);
4141
+ const labelWidth = showRowLabels ? Math.min(10, Math.max(...rowKeys.map((k) => k.length))) + 1 : 0;
4142
+ const labelHeight = showColLabels ? 1 : 0;
4143
+ const availWidth = plotRight - plotLeft - labelWidth;
4144
+ const availHeight = plotBottom - plotTop - labelHeight;
4145
+ const cellWidth = Math.max(1, Math.floor(availWidth / colKeys.length));
4146
+ const cellHeight = Math.max(1, Math.floor(availHeight / rowKeys.length));
4147
+ for (let ri = 0;ri < rowKeys.length; ri++) {
4148
+ const rowKey = rowKeys[ri];
4149
+ const baseY = plotTop + labelHeight + ri * cellHeight;
4150
+ for (let ci = 0;ci < colKeys.length; ci++) {
4151
+ const colKey = colKeys[ci];
4152
+ const baseX = plotLeft + labelWidth + ci * cellWidth;
4153
+ const val = finalValues.get(`${rowKey}|${colKey}`);
4154
+ const color = val !== undefined ? interpolateColor2(val) : naRgb;
4155
+ for (let dy = 0;dy < cellHeight; dy++) {
4156
+ for (let dx = 0;dx < cellWidth; dx++) {
4157
+ canvas.drawChar(baseX + dx, baseY + dy, cellChar, color);
4158
+ }
4159
+ }
4160
+ }
4161
+ }
4162
+ if (showRowLabels) {
4163
+ const labelColor = { r: 180, g: 180, b: 180, a: 1 };
4164
+ for (let ri = 0;ri < rowKeys.length; ri++) {
4165
+ const label = rowKeys[ri].slice(0, labelWidth - 1);
4166
+ const y = plotTop + labelHeight + ri * cellHeight + Math.floor(cellHeight / 2);
4167
+ for (let i = 0;i < label.length; i++) {
4168
+ canvas.drawChar(plotLeft + i, y, label[i], labelColor);
4169
+ }
4170
+ }
4171
+ }
4172
+ if (showColLabels) {
4173
+ const labelColor = { r: 180, g: 180, b: 180, a: 1 };
4174
+ for (let ci = 0;ci < colKeys.length; ci++) {
4175
+ const label = colKeys[ci].slice(0, cellWidth);
4176
+ const x = plotLeft + labelWidth + ci * cellWidth + Math.floor(cellWidth / 2);
4177
+ for (let i = 0;i < Math.min(label.length, 1); i++) {
4178
+ canvas.drawChar(x, plotTop + i, label[i], labelColor);
4179
+ }
4180
+ }
4181
+ }
4182
+ }
4183
+ function renderGeomBiplot(data, geom, aes, scales, canvas) {
4184
+ const params = geom.params || {};
4185
+ const pc1Col = params.pc1_col ?? "PC1";
4186
+ const pc2Col = params.pc2_col ?? "PC2";
4187
+ const loadings = params.loadings;
4188
+ const showScores = params.show_scores ?? true;
4189
+ const scoreChar = String(params.score_char ?? "●");
4190
+ const showScoreLabels = params.show_score_labels ?? false;
4191
+ const showLoadings = params.show_loadings ?? true;
4192
+ const loadingColor = String(params.loading_color ?? "#e41a1c");
4193
+ const loadingScale = params.loading_scale;
4194
+ const showLoadingLabels = params.show_loading_labels ?? true;
4195
+ const showOrigin = params.show_origin ?? true;
4196
+ const originColor = String(params.origin_color ?? "#999999");
4197
+ if (!Array.isArray(data) || data.length === 0)
4198
+ return;
4199
+ const parseHex = (hex) => {
4200
+ const r = parseInt(hex.slice(1, 3), 16);
4201
+ const g = parseInt(hex.slice(3, 5), 16);
4202
+ const b = parseInt(hex.slice(5, 7), 16);
4203
+ return { r, g, b, a: 1 };
4204
+ };
4205
+ const loadingColorParsed = parseHex(loadingColor);
4206
+ const originColorParsed = parseHex(originColor);
4207
+ const scores = [];
4208
+ const xField = typeof aes.x === "string" ? aes.x : pc1Col;
4209
+ const yField = typeof aes.y === "string" ? aes.y : pc2Col;
4210
+ const labelField = typeof aes.label === "string" ? aes.label : undefined;
4211
+ const colorField = typeof aes.color === "string" ? aes.color : undefined;
4212
+ for (const row of data) {
4213
+ const rawPc1 = row[xField];
4214
+ const rawPc2 = row[yField];
4215
+ const pc1 = typeof rawPc1 === "number" ? rawPc1 : parseFloat(String(rawPc1));
4216
+ const pc2 = typeof rawPc2 === "number" ? rawPc2 : parseFloat(String(rawPc2));
4217
+ if (!isNaN(pc1) && !isNaN(pc2)) {
4218
+ const point = { pc1, pc2 };
4219
+ if (labelField)
4220
+ point.label = String(row[labelField] ?? "");
4221
+ if (colorField && scales.color) {
4222
+ point.color = scales.color.map(row[colorField]);
4223
+ }
4224
+ scores.push(point);
4225
+ }
4226
+ }
4227
+ if (scores.length === 0)
4228
+ return;
4229
+ let minX = Math.min(...scores.map((s) => s.pc1));
4230
+ let maxX = Math.max(...scores.map((s) => s.pc1));
4231
+ let minY = Math.min(...scores.map((s) => s.pc2));
4232
+ let maxY = Math.max(...scores.map((s) => s.pc2));
4233
+ let actualLoadingScale = loadingScale;
4234
+ if (loadings && loadings.length > 0 && !actualLoadingScale) {
4235
+ const maxLoading = Math.max(...loadings.map((l) => Math.sqrt(l.pc1 ** 2 + l.pc2 ** 2)));
4236
+ const maxScore = Math.max(Math.abs(minX), Math.abs(maxX), Math.abs(minY), Math.abs(maxY));
4237
+ actualLoadingScale = maxScore * 0.8 / (maxLoading || 1);
4238
+ }
4239
+ if (loadings && actualLoadingScale) {
4240
+ for (const l of loadings) {
4241
+ const lx = l.pc1 * actualLoadingScale;
4242
+ const ly = l.pc2 * actualLoadingScale;
4243
+ minX = Math.min(minX, lx);
4244
+ maxX = Math.max(maxX, lx);
4245
+ minY = Math.min(minY, ly);
4246
+ maxY = Math.max(maxY, ly);
4247
+ }
4248
+ }
4249
+ const rangeX = maxX - minX || 1;
4250
+ const rangeY = maxY - minY || 1;
4251
+ minX -= rangeX * 0.1;
4252
+ maxX += rangeX * 0.1;
4253
+ minY -= rangeY * 0.1;
4254
+ maxY += rangeY * 0.1;
4255
+ const plotLeft = Math.round(scales.x.range[0]);
4256
+ const plotRight = Math.round(scales.x.range[1]);
4257
+ const plotTop = Math.round(scales.y.range[1]);
4258
+ const plotBottom = Math.round(scales.y.range[0]);
4259
+ const mapX = (v) => plotLeft + (v - minX) / (maxX - minX) * (plotRight - plotLeft);
4260
+ const mapY = (v) => plotBottom - (v - minY) / (maxY - minY) * (plotBottom - plotTop);
4261
+ if (showOrigin && minX <= 0 && maxX >= 0 && minY <= 0 && maxY >= 0) {
4262
+ const originX = Math.round(mapX(0));
4263
+ const originY = Math.round(mapY(0));
4264
+ for (let x = plotLeft;x <= plotRight; x++) {
4265
+ canvas.drawChar(x, originY, "─", originColorParsed);
4266
+ }
4267
+ for (let y = plotTop;y <= plotBottom; y++) {
4268
+ canvas.drawChar(originX, y, "│", originColorParsed);
4269
+ }
4270
+ canvas.drawChar(originX, originY, "┼", originColorParsed);
4271
+ }
4272
+ if (showLoadings && loadings && actualLoadingScale) {
4273
+ for (const loading of loadings) {
4274
+ const endX = loading.pc1 * actualLoadingScale;
4275
+ const endY = loading.pc2 * actualLoadingScale;
4276
+ const sx = Math.round(mapX(0));
4277
+ const sy = Math.round(mapY(0));
4278
+ const ex = Math.round(mapX(endX));
4279
+ const ey = Math.round(mapY(endY));
4280
+ const steps = Math.max(Math.abs(ex - sx), Math.abs(ey - sy));
4281
+ for (let i = 0;i <= steps; i++) {
4282
+ const t = steps > 0 ? i / steps : 0;
4283
+ const px = Math.round(sx + (ex - sx) * t);
4284
+ const py = Math.round(sy + (ey - sy) * t);
4285
+ const dx = ex - sx;
4286
+ const dy = ey - sy;
4287
+ let char = "·";
4288
+ if (Math.abs(dx) > Math.abs(dy) * 2) {
4289
+ char = dx > 0 ? "─" : "─";
4290
+ } else if (Math.abs(dy) > Math.abs(dx) * 2) {
4291
+ char = "│";
4292
+ } else if (dx > 0 && dy < 0 || dx < 0 && dy > 0) {
4293
+ char = "/";
4294
+ } else {
4295
+ char = "\\";
4296
+ }
4297
+ canvas.drawChar(px, py, char, loadingColorParsed);
4298
+ }
4299
+ const angle = Math.atan2(ey - sy, ex - sx);
4300
+ let arrowChar = "→";
4301
+ if (angle > Math.PI * 3 / 4 || angle < -Math.PI * 3 / 4)
4302
+ arrowChar = "←";
4303
+ else if (angle > Math.PI / 4)
4304
+ arrowChar = "↓";
4305
+ else if (angle < -Math.PI / 4)
4306
+ arrowChar = "↑";
4307
+ canvas.drawChar(ex, ey, arrowChar, loadingColorParsed);
4308
+ if (showLoadingLabels) {
4309
+ const labelX = ex + (ex >= sx ? 1 : -loading.variable.length);
4310
+ for (let i = 0;i < loading.variable.length; i++) {
4311
+ canvas.drawChar(labelX + i, ey, loading.variable[i], loadingColorParsed);
4312
+ }
4313
+ }
4314
+ }
4315
+ }
4316
+ if (showScores) {
4317
+ const defaultColor = { r: 31, g: 120, b: 180, a: 1 };
4318
+ for (const score of scores) {
4319
+ const cx = Math.round(mapX(score.pc1));
4320
+ const cy = Math.round(mapY(score.pc2));
4321
+ const color = score.color ?? defaultColor;
4322
+ canvas.drawPoint(cx, cy, color, scoreChar);
4323
+ if (showScoreLabels && score.label) {
4324
+ const labelColor = { r: 50, g: 50, b: 50, a: 1 };
4325
+ for (let i = 0;i < score.label.length; i++) {
4326
+ canvas.drawChar(cx + 1 + i, cy, score.label[i], labelColor);
4327
+ }
4328
+ }
4329
+ }
4330
+ }
4331
+ }
4332
+ function renderGeomKaplanMeier(data, geom, aes, scales, canvas) {
4333
+ const params = geom.params || {};
4334
+ const showCensored = Boolean(params.show_censored ?? true);
4335
+ const censorChar = String(params.censor_char ?? "+");
4336
+ const showMedian = Boolean(params.show_median ?? false);
4337
+ if (!Array.isArray(data) || data.length === 0)
4338
+ return;
4339
+ const xField = typeof aes.x === "string" ? aes.x : "time";
4340
+ const yField = typeof aes.y === "string" ? aes.y : "status";
4341
+ const colorField = typeof aes.color === "string" ? aes.color : undefined;
4342
+ const groups = new Map;
4343
+ for (const row of data) {
4344
+ const time = Number(row[xField] ?? 0);
4345
+ const status = Number(row[yField] ?? 0);
4346
+ const group = colorField ? String(row[colorField] ?? "default") : "default";
4347
+ if (!groups.has(group))
4348
+ groups.set(group, []);
4349
+ groups.get(group).push({ time, status });
4350
+ }
4351
+ const colors = [
4352
+ { r: 31, g: 119, b: 180, a: 1 },
4353
+ { r: 255, g: 127, b: 14, a: 1 },
4354
+ { r: 44, g: 160, b: 44, a: 1 },
4355
+ { r: 214, g: 39, b: 40, a: 1 },
4356
+ { r: 148, g: 103, b: 189, a: 1 }
4357
+ ];
4358
+ const plotLeft = Math.round(scales.x.range[0]);
4359
+ const plotRight = Math.round(scales.x.range[1]);
4360
+ const plotTop = Math.round(scales.y.range[1]);
4361
+ const plotBottom = Math.round(scales.y.range[0]);
4362
+ let maxTime = 0;
4363
+ for (const [, events] of groups) {
4364
+ for (const e of events) {
4365
+ if (e.time > maxTime)
4366
+ maxTime = e.time;
4367
+ }
4368
+ }
4369
+ const mapX = (t) => plotLeft + t / maxTime * (plotRight - plotLeft);
4370
+ const mapY = (s) => plotBottom - s * (plotBottom - plotTop);
4371
+ let colorIndex = 0;
4372
+ for (const [, events] of groups) {
4373
+ const color = colors[colorIndex % colors.length];
4374
+ colorIndex++;
4375
+ events.sort((a, b) => a.time - b.time);
4376
+ const n = events.length;
4377
+ let survival = 1;
4378
+ let atRisk = n;
4379
+ const survivalCurve = [];
4380
+ survivalCurve.push({ time: 0, survival: 1, censored: false });
4381
+ for (const event of events) {
4382
+ if (event.status === 1) {
4383
+ survival *= (atRisk - 1) / atRisk;
4384
+ survivalCurve.push({ time: event.time, survival, censored: false });
4385
+ } else {
4386
+ survivalCurve.push({ time: event.time, survival, censored: true });
4387
+ }
4388
+ atRisk--;
4389
+ }
4390
+ for (let i = 0;i < survivalCurve.length; i++) {
4391
+ const point = survivalCurve[i];
4392
+ const x = Math.round(mapX(point.time));
4393
+ const y = Math.round(mapY(point.survival));
4394
+ if (i > 0) {
4395
+ const prevPoint = survivalCurve[i - 1];
4396
+ const px = Math.round(mapX(prevPoint.time));
4397
+ const py = Math.round(mapY(prevPoint.survival));
4398
+ for (let hx = px;hx <= x; hx++) {
4399
+ canvas.drawChar(hx, py, "─", color);
4400
+ }
4401
+ if (py !== y) {
4402
+ for (let vy = Math.min(py, y);vy <= Math.max(py, y); vy++) {
4403
+ canvas.drawChar(x, vy, "│", color);
4404
+ }
4405
+ }
4406
+ }
4407
+ if (point.censored && showCensored) {
4408
+ canvas.drawChar(x, y, censorChar, color);
4409
+ }
4410
+ }
4411
+ if (showMedian) {
4412
+ const medianY = mapY(0.5);
4413
+ for (let mx = plotLeft;mx <= plotRight; mx += 2) {
4414
+ canvas.drawChar(mx, Math.round(medianY), "·", { r: 150, g: 150, b: 150, a: 1 });
4415
+ }
4416
+ }
4417
+ }
4418
+ }
4419
+ function renderGeomForest(data, geom, aes, scales, canvas) {
4420
+ const params = geom.params || {};
4421
+ const nullLine = Number(params.null_line ?? 1);
4422
+ const logScale = Boolean(params.log_scale ?? false);
4423
+ const nullLineColor = String(params.null_line_color ?? "#888888");
4424
+ const pointChar = String(params.point_char ?? "■");
4425
+ if (!Array.isArray(data) || data.length === 0)
4426
+ return;
4427
+ const parseHex = (hex) => {
4428
+ const r = parseInt(hex.slice(1, 3), 16);
4429
+ const g = parseInt(hex.slice(3, 5), 16);
4430
+ const b = parseInt(hex.slice(5, 7), 16);
4431
+ return { r, g, b, a: 1 };
4432
+ };
4433
+ const nullColor = parseHex(nullLineColor);
4434
+ const xField = typeof aes.x === "string" ? aes.x : "estimate";
4435
+ const yField = typeof aes.y === "string" ? aes.y : "study";
4436
+ const xminField = typeof aes.xmin === "string" ? aes.xmin : "ci_lower";
4437
+ const xmaxField = typeof aes.xmax === "string" ? aes.xmax : "ci_upper";
4438
+ const sizeField = typeof aes.size === "string" ? aes.size : undefined;
4439
+ const rows = [];
4440
+ let minWeight = Infinity;
4441
+ let maxWeight = -Infinity;
4442
+ for (const row of data) {
4443
+ const estimate = Number(row[xField] ?? 0);
4444
+ const ci_lower = Number(row[xminField] ?? estimate);
4445
+ const ci_upper = Number(row[xmaxField] ?? estimate);
4446
+ const study = String(row[yField] ?? "");
4447
+ const weight = sizeField ? Number(row[sizeField] ?? 1) : 1;
4448
+ if (weight < minWeight)
4449
+ minWeight = weight;
4450
+ if (weight > maxWeight)
4451
+ maxWeight = weight;
4452
+ rows.push({ study, estimate, ci_lower, ci_upper, weight });
4453
+ }
4454
+ const plotLeft = Math.round(scales.x.range[0]);
4455
+ const plotRight = Math.round(scales.x.range[1]);
4456
+ const plotTop = Math.round(scales.y.range[1]);
4457
+ const plotBottom = Math.round(scales.y.range[0]);
4458
+ let xMin = Math.min(...rows.map((r) => r.ci_lower), nullLine);
4459
+ let xMax = Math.max(...rows.map((r) => r.ci_upper), nullLine);
4460
+ if (logScale) {
4461
+ xMin = Math.log10(Math.max(xMin, 0.001));
4462
+ xMax = Math.log10(Math.max(xMax, 0.001));
4463
+ }
4464
+ const mapX = (v) => {
4465
+ const val = logScale ? Math.log10(Math.max(v, 0.001)) : v;
4466
+ return plotLeft + (val - xMin) / (xMax - xMin) * (plotRight - plotLeft);
4467
+ };
4468
+ const nullX = Math.round(mapX(nullLine));
4469
+ for (let y = plotTop;y <= plotBottom; y++) {
4470
+ if ((y - plotTop) % 2 === 0) {
4471
+ canvas.drawChar(nullX, y, "│", nullColor);
4472
+ }
4473
+ }
4474
+ const rowHeight = (plotBottom - plotTop) / rows.length;
4475
+ const pointColor = { r: 31, g: 119, b: 180, a: 1 };
4476
+ const ciColor = { r: 80, g: 80, b: 80, a: 1 };
4477
+ for (let i = 0;i < rows.length; i++) {
4478
+ const row = rows[i];
4479
+ const y = Math.round(plotTop + (i + 0.5) * rowHeight);
4480
+ const x1 = Math.round(mapX(row.ci_lower));
4481
+ const x2 = Math.round(mapX(row.ci_upper));
4482
+ for (let x = x1;x <= x2; x++) {
4483
+ canvas.drawChar(x, y, "─", ciColor);
4484
+ }
4485
+ canvas.drawChar(x1, y, "├", ciColor);
4486
+ canvas.drawChar(x2, y, "┤", ciColor);
4487
+ const px = Math.round(mapX(row.estimate));
4488
+ canvas.drawChar(px, y, pointChar, pointColor);
4489
+ const label = row.study;
4490
+ const labelColor = { r: 200, g: 200, b: 200, a: 1 };
4491
+ const labelEnd = plotLeft - 1;
4492
+ const labelStart = labelEnd - label.length;
4493
+ for (let c = 0;c < label.length; c++) {
4494
+ const charX = labelStart + c;
4495
+ if (charX >= 0) {
4496
+ canvas.drawChar(charX, y, label[c], labelColor);
4497
+ }
4498
+ }
4499
+ }
4500
+ }
4501
+ function renderGeomRoc(data, geom, aes, scales, canvas) {
4502
+ const params = geom.params || {};
4503
+ const showDiagonal = Boolean(params.show_diagonal ?? true);
4504
+ const diagonalColor = String(params.diagonal_color ?? "#888888");
4505
+ const showAuc = Boolean(params.show_auc ?? true);
4506
+ const showOptimal = Boolean(params.show_optimal ?? false);
4507
+ const optimalChar = String(params.optimal_char ?? "●");
4508
+ if (!Array.isArray(data) || data.length === 0)
4509
+ return;
4510
+ const parseHex = (hex) => {
4511
+ const r = parseInt(hex.slice(1, 3), 16);
4512
+ const g = parseInt(hex.slice(3, 5), 16);
4513
+ const b = parseInt(hex.slice(5, 7), 16);
4514
+ return { r, g, b, a: 1 };
4515
+ };
4516
+ const diagColor = parseHex(diagonalColor);
4517
+ const xField = typeof aes.x === "string" ? aes.x : "fpr";
4518
+ const yField = typeof aes.y === "string" ? aes.y : "tpr";
4519
+ const colorField = typeof aes.color === "string" ? aes.color : undefined;
4520
+ const groups = new Map;
4521
+ for (const row of data) {
4522
+ const fpr = Number(row[xField] ?? 0);
4523
+ const tpr = Number(row[yField] ?? 0);
4524
+ const group = colorField ? String(row[colorField] ?? "default") : "default";
4525
+ if (!groups.has(group))
4526
+ groups.set(group, []);
4527
+ groups.get(group).push({ fpr, tpr });
4528
+ }
4529
+ const plotLeft = Math.round(scales.x.range[0]);
4530
+ const plotRight = Math.round(scales.x.range[1]);
4531
+ const plotTop = Math.round(scales.y.range[1]);
4532
+ const plotBottom = Math.round(scales.y.range[0]);
4533
+ const mapX = (v) => plotLeft + v * (plotRight - plotLeft);
4534
+ const mapY = (v) => plotBottom - v * (plotBottom - plotTop);
4535
+ if (showDiagonal) {
4536
+ const steps = plotRight - plotLeft;
4537
+ for (let i = 0;i <= steps; i += 2) {
4538
+ const t = i / steps;
4539
+ const x = Math.round(mapX(t));
4540
+ const y = Math.round(mapY(t));
4541
+ canvas.drawChar(x, y, "·", diagColor);
4542
+ }
4543
+ }
4544
+ const colors = [
4545
+ { r: 31, g: 119, b: 180, a: 1 },
4546
+ { r: 255, g: 127, b: 14, a: 1 },
4547
+ { r: 44, g: 160, b: 44, a: 1 },
4548
+ { r: 214, g: 39, b: 40, a: 1 }
4549
+ ];
4550
+ let colorIndex = 0;
4551
+ for (const [, points] of groups) {
4552
+ const color = colors[colorIndex % colors.length];
4553
+ colorIndex++;
4554
+ points.sort((a, b) => a.fpr - b.fpr);
4555
+ let auc = 0;
4556
+ for (let i = 1;i < points.length; i++) {
4557
+ const dx = points[i].fpr - points[i - 1].fpr;
4558
+ const avgY = (points[i].tpr + points[i - 1].tpr) / 2;
4559
+ auc += dx * avgY;
4560
+ }
4561
+ let optimalPoint = points[0];
4562
+ let maxJ = -Infinity;
4563
+ for (const p of points) {
4564
+ const j = p.tpr - p.fpr;
4565
+ if (j > maxJ) {
4566
+ maxJ = j;
4567
+ optimalPoint = p;
4568
+ }
4569
+ }
4570
+ for (let i = 0;i < points.length; i++) {
4571
+ const p = points[i];
4572
+ const x = Math.round(mapX(p.fpr));
4573
+ const y = Math.round(mapY(p.tpr));
4574
+ if (i > 0) {
4575
+ const prev = points[i - 1];
4576
+ const px = Math.round(mapX(prev.fpr));
4577
+ const py = Math.round(mapY(prev.tpr));
4578
+ const steps = Math.max(Math.abs(x - px), Math.abs(y - py));
4579
+ for (let s = 0;s <= steps; s++) {
4580
+ const t = steps > 0 ? s / steps : 0;
4581
+ const lx = Math.round(px + (x - px) * t);
4582
+ const ly = Math.round(py + (y - py) * t);
4583
+ canvas.drawChar(lx, ly, "─", color);
4584
+ }
4585
+ }
4586
+ canvas.drawChar(x, y, "●", color);
4587
+ }
4588
+ if (showOptimal) {
4589
+ const ox = Math.round(mapX(optimalPoint.fpr));
4590
+ const oy = Math.round(mapY(optimalPoint.tpr));
4591
+ canvas.drawChar(ox, oy, optimalChar, { r: 255, g: 0, b: 0, a: 1 });
4592
+ }
4593
+ if (showAuc && colorIndex === 1) {
4594
+ const aucText = `AUC=${auc.toFixed(3)}`;
4595
+ const labelColor = { r: 100, g: 100, b: 100, a: 1 };
4596
+ for (let i = 0;i < aucText.length; i++) {
4597
+ canvas.drawChar(plotRight - aucText.length + i, plotTop + 1, aucText[i], labelColor);
4598
+ }
4599
+ }
4600
+ }
4601
+ }
4602
+ function renderGeomBlandAltman(data, geom, aes, scales, canvas) {
4603
+ const params = geom.params || {};
4604
+ const showLimits = Boolean(params.show_limits ?? true);
4605
+ const showBias = Boolean(params.show_bias ?? true);
4606
+ const limitMultiplier = Number(params.limit_multiplier ?? 1.96);
4607
+ const biasColor = String(params.bias_color ?? "#0000ff");
4608
+ const limitColor = String(params.limit_color ?? "#ff0000");
4609
+ const pointChar = String(params.point_char ?? "●");
4610
+ const precomputed = Boolean(params.precomputed ?? false);
4611
+ if (!Array.isArray(data) || data.length === 0)
4612
+ return;
4613
+ const parseHex = (hex) => {
4614
+ const r = parseInt(hex.slice(1, 3), 16);
4615
+ const g = parseInt(hex.slice(3, 5), 16);
4616
+ const b = parseInt(hex.slice(5, 7), 16);
4617
+ return { r, g, b, a: 1 };
4618
+ };
4619
+ const biasColorParsed = parseHex(biasColor);
4620
+ const limitColorParsed = parseHex(limitColor);
4621
+ const xField = typeof aes.x === "string" ? aes.x : "method1";
4622
+ const yField = typeof aes.y === "string" ? aes.y : "method2";
4623
+ const points = [];
4624
+ if (precomputed) {
4625
+ for (const row of data) {
4626
+ const mean = Number(row[xField] ?? 0);
4627
+ const diff = Number(row[yField] ?? 0);
4628
+ points.push({ mean, diff });
4629
+ }
4630
+ } else {
4631
+ for (const row of data) {
4632
+ const m1 = Number(row[xField] ?? 0);
4633
+ const m2 = Number(row[yField] ?? 0);
4634
+ const mean = (m1 + m2) / 2;
4635
+ const diff = m1 - m2;
4636
+ points.push({ mean, diff });
4637
+ }
4638
+ }
4639
+ if (points.length === 0)
4640
+ return;
4641
+ const diffs = points.map((p) => p.diff);
4642
+ const bias = diffs.reduce((a, b) => a + b, 0) / diffs.length;
4643
+ const variance = diffs.reduce((a, b) => a + Math.pow(b - bias, 2), 0) / (diffs.length - 1);
4644
+ const sd = Math.sqrt(variance);
4645
+ const upperLimit = bias + limitMultiplier * sd;
4646
+ const lowerLimit = bias - limitMultiplier * sd;
4647
+ const plotLeft = Math.round(scales.x.range[0]);
4648
+ const plotRight = Math.round(scales.x.range[1]);
4649
+ const plotTop = Math.round(scales.y.range[1]);
4650
+ const plotBottom = Math.round(scales.y.range[0]);
4651
+ const minMean = Math.min(...points.map((p) => p.mean));
4652
+ const maxMean = Math.max(...points.map((p) => p.mean));
4653
+ const minDiff = Math.min(...points.map((p) => p.diff), lowerLimit);
4654
+ const maxDiff = Math.max(...points.map((p) => p.diff), upperLimit);
4655
+ const mapX = (v) => plotLeft + (v - minMean) / (maxMean - minMean) * (plotRight - plotLeft);
4656
+ const mapY = (v) => plotBottom - (v - minDiff) / (maxDiff - minDiff) * (plotBottom - plotTop);
4657
+ if (showBias) {
4658
+ const biasY = Math.round(mapY(bias));
4659
+ for (let x = plotLeft;x <= plotRight; x++) {
4660
+ canvas.drawChar(x, biasY, "─", biasColorParsed);
4661
+ }
4662
+ }
4663
+ if (showLimits) {
4664
+ const upperY = Math.round(mapY(upperLimit));
4665
+ const lowerY = Math.round(mapY(lowerLimit));
4666
+ for (let x = plotLeft;x <= plotRight; x += 2) {
4667
+ canvas.drawChar(x, upperY, "─", limitColorParsed);
4668
+ canvas.drawChar(x, lowerY, "─", limitColorParsed);
4669
+ }
4670
+ }
4671
+ const pointColor = { r: 31, g: 119, b: 180, a: 1 };
4672
+ for (const p of points) {
4673
+ const x = Math.round(mapX(p.mean));
4674
+ const y = Math.round(mapY(p.diff));
4675
+ canvas.drawChar(x, y, pointChar, pointColor);
4676
+ }
4677
+ }
4678
+ function renderGeomQQ(data, geom, aes, scales, canvas) {
4679
+ const params = geom.params || {};
4680
+ const showLine = params.show_line ?? true;
4681
+ const lineColor = params.line_color ?? "#ff0000";
4682
+ const pointChar = params.point_char ?? "●";
4683
+ const standardize = params.standardize ?? true;
4684
+ const parseHex = (hex) => {
4685
+ const r = parseInt(hex.slice(1, 3), 16);
4686
+ const g = parseInt(hex.slice(3, 5), 16);
4687
+ const b = parseInt(hex.slice(5, 7), 16);
4688
+ return { r, g, b, a: 1 };
4689
+ };
4690
+ const lineColorParsed = parseHex(lineColor);
4691
+ const sampleField = typeof aes.x === "string" ? aes.x : "x";
4692
+ const values = [];
4693
+ for (const row of data) {
4694
+ const v = Number(row[sampleField]);
4695
+ if (!isNaN(v))
4696
+ values.push(v);
4697
+ }
4698
+ if (values.length === 0)
4699
+ return;
4700
+ values.sort((a, b) => a - b);
4701
+ const n = values.length;
4702
+ const mean = values.reduce((a, b) => a + b, 0) / n;
4703
+ const variance = values.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / (n - 1);
4704
+ const sd = Math.sqrt(variance);
4705
+ const qnorm = (p) => {
4706
+ if (p <= 0)
4707
+ return -Infinity;
4708
+ if (p >= 1)
4709
+ return Infinity;
4710
+ if (p === 0.5)
4711
+ return 0;
4712
+ const a = [
4713
+ -39.69683028665376,
4714
+ 220.9460984245205,
4715
+ -275.9285104469687,
4716
+ 138.357751867269,
4717
+ -30.66479806614716,
4718
+ 2.506628277459239
4719
+ ];
4720
+ const b = [
4721
+ -54.47609879822406,
4722
+ 161.5858368580409,
4723
+ -155.6989798598866,
4724
+ 66.80131188771972,
4725
+ -13.28068155288572
4726
+ ];
4727
+ const c = [
4728
+ -0.007784894002430293,
4729
+ -0.3223964580411365,
4730
+ -2.400758277161838,
4731
+ -2.549732539343734,
4732
+ 4.374664141464968,
4733
+ 2.938163982698783
4734
+ ];
4735
+ const d = [
4736
+ 0.007784695709041462,
4737
+ 0.3224671290700398,
4738
+ 2.445134137142996,
4739
+ 3.754408661907416
4740
+ ];
4741
+ const pLow = 0.02425;
4742
+ const pHigh = 1 - pLow;
4743
+ let q;
4744
+ if (p < pLow) {
4745
+ q = Math.sqrt(-2 * Math.log(p));
4746
+ return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
4747
+ } else if (p <= pHigh) {
4748
+ q = p - 0.5;
4749
+ const r = q * q;
4750
+ return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
4751
+ } else {
4752
+ q = Math.sqrt(-2 * Math.log(1 - p));
4753
+ return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
4754
+ }
4755
+ };
4756
+ const points = [];
4757
+ for (let i = 0;i < n; i++) {
4758
+ const p = (i + 0.5) / n;
4759
+ const theoretical = qnorm(p);
4760
+ const sample = standardize ? (values[i] - mean) / sd : values[i];
4761
+ points.push({ theoretical, sample });
4762
+ }
4763
+ const plotLeft = Math.round(scales.x.range[0]);
4764
+ const plotRight = Math.round(scales.x.range[1]);
4765
+ const plotTop = Math.round(scales.y.range[1]);
4766
+ const plotBottom = Math.round(scales.y.range[0]);
4767
+ const minT = Math.min(...points.map((p) => p.theoretical));
4768
+ const maxT = Math.max(...points.map((p) => p.theoretical));
4769
+ const minS = Math.min(...points.map((p) => p.sample));
4770
+ const maxS = Math.max(...points.map((p) => p.sample));
4771
+ const minVal = Math.min(minT, minS);
4772
+ const maxVal = Math.max(maxT, maxS);
4773
+ const mapX = (v) => plotLeft + (v - minVal) / (maxVal - minVal) * (plotRight - plotLeft);
4774
+ const mapY = (v) => plotBottom - (v - minVal) / (maxVal - minVal) * (plotBottom - plotTop);
4775
+ if (showLine) {
4776
+ const steps = plotRight - plotLeft;
4777
+ for (let i = 0;i <= steps; i++) {
4778
+ const v = minVal + i / steps * (maxVal - minVal);
4779
+ const x = Math.round(mapX(v));
4780
+ const y = Math.round(mapY(v));
4781
+ if (y >= plotTop && y <= plotBottom) {
4782
+ canvas.drawChar(x, y, "─", lineColorParsed);
4783
+ }
4784
+ }
4785
+ }
4786
+ const pointColor = { r: 31, g: 119, b: 180, a: 1 };
4787
+ for (const p of points) {
4788
+ const x = Math.round(mapX(p.theoretical));
4789
+ const y = Math.round(mapY(p.sample));
4790
+ canvas.drawChar(x, y, pointChar, pointColor);
4791
+ }
4792
+ }
4793
+ function renderGeomECDF(data, geom, aes, scales, canvas) {
4794
+ const params = geom.params || {};
4795
+ const complement = params.complement ?? false;
4796
+ const showPoints = params.show_points ?? false;
4797
+ const xField = typeof aes.x === "string" ? aes.x : "x";
4798
+ const colorField = typeof aes.color === "string" ? aes.color : null;
4799
+ const groups = new Map;
4800
+ for (const row of data) {
4801
+ const v = Number(row[xField]);
4802
+ if (isNaN(v))
4803
+ continue;
4804
+ const groupKey = colorField ? String(row[colorField] ?? "default") : "default";
4805
+ if (!groups.has(groupKey))
4806
+ groups.set(groupKey, []);
4807
+ groups.get(groupKey).push(v);
4808
+ }
4809
+ if (groups.size === 0)
4810
+ return;
4811
+ const plotLeft = Math.round(scales.x.range[0]);
4812
+ const plotRight = Math.round(scales.x.range[1]);
4813
+ const plotTop = Math.round(scales.y.range[1]);
4814
+ const plotBottom = Math.round(scales.y.range[0]);
4815
+ let globalMin = Infinity;
4816
+ let globalMax = -Infinity;
4817
+ for (const values of groups.values()) {
4818
+ globalMin = Math.min(globalMin, ...values);
4819
+ globalMax = Math.max(globalMax, ...values);
4820
+ }
4821
+ const mapX = (v) => plotLeft + (v - globalMin) / (globalMax - globalMin) * (plotRight - plotLeft);
4822
+ const mapY = (v) => {
4823
+ const ecdf = complement ? 1 - v : v;
4824
+ return plotBottom - ecdf * (plotBottom - plotTop);
4825
+ };
4826
+ const colors = [
4827
+ { r: 31, g: 119, b: 180, a: 1 },
4828
+ { r: 255, g: 127, b: 14, a: 1 },
4829
+ { r: 44, g: 160, b: 44, a: 1 },
4830
+ { r: 214, g: 39, b: 40, a: 1 },
4831
+ { r: 148, g: 103, b: 189, a: 1 }
4832
+ ];
4833
+ let colorIdx = 0;
4834
+ for (const [, values] of groups) {
4835
+ const color = colors[colorIdx % colors.length];
4836
+ colorIdx++;
4837
+ const sorted = [...values].sort((a, b) => a - b);
4838
+ const n = sorted.length;
4839
+ let prevX = plotLeft;
4840
+ let prevY = Math.round(mapY(0));
4841
+ for (let i = 0;i < n; i++) {
4842
+ const ecdfVal = (i + 1) / n;
4843
+ const x = Math.round(mapX(sorted[i]));
4844
+ const y = Math.round(mapY(ecdfVal));
4845
+ for (let px = prevX;px <= x; px++) {
4846
+ canvas.drawChar(px, prevY, "─", color);
4847
+ }
4848
+ const stepDir = y < prevY ? -1 : 1;
4849
+ for (let py = prevY;stepDir > 0 ? py <= y : py >= y; py += stepDir) {
4850
+ canvas.drawChar(x, py, "│", color);
4851
+ }
4852
+ if (showPoints) {
4853
+ canvas.drawChar(x, y, "●", color);
4854
+ }
4855
+ prevX = x;
4856
+ prevY = y;
4857
+ }
4858
+ for (let px = prevX;px <= plotRight; px++) {
4859
+ canvas.drawChar(px, prevY, "─", color);
4860
+ }
4861
+ }
4862
+ }
4863
+ function renderGeomFunnel(data, geom, aes, scales, canvas) {
4864
+ const params = geom.params || {};
4865
+ const showContours = params.show_contours ?? true;
4866
+ const showSummaryLine = params.show_summary_line ?? true;
4867
+ const summaryEffect = params.summary_effect;
4868
+ const pointChar = params.point_char ?? "●";
4869
+ const contourColor = params.contour_color ?? "#888888";
4870
+ const invertY = params.invert_y ?? true;
4871
+ const parseHex = (hex) => {
4872
+ const r = parseInt(hex.slice(1, 3), 16);
4873
+ const g = parseInt(hex.slice(3, 5), 16);
4874
+ const b = parseInt(hex.slice(5, 7), 16);
4875
+ return { r, g, b, a: 1 };
4876
+ };
4877
+ const contourColorParsed = parseHex(contourColor);
4878
+ const xField = typeof aes.x === "string" ? aes.x : "effect";
4879
+ const yField = typeof aes.y === "string" ? aes.y : "se";
4880
+ const points = [];
4881
+ for (const row of data) {
4882
+ const effect = Number(row[xField]);
4883
+ const se = Number(row[yField]);
4884
+ if (!isNaN(effect) && !isNaN(se)) {
4885
+ points.push({ effect, se });
4886
+ }
4887
+ }
4888
+ if (points.length === 0)
4889
+ return;
4890
+ const summary = summaryEffect ?? points.reduce((a, b) => a + b.effect, 0) / points.length;
4891
+ const plotLeft = Math.round(scales.x.range[0]);
4892
+ const plotRight = Math.round(scales.x.range[1]);
4893
+ const plotTop = Math.round(scales.y.range[1]);
4894
+ const plotBottom = Math.round(scales.y.range[0]);
4895
+ const minEffect = Math.min(...points.map((p) => p.effect));
4896
+ const maxEffect = Math.max(...points.map((p) => p.effect));
4897
+ const maxSE = Math.max(...points.map((p) => p.se));
4898
+ const effectPad = (maxEffect - minEffect) * 0.2;
4899
+ const effectMin = minEffect - effectPad;
4900
+ const effectMax = maxEffect + effectPad;
4901
+ const mapX = (v) => plotLeft + (v - effectMin) / (effectMax - effectMin) * (plotRight - plotLeft);
4902
+ const mapY = (v) => {
4903
+ if (invertY) {
4904
+ return plotTop + v / maxSE * (plotBottom - plotTop);
4905
+ }
4906
+ return plotBottom - v / maxSE * (plotBottom - plotTop);
4907
+ };
4908
+ if (showContours) {
4909
+ const z = 1.96;
4910
+ for (let se = 0;se <= maxSE; se += maxSE / 40) {
4911
+ const leftBound = summary - z * se;
4912
+ const rightBound = summary + z * se;
4913
+ const y = Math.round(mapY(se));
4914
+ const leftX = Math.round(mapX(leftBound));
4915
+ const rightX = Math.round(mapX(rightBound));
4916
+ if (leftX >= plotLeft && leftX <= plotRight) {
4917
+ canvas.drawChar(leftX, y, "·", contourColorParsed);
4918
+ }
4919
+ if (rightX >= plotLeft && rightX <= plotRight) {
4920
+ canvas.drawChar(rightX, y, "·", contourColorParsed);
4921
+ }
4922
+ }
4923
+ }
4924
+ if (showSummaryLine) {
4925
+ const summaryX = Math.round(mapX(summary));
4926
+ for (let y = plotTop;y <= plotBottom; y += 2) {
4927
+ canvas.drawChar(summaryX, y, "│", contourColorParsed);
4928
+ }
4929
+ }
4930
+ const pointColor = { r: 31, g: 119, b: 180, a: 1 };
4931
+ for (const p of points) {
4932
+ const x = Math.round(mapX(p.effect));
4933
+ const y = Math.round(mapY(p.se));
4934
+ canvas.drawChar(x, y, pointChar, pointColor);
4935
+ }
4936
+ }
4937
+ function renderGeomControl(data, geom, aes, scales, canvas) {
4938
+ const params = geom.params || {};
4939
+ const sigma = params.sigma ?? 3;
4940
+ const showCenter = params.show_center ?? true;
4941
+ const showUCL = params.show_ucl ?? true;
4942
+ const showLCL = params.show_lcl ?? true;
4943
+ const showWarning = params.show_warning ?? false;
4944
+ const customCenter = params.center;
4945
+ const customUCL = params.ucl;
4946
+ const customLCL = params.lcl;
4947
+ const centerColor = params.center_color ?? "#0000ff";
4948
+ const limitColor = params.limit_color ?? "#ff0000";
4949
+ const warningColor = params.warning_color ?? "#ffa500";
4950
+ const connectPoints = params.connect_points ?? true;
4951
+ const highlightOOC = params.highlight_ooc ?? true;
4952
+ const oocChar = params.ooc_char ?? "◆";
4953
+ const pointChar = params.point_char ?? "●";
4954
+ const parseHex = (hex) => {
4955
+ const r = parseInt(hex.slice(1, 3), 16);
4956
+ const g = parseInt(hex.slice(3, 5), 16);
4957
+ const b = parseInt(hex.slice(5, 7), 16);
4958
+ return { r, g, b, a: 1 };
4959
+ };
4960
+ const centerColorParsed = parseHex(centerColor);
4961
+ const limitColorParsed = parseHex(limitColor);
4962
+ const warningColorParsed = parseHex(warningColor);
4963
+ const xField = typeof aes.x === "string" ? aes.x : "x";
4964
+ const yField = typeof aes.y === "string" ? aes.y : "y";
4965
+ const points = [];
4966
+ for (const row of data) {
4967
+ const x = Number(row[xField]);
4968
+ const y = Number(row[yField]);
4969
+ if (!isNaN(x) && !isNaN(y)) {
4970
+ points.push({ x, y });
4971
+ }
4972
+ }
4973
+ if (points.length === 0)
4974
+ return;
4975
+ points.sort((a, b) => a.x - b.x);
4976
+ const yValues = points.map((p) => p.y);
4977
+ const mean = customCenter ?? yValues.reduce((a, b) => a + b, 0) / yValues.length;
4978
+ let sigmaEst;
4979
+ if (points.length > 1) {
4980
+ const movingRanges = [];
4981
+ for (let i = 1;i < points.length; i++) {
4982
+ movingRanges.push(Math.abs(points[i].y - points[i - 1].y));
4983
+ }
4984
+ const avgMR = movingRanges.reduce((a, b) => a + b, 0) / movingRanges.length;
4985
+ sigmaEst = avgMR / 1.128;
4986
+ } else {
4987
+ const variance = yValues.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / (yValues.length - 1);
4988
+ sigmaEst = Math.sqrt(variance);
4989
+ }
4990
+ const ucl = customUCL ?? mean + sigma * sigmaEst;
4991
+ const lcl = customLCL ?? mean - sigma * sigmaEst;
4992
+ const uwl = mean + 2 * sigmaEst;
4993
+ const lwl = mean - 2 * sigmaEst;
4994
+ const plotLeft = Math.round(scales.x.range[0]);
4995
+ const plotRight = Math.round(scales.x.range[1]);
4996
+ const plotTop = Math.round(scales.y.range[1]);
4997
+ const plotBottom = Math.round(scales.y.range[0]);
4998
+ const minX = Math.min(...points.map((p) => p.x));
4999
+ const maxX = Math.max(...points.map((p) => p.x));
5000
+ const minY = Math.min(...points.map((p) => p.y), lcl);
5001
+ const maxY = Math.max(...points.map((p) => p.y), ucl);
5002
+ const mapX = (v) => plotLeft + (v - minX) / (maxX - minX) * (plotRight - plotLeft);
5003
+ const mapY = (v) => plotBottom - (v - minY) / (maxY - minY) * (plotBottom - plotTop);
5004
+ if (showCenter) {
5005
+ const centerY = Math.round(mapY(mean));
5006
+ for (let x = plotLeft;x <= plotRight; x++) {
5007
+ canvas.drawChar(x, centerY, "─", centerColorParsed);
5008
+ }
5009
+ }
5010
+ if (showUCL) {
5011
+ const uclY = Math.round(mapY(ucl));
5012
+ for (let x = plotLeft;x <= plotRight; x += 2) {
5013
+ canvas.drawChar(x, uclY, "─", limitColorParsed);
5014
+ }
5015
+ }
5016
+ if (showLCL) {
5017
+ const lclY = Math.round(mapY(lcl));
5018
+ for (let x = plotLeft;x <= plotRight; x += 2) {
5019
+ canvas.drawChar(x, lclY, "─", limitColorParsed);
5020
+ }
5021
+ }
5022
+ if (showWarning) {
5023
+ const uwlY = Math.round(mapY(uwl));
5024
+ const lwlY = Math.round(mapY(lwl));
5025
+ for (let x = plotLeft;x <= plotRight; x += 3) {
5026
+ canvas.drawChar(x, uwlY, "·", warningColorParsed);
5027
+ canvas.drawChar(x, lwlY, "·", warningColorParsed);
5028
+ }
5029
+ }
5030
+ if (connectPoints && points.length > 1) {
5031
+ const lineColor = { r: 100, g: 100, b: 100, a: 1 };
5032
+ for (let i = 1;i < points.length; i++) {
5033
+ const x1 = Math.round(mapX(points[i - 1].x));
5034
+ const y1 = Math.round(mapY(points[i - 1].y));
5035
+ const x2 = Math.round(mapX(points[i].x));
5036
+ const y2 = Math.round(mapY(points[i].y));
5037
+ const dx = Math.abs(x2 - x1);
5038
+ const dy = Math.abs(y2 - y1);
5039
+ const sx = x1 < x2 ? 1 : -1;
5040
+ const sy = y1 < y2 ? 1 : -1;
5041
+ let err = dx - dy;
5042
+ let x = x1;
5043
+ let y = y1;
5044
+ while (true) {
5045
+ canvas.drawChar(x, y, "·", lineColor);
5046
+ if (x === x2 && y === y2)
5047
+ break;
5048
+ const e2 = 2 * err;
5049
+ if (e2 > -dy) {
5050
+ err -= dy;
5051
+ x += sx;
5052
+ }
5053
+ if (e2 < dx) {
5054
+ err += dx;
5055
+ y += sy;
5056
+ }
5057
+ }
5058
+ }
5059
+ }
5060
+ const inControlColor = { r: 31, g: 119, b: 180, a: 1 };
5061
+ const oocColor = { r: 214, g: 39, b: 40, a: 1 };
5062
+ for (const p of points) {
5063
+ const x = Math.round(mapX(p.x));
5064
+ const y = Math.round(mapY(p.y));
5065
+ const isOOC = p.y > ucl || p.y < lcl;
5066
+ if (highlightOOC && isOOC) {
5067
+ canvas.drawChar(x, y, oocChar, oocColor);
5068
+ } else {
5069
+ canvas.drawChar(x, y, pointChar, inControlColor);
5070
+ }
5071
+ }
5072
+ }
5073
+ function renderGeomScree(data, geom, aes, scales, canvas) {
5074
+ const params = geom.params || {};
5075
+ const showCumulative = params.show_cumulative ?? false;
5076
+ const showKaiser = params.show_kaiser ?? false;
5077
+ const connectPoints = params.connect_points ?? true;
5078
+ const showBars = params.show_bars ?? false;
5079
+ const pointChar = params.point_char ?? "●";
5080
+ const cumulativeColor = params.cumulative_color ?? "#ff0000";
5081
+ const kaiserColor = params.kaiser_color ?? "#888888";
5082
+ const threshold = params.threshold;
5083
+ const thresholdColor = params.threshold_color ?? "#00aa00";
5084
+ const parseHex = (hex) => {
5085
+ const r = parseInt(hex.slice(1, 3), 16);
5086
+ const g = parseInt(hex.slice(3, 5), 16);
5087
+ const b = parseInt(hex.slice(5, 7), 16);
5088
+ return { r, g, b, a: 1 };
5089
+ };
5090
+ const cumulativeColorParsed = parseHex(cumulativeColor);
5091
+ const kaiserColorParsed = parseHex(kaiserColor);
5092
+ const thresholdColorParsed = parseHex(thresholdColor);
5093
+ const xField = typeof aes.x === "string" ? aes.x : "component";
5094
+ const yField = typeof aes.y === "string" ? aes.y : "variance";
5095
+ const points = [];
5096
+ for (const row of data) {
5097
+ const component = Number(row[xField]);
5098
+ const variance = Number(row[yField]);
5099
+ if (!isNaN(component) && !isNaN(variance)) {
5100
+ points.push({ component, variance });
5101
+ }
5102
+ }
5103
+ if (points.length === 0)
5104
+ return;
5105
+ points.sort((a, b) => a.component - b.component);
5106
+ const total = points.reduce((a, b) => a + b.variance, 0);
5107
+ let cumSum = 0;
5108
+ const cumulativePoints = points.map((p) => {
5109
+ cumSum += p.variance;
5110
+ return { component: p.component, cumulative: cumSum / total };
5111
+ });
5112
+ const plotLeft = Math.round(scales.x.range[0]);
5113
+ const plotRight = Math.round(scales.x.range[1]);
5114
+ const plotTop = Math.round(scales.y.range[1]);
5115
+ const plotBottom = Math.round(scales.y.range[0]);
5116
+ const minX = Math.min(...points.map((p) => p.component));
5117
+ const maxX = Math.max(...points.map((p) => p.component));
5118
+ const maxY = Math.max(...points.map((p) => p.variance));
5119
+ const yMax = showCumulative ? Math.max(maxY, total) : maxY;
5120
+ const mapX = (v) => plotLeft + (v - minX) / (maxX - minX) * (plotRight - plotLeft);
5121
+ const mapY = (v) => plotBottom - v / yMax * (plotBottom - plotTop);
5122
+ const mapYCumulative = (v) => plotBottom - v * (plotBottom - plotTop);
5123
+ if (showKaiser) {
5124
+ const kaiserY = Math.round(mapY(1));
5125
+ if (kaiserY >= plotTop && kaiserY <= plotBottom) {
5126
+ for (let x = plotLeft;x <= plotRight; x += 2) {
5127
+ canvas.drawChar(x, kaiserY, "─", kaiserColorParsed);
5128
+ }
5129
+ }
5130
+ }
5131
+ if (threshold !== undefined) {
5132
+ const thresholdY = Math.round(mapYCumulative(threshold));
5133
+ for (let x = plotLeft;x <= plotRight; x += 2) {
5134
+ canvas.drawChar(x, thresholdY, "─", thresholdColorParsed);
5135
+ }
5136
+ }
5137
+ if (showBars) {
5138
+ const barColor = { r: 180, g: 180, b: 180, a: 1 };
5139
+ const barWidth = Math.max(1, Math.floor((plotRight - plotLeft) / points.length / 2));
5140
+ for (const p of points) {
5141
+ const x = Math.round(mapX(p.component));
5142
+ const y = Math.round(mapY(p.variance));
5143
+ for (let bx = x - barWidth;bx <= x + barWidth; bx++) {
5144
+ for (let by = y;by <= plotBottom; by++) {
5145
+ canvas.drawChar(bx, by, "░", barColor);
5146
+ }
5147
+ }
5148
+ }
5149
+ }
5150
+ if (connectPoints && points.length > 1) {
5151
+ const lineColor = { r: 31, g: 119, b: 180, a: 1 };
5152
+ for (let i = 1;i < points.length; i++) {
5153
+ const x1 = Math.round(mapX(points[i - 1].component));
5154
+ const y1 = Math.round(mapY(points[i - 1].variance));
5155
+ const x2 = Math.round(mapX(points[i].component));
5156
+ const y2 = Math.round(mapY(points[i].variance));
5157
+ const steps = Math.max(Math.abs(x2 - x1), 1);
5158
+ for (let s = 0;s <= steps; s++) {
5159
+ const t = s / steps;
5160
+ const x = Math.round(x1 + t * (x2 - x1));
5161
+ const y = Math.round(y1 + t * (y2 - y1));
5162
+ canvas.drawChar(x, y, "─", lineColor);
5163
+ }
5164
+ }
5165
+ }
5166
+ if (showCumulative && cumulativePoints.length > 1) {
5167
+ for (let i = 1;i < cumulativePoints.length; i++) {
5168
+ const x1 = Math.round(mapX(cumulativePoints[i - 1].component));
5169
+ const y1 = Math.round(mapYCumulative(cumulativePoints[i - 1].cumulative));
5170
+ const x2 = Math.round(mapX(cumulativePoints[i].component));
5171
+ const y2 = Math.round(mapYCumulative(cumulativePoints[i].cumulative));
5172
+ const steps = Math.max(Math.abs(x2 - x1), 1);
5173
+ for (let s = 0;s <= steps; s++) {
5174
+ const t = s / steps;
5175
+ const x = Math.round(x1 + t * (x2 - x1));
5176
+ const y = Math.round(y1 + t * (y2 - y1));
5177
+ canvas.drawChar(x, y, "─", cumulativeColorParsed);
5178
+ }
5179
+ }
5180
+ for (const p of cumulativePoints) {
5181
+ const x = Math.round(mapX(p.component));
5182
+ const y = Math.round(mapYCumulative(p.cumulative));
5183
+ canvas.drawChar(x, y, "○", cumulativeColorParsed);
5184
+ }
5185
+ }
5186
+ const pointColor = { r: 31, g: 119, b: 180, a: 1 };
5187
+ for (const p of points) {
5188
+ const x = Math.round(mapX(p.component));
5189
+ const y = Math.round(mapY(p.variance));
5190
+ canvas.drawChar(x, y, pointChar, pointColor);
5191
+ }
5192
+ }
3724
5193
  function renderGeom(data, geom, aes, scales, canvas, coordType) {
3725
5194
  switch (geom.type) {
3726
5195
  case "point":
@@ -3849,10 +5318,455 @@ function renderGeom(data, geom, aes, scales, canvas, coordType) {
3849
5318
  case "volcano":
3850
5319
  renderGeomVolcano(data, geom, aes, scales, canvas);
3851
5320
  break;
5321
+ case "ma":
5322
+ renderGeomMA(data, geom, aes, scales, canvas);
5323
+ break;
5324
+ case "manhattan":
5325
+ renderGeomManhattan(data, geom, aes, scales, canvas);
5326
+ break;
5327
+ case "heatmap":
5328
+ renderGeomHeatmap(data, geom, aes, scales, canvas);
5329
+ break;
5330
+ case "biplot":
5331
+ renderGeomBiplot(data, geom, aes, scales, canvas);
5332
+ break;
5333
+ case "kaplan_meier":
5334
+ renderGeomKaplanMeier(data, geom, aes, scales, canvas);
5335
+ break;
5336
+ case "forest":
5337
+ renderGeomForest(data, geom, aes, scales, canvas);
5338
+ break;
5339
+ case "roc":
5340
+ renderGeomRoc(data, geom, aes, scales, canvas);
5341
+ break;
5342
+ case "bland_altman":
5343
+ renderGeomBlandAltman(data, geom, aes, scales, canvas);
5344
+ break;
5345
+ case "qq":
5346
+ renderGeomQQ(data, geom, aes, scales, canvas);
5347
+ break;
5348
+ case "ecdf":
5349
+ renderGeomECDF(data, geom, aes, scales, canvas);
5350
+ break;
5351
+ case "funnel":
5352
+ renderGeomFunnel(data, geom, aes, scales, canvas);
5353
+ break;
5354
+ case "control":
5355
+ renderGeomControl(data, geom, aes, scales, canvas);
5356
+ break;
5357
+ case "scree":
5358
+ renderGeomScree(data, geom, aes, scales, canvas);
5359
+ break;
5360
+ case "upset":
5361
+ renderGeomUpset(data, geom, aes, scales, canvas);
5362
+ break;
5363
+ case "dendrogram":
5364
+ renderGeomDendrogram(data, geom, aes, scales, canvas);
5365
+ break;
3852
5366
  default:
3853
5367
  break;
3854
5368
  }
3855
5369
  }
5370
+ function renderGeomUpset(data, geom, aes, scales, canvas) {
5371
+ const params = geom.params || {};
5372
+ const sets = params.sets;
5373
+ const minSize = params.min_size ?? 1;
5374
+ const maxIntersections = params.max_intersections ?? 20;
5375
+ const sortBy = params.sort_by ?? "size";
5376
+ const sortOrder = params.sort_order ?? "desc";
5377
+ const showSetSizes = params.show_set_sizes ?? true;
5378
+ const dotChar = params.dot_char ?? "●";
5379
+ const emptyChar = params.empty_char ?? "○";
5380
+ const lineChar = params.line_char ?? "│";
5381
+ const barChar = params.bar_char ?? "█";
5382
+ let setNames = [];
5383
+ if (sets && sets.length > 0) {
5384
+ setNames = sets;
5385
+ } else if (data.length > 0) {
5386
+ const firstRow = data[0];
5387
+ for (const key of Object.keys(firstRow)) {
5388
+ const values = data.map((row) => row[key]);
5389
+ const isBinary = values.every((v) => v === 0 || v === 1 || v === "0" || v === "1");
5390
+ if (isBinary && key !== "id" && key !== "name" && key !== "element") {
5391
+ setNames.push(key);
5392
+ }
5393
+ }
5394
+ if (setNames.length === 0) {
5395
+ const setsField2 = typeof aes.x === "string" ? aes.x : "sets";
5396
+ const allSets = new Set;
5397
+ for (const row of data) {
5398
+ const val = row[setsField2];
5399
+ if (typeof val === "string") {
5400
+ val.split(",").forEach((s) => allSets.add(s.trim()));
5401
+ }
5402
+ }
5403
+ setNames = Array.from(allSets).sort();
5404
+ }
5405
+ }
5406
+ if (setNames.length === 0)
5407
+ return;
5408
+ const intersectionMap = new Map;
5409
+ const setsField = typeof aes.x === "string" ? aes.x : "sets";
5410
+ const hasListFormat = data.length > 0 && typeof data[0][setsField] === "string";
5411
+ for (const row of data) {
5412
+ let memberSets;
5413
+ if (hasListFormat) {
5414
+ const val = row[setsField];
5415
+ memberSets = typeof val === "string" ? val.split(",").map((s) => s.trim()).filter((s) => setNames.includes(s)) : [];
5416
+ } else {
5417
+ memberSets = setNames.filter((s) => {
5418
+ const v = row[s];
5419
+ return v === 1 || v === "1";
5420
+ });
5421
+ }
5422
+ if (memberSets.length > 0) {
5423
+ const key = memberSets.sort().join("|");
5424
+ intersectionMap.set(key, (intersectionMap.get(key) || 0) + 1);
5425
+ }
5426
+ }
5427
+ let intersections = Array.from(intersectionMap.entries()).map(([key, count]) => ({
5428
+ sets: new Set(key.split("|")),
5429
+ count,
5430
+ key
5431
+ })).filter((i) => i.count >= minSize);
5432
+ if (sortBy === "size") {
5433
+ intersections.sort((a, b) => sortOrder === "desc" ? b.count - a.count : a.count - b.count);
5434
+ } else if (sortBy === "degree") {
5435
+ intersections.sort((a, b) => sortOrder === "desc" ? b.sets.size - a.sets.size : a.sets.size - b.sets.size);
5436
+ }
5437
+ intersections = intersections.slice(0, maxIntersections);
5438
+ if (intersections.length === 0)
5439
+ return;
5440
+ const plotLeft = Math.round(scales.x.range[0]);
5441
+ const plotRight = Math.round(scales.x.range[1]);
5442
+ const plotTop = Math.round(scales.y.range[1]);
5443
+ const plotBottom = Math.round(scales.y.range[0]);
5444
+ const plotWidth = plotRight - plotLeft;
5445
+ const plotHeight = plotBottom - plotTop;
5446
+ const matrixHeight = Math.min(setNames.length * 2 + 2, Math.floor(plotHeight * 0.4));
5447
+ const barHeight = plotHeight - matrixHeight - 2;
5448
+ const barTop = plotTop;
5449
+ const barBottom = plotTop + barHeight;
5450
+ const matrixTop = barBottom + 2;
5451
+ const setLabelWidth = showSetSizes ? Math.max(...setNames.map((s) => s.length)) + 8 : 0;
5452
+ const colWidth = Math.max(2, Math.floor((plotWidth - setLabelWidth) / intersections.length));
5453
+ const maxCount = Math.max(...intersections.map((i) => i.count));
5454
+ const barColor = { r: 31, g: 119, b: 180, a: 1 };
5455
+ const dotColor = { r: 50, g: 50, b: 50, a: 1 };
5456
+ const lineColor = { r: 100, g: 100, b: 100, a: 1 };
5457
+ const labelColor = { r: 150, g: 150, b: 150, a: 1 };
5458
+ for (let i = 0;i < intersections.length; i++) {
5459
+ const inter = intersections[i];
5460
+ const x = plotLeft + setLabelWidth + i * colWidth + Math.floor(colWidth / 2);
5461
+ const barHeightPx = Math.round(inter.count / maxCount * barHeight);
5462
+ for (let y = barBottom - barHeightPx;y <= barBottom; y++) {
5463
+ canvas.drawChar(x, y, barChar, barColor);
5464
+ }
5465
+ const countStr = inter.count.toString();
5466
+ const labelY = barBottom - barHeightPx - 1;
5467
+ if (labelY >= barTop) {
5468
+ for (let ci = 0;ci < countStr.length; ci++) {
5469
+ canvas.drawChar(x - Math.floor(countStr.length / 2) + ci, labelY, countStr[ci], labelColor);
5470
+ }
5471
+ }
5472
+ }
5473
+ const rowSpacing = Math.max(1, Math.floor(matrixHeight / setNames.length));
5474
+ if (showSetSizes) {
5475
+ for (let si = 0;si < setNames.length; si++) {
5476
+ const setName = setNames[si];
5477
+ const y = matrixTop + si * rowSpacing + 1;
5478
+ let setSize = 0;
5479
+ for (const row of data) {
5480
+ if (hasListFormat) {
5481
+ const val = row[setsField];
5482
+ if (typeof val === "string" && val.split(",").map((s) => s.trim()).includes(setName)) {
5483
+ setSize++;
5484
+ }
5485
+ } else {
5486
+ const v = row[setName];
5487
+ if (v === 1 || v === "1")
5488
+ setSize++;
5489
+ }
5490
+ }
5491
+ const label = `${setName.substring(0, 6)}`;
5492
+ for (let ci = 0;ci < label.length; ci++) {
5493
+ canvas.drawChar(plotLeft + ci, y, label[ci], labelColor);
5494
+ }
5495
+ const sizeBarLen = Math.max(1, Math.round(setSize / data.length * 5));
5496
+ for (let bi = 0;bi < sizeBarLen; bi++) {
5497
+ canvas.drawChar(plotLeft + label.length + 1 + bi, y, "▪", barColor);
5498
+ }
5499
+ }
5500
+ }
5501
+ for (let i = 0;i < intersections.length; i++) {
5502
+ const inter = intersections[i];
5503
+ const x = plotLeft + setLabelWidth + i * colWidth + Math.floor(colWidth / 2);
5504
+ const activeRows = [];
5505
+ for (let si = 0;si < setNames.length; si++) {
5506
+ const setName = setNames[si];
5507
+ const y = matrixTop + si * rowSpacing + 1;
5508
+ const isActive = inter.sets.has(setName);
5509
+ if (isActive) {
5510
+ canvas.drawChar(x, y, dotChar, dotColor);
5511
+ activeRows.push(y);
5512
+ } else {
5513
+ canvas.drawChar(x, y, emptyChar, { r: 200, g: 200, b: 200, a: 1 });
5514
+ }
5515
+ }
5516
+ if (activeRows.length > 1) {
5517
+ const minY = Math.min(...activeRows);
5518
+ const maxY = Math.max(...activeRows);
5519
+ for (let y = minY + 1;y < maxY; y++) {
5520
+ if (!activeRows.includes(y)) {
5521
+ canvas.drawChar(x, y, lineChar, lineColor);
5522
+ }
5523
+ }
5524
+ }
5525
+ }
5526
+ }
5527
+ function renderGeomDendrogram(data, geom, _aes, scales, canvas) {
5528
+ const params = geom.params || {};
5529
+ const orientation = params.orientation ?? "vertical";
5530
+ const labels = params.labels;
5531
+ const showLabels = params.show_labels ?? true;
5532
+ const hang = params.hang ?? false;
5533
+ const hConnector = params.h_connector ?? "─";
5534
+ const vConnector = params.v_connector ?? "│";
5535
+ const cornerTR = params.corner_tr ?? "┐";
5536
+ const cornerBL = params.corner_bl ?? "└";
5537
+ const cornerBR = params.corner_br ?? "┘";
5538
+ const leafChar = params.leaf_char ?? "○";
5539
+ const parentCol = params.parent_col ?? "parent";
5540
+ const heightCol = params.height_col ?? "height";
5541
+ const idCol = params.id_col ?? "id";
5542
+ const plotLeft = Math.round(scales.x.range[0]);
5543
+ const plotRight = Math.round(scales.x.range[1]);
5544
+ const plotTop = Math.round(scales.y.range[1]);
5545
+ const plotBottom = Math.round(scales.y.range[0]);
5546
+ const plotWidth = plotRight - plotLeft;
5547
+ const plotHeight = plotBottom - plotTop;
5548
+ const lineColor = { r: 50, g: 50, b: 50, a: 1 };
5549
+ const leafColor = { r: 31, g: 119, b: 180, a: 1 };
5550
+ const labelColor = { r: 100, g: 100, b: 100, a: 1 };
5551
+ const hasLinkageFormat = data.length > 0 && (("merge1" in data[0]) || ("merge_1" in data[0]));
5552
+ if (hasLinkageFormat) {
5553
+ const linkage = data.map((row) => ({
5554
+ merge1: Number(row["merge1"] ?? row["merge_1"]),
5555
+ merge2: Number(row["merge2"] ?? row["merge_2"]),
5556
+ height: Number(row[heightCol] ?? row["height"]),
5557
+ size: Number(row["size"] ?? 2)
5558
+ }));
5559
+ if (linkage.length === 0)
5560
+ return;
5561
+ const n = linkage.length + 1;
5562
+ const nodes = new Map;
5563
+ for (let i = 0;i < n; i++) {
5564
+ nodes.set(i, {
5565
+ id: i,
5566
+ height: 0,
5567
+ label: labels?.[i] ?? `${i}`
5568
+ });
5569
+ }
5570
+ for (let i = 0;i < linkage.length; i++) {
5571
+ const row = linkage[i];
5572
+ const newId = n + i;
5573
+ const leftNode = nodes.get(row.merge1 < n ? row.merge1 : row.merge1);
5574
+ const rightNode = nodes.get(row.merge2 < n ? row.merge2 : row.merge2);
5575
+ nodes.set(newId, {
5576
+ id: newId,
5577
+ left: leftNode,
5578
+ right: rightNode,
5579
+ height: row.height
5580
+ });
5581
+ }
5582
+ const root = nodes.get(n + linkage.length - 1);
5583
+ if (!root)
5584
+ return;
5585
+ let xPos = 0;
5586
+ const assignX = (node) => {
5587
+ if (!node.left && !node.right) {
5588
+ node.x = xPos++;
5589
+ } else {
5590
+ if (node.left)
5591
+ assignX(node.left);
5592
+ if (node.right)
5593
+ assignX(node.right);
5594
+ const leftX = node.left?.x ?? 0;
5595
+ const rightX = node.right?.x ?? 0;
5596
+ node.x = (leftX + rightX) / 2;
5597
+ }
5598
+ };
5599
+ assignX(root);
5600
+ const maxHeight = root.height;
5601
+ const leafCount = xPos;
5602
+ const mapX = (x) => {
5603
+ if (orientation === "vertical") {
5604
+ return plotLeft + x / (leafCount - 1 || 1) * plotWidth;
5605
+ } else {
5606
+ return plotBottom - x / (leafCount - 1 || 1) * plotHeight;
5607
+ }
5608
+ };
5609
+ const mapY = (h) => {
5610
+ if (orientation === "vertical") {
5611
+ return plotTop + (1 - h / maxHeight) * (plotHeight - 3);
5612
+ } else {
5613
+ return plotLeft + h / maxHeight * plotWidth;
5614
+ }
5615
+ };
5616
+ const drawNode = (node) => {
5617
+ if (node.x === undefined)
5618
+ return;
5619
+ if (node.left && node.right) {
5620
+ const nodeY = mapY(node.height);
5621
+ const leftX = mapX(node.left.x);
5622
+ const leftY = mapY(node.left.height);
5623
+ const rightX = mapX(node.right.x);
5624
+ const rightY = mapY(node.right.height);
5625
+ if (orientation === "vertical") {
5626
+ const hLineY = Math.round(nodeY);
5627
+ const leftXRound = Math.round(leftX);
5628
+ const rightXRound = Math.round(rightX);
5629
+ for (let x = Math.min(leftXRound, rightXRound);x <= Math.max(leftXRound, rightXRound); x++) {
5630
+ canvas.drawChar(x, hLineY, hConnector, lineColor);
5631
+ }
5632
+ canvas.drawChar(leftXRound, hLineY, cornerBL, lineColor);
5633
+ canvas.drawChar(rightXRound, hLineY, cornerBR, lineColor);
5634
+ const leftYRound = Math.round(leftY);
5635
+ const rightYRound = Math.round(rightY);
5636
+ for (let y = hLineY + 1;y < leftYRound; y++) {
5637
+ canvas.drawChar(leftXRound, y, vConnector, lineColor);
5638
+ }
5639
+ for (let y = hLineY + 1;y < rightYRound; y++) {
5640
+ canvas.drawChar(rightXRound, y, vConnector, lineColor);
5641
+ }
5642
+ } else {
5643
+ const hLineX = Math.round(nodeY);
5644
+ const leftYRound = Math.round(leftX);
5645
+ const rightYRound = Math.round(rightX);
5646
+ for (let y = Math.min(leftYRound, rightYRound);y <= Math.max(leftYRound, rightYRound); y++) {
5647
+ canvas.drawChar(hLineX, y, vConnector, lineColor);
5648
+ }
5649
+ canvas.drawChar(hLineX, leftYRound, cornerTR, lineColor);
5650
+ canvas.drawChar(hLineX, rightYRound, cornerBR, lineColor);
5651
+ const leftXRound = Math.round(mapY(node.left.height));
5652
+ const rightXRound = Math.round(mapY(node.right.height));
5653
+ for (let x = hLineX + 1;x < leftXRound; x++) {
5654
+ canvas.drawChar(x, leftYRound, hConnector, lineColor);
5655
+ }
5656
+ for (let x = hLineX + 1;x < rightXRound; x++) {
5657
+ canvas.drawChar(x, rightYRound, hConnector, lineColor);
5658
+ }
5659
+ }
5660
+ drawNode(node.left);
5661
+ drawNode(node.right);
5662
+ } else {
5663
+ if (orientation === "vertical") {
5664
+ const x = Math.round(mapX(node.x));
5665
+ const y = hang ? plotBottom - 2 : Math.round(mapY(0));
5666
+ canvas.drawChar(x, y, leafChar, leafColor);
5667
+ if (showLabels && node.label) {
5668
+ const label = node.label.substring(0, 4);
5669
+ for (let ci = 0;ci < label.length; ci++) {
5670
+ canvas.drawChar(x - Math.floor(label.length / 2) + ci, y + 1, label[ci], labelColor);
5671
+ }
5672
+ }
5673
+ } else {
5674
+ const y = Math.round(mapX(node.x));
5675
+ const x = Math.round(mapY(0));
5676
+ canvas.drawChar(x, y, leafChar, leafColor);
5677
+ if (showLabels && node.label) {
5678
+ const label = node.label.substring(0, 6);
5679
+ for (let ci = 0;ci < label.length; ci++) {
5680
+ canvas.drawChar(x + 2 + ci, y, label[ci], labelColor);
5681
+ }
5682
+ }
5683
+ }
5684
+ }
5685
+ };
5686
+ drawNode(root);
5687
+ } else {
5688
+ const nodeMap = new Map;
5689
+ for (const row of data) {
5690
+ const id = String(row[idCol] ?? "");
5691
+ const parent = row[parentCol];
5692
+ const height = Number(row[heightCol] ?? 0);
5693
+ nodeMap.set(id, {
5694
+ id,
5695
+ parent: parent === null || parent === "" || parent === "null" ? null : String(parent),
5696
+ height,
5697
+ children: []
5698
+ });
5699
+ }
5700
+ let root = null;
5701
+ for (const node of nodeMap.values()) {
5702
+ if (node.parent === null) {
5703
+ root = node;
5704
+ } else {
5705
+ const parentNode = nodeMap.get(node.parent);
5706
+ if (parentNode) {
5707
+ parentNode.children.push(node);
5708
+ }
5709
+ }
5710
+ }
5711
+ if (!root)
5712
+ return;
5713
+ let xPos = 0;
5714
+ const assignX = (node) => {
5715
+ if (node.children.length === 0) {
5716
+ node.x = xPos++;
5717
+ } else {
5718
+ for (const child of node.children) {
5719
+ assignX(child);
5720
+ }
5721
+ const childXs = node.children.map((c) => c.x ?? 0);
5722
+ node.x = childXs.reduce((a, b) => a + b, 0) / childXs.length;
5723
+ }
5724
+ };
5725
+ assignX(root);
5726
+ const findMaxHeight = (node) => {
5727
+ if (node.children.length === 0)
5728
+ return node.height;
5729
+ return Math.max(node.height, ...node.children.map(findMaxHeight));
5730
+ };
5731
+ const maxHeight = findMaxHeight(root) || 1;
5732
+ const leafCount = xPos || 1;
5733
+ const mapX = (x) => plotLeft + x / (leafCount - 1 || 1) * plotWidth;
5734
+ const mapY = (h) => plotTop + (1 - h / maxHeight) * (plotHeight - 3);
5735
+ const drawNode = (node) => {
5736
+ if (node.x === undefined)
5737
+ return;
5738
+ if (node.children.length > 0) {
5739
+ const nodeY = Math.round(mapY(node.height));
5740
+ const childXs = node.children.map((c) => Math.round(mapX(c.x ?? 0)));
5741
+ const minX = Math.min(...childXs);
5742
+ const maxX = Math.max(...childXs);
5743
+ for (let x = minX;x <= maxX; x++) {
5744
+ canvas.drawChar(x, nodeY, hConnector, lineColor);
5745
+ }
5746
+ for (const child of node.children) {
5747
+ const childX = Math.round(mapX(child.x ?? 0));
5748
+ const childY = Math.round(mapY(child.height));
5749
+ canvas.drawChar(childX, nodeY, child === node.children[0] ? cornerBL : child === node.children[node.children.length - 1] ? cornerBR : "┴", lineColor);
5750
+ for (let y = nodeY + 1;y < childY; y++) {
5751
+ canvas.drawChar(childX, y, vConnector, lineColor);
5752
+ }
5753
+ drawNode(child);
5754
+ }
5755
+ } else {
5756
+ const x = Math.round(mapX(node.x));
5757
+ const y = hang ? plotBottom - 2 : Math.round(mapY(node.height));
5758
+ canvas.drawChar(x, y, leafChar, leafColor);
5759
+ if (showLabels) {
5760
+ const label = node.id.substring(0, 4);
5761
+ for (let ci = 0;ci < label.length; ci++) {
5762
+ canvas.drawChar(x - Math.floor(label.length / 2) + ci, y + 1, label[ci], labelColor);
5763
+ }
5764
+ }
5765
+ }
5766
+ };
5767
+ drawNode(root);
5768
+ }
5769
+ }
3856
5770
  var POINT_SHAPES, SIZE_CHARS;
3857
5771
  var init_render_geoms = __esm(() => {
3858
5772
  init_scales();
@@ -6003,11 +7917,23 @@ function calculateLayout(spec, options) {
6003
7917
  } else if (hasY2) {
6004
7918
  rightMargin = 8 + (hasY2Label ? 2 : 0);
6005
7919
  }
7920
+ let forestLabelWidth = 0;
7921
+ const isForestPlot = spec.geoms.some((g) => g.type === "forest");
7922
+ if (isForestPlot && Array.isArray(spec.data) && spec.data.length > 0) {
7923
+ const yField = typeof spec.aes.y === "string" ? spec.aes.y : "study";
7924
+ for (const row of spec.data) {
7925
+ const label = String(row[yField] ?? "");
7926
+ if (label.length > forestLabelWidth)
7927
+ forestLabelWidth = label.length;
7928
+ }
7929
+ }
7930
+ const defaultLeft = 8 + (hasYLabel ? 2 : 0);
7931
+ const neededLeft = forestLabelWidth > 0 ? forestLabelWidth + 2 : defaultLeft;
6006
7932
  const margins = {
6007
7933
  top: hasTitle ? 2 : 1,
6008
7934
  right: rightMargin,
6009
7935
  bottom: 2 + (hasXLabel ? 1 : 0) + (hasLegend && legendPosition === "bottom" ? 2 : 0),
6010
- left: 8 + (hasYLabel ? 2 : 0)
7936
+ left: Math.max(defaultLeft, neededLeft)
6011
7937
  };
6012
7938
  const plotArea = {
6013
7939
  x: margins.left,
@@ -6221,7 +8147,9 @@ function renderToCanvas(spec, options) {
6221
8147
  renderTitle(canvas, spec.labels.title, layout.width, spec.theme);
6222
8148
  }
6223
8149
  renderGridLines(canvas, scales, layout.plotArea, spec.theme);
6224
- renderAxes(canvas, scales, layout.plotArea, spec.labels, spec.theme);
8150
+ const isForest = spec.geoms.some((g) => g.type === "forest");
8151
+ const axisLabels = isForest ? { ...spec.labels, y: undefined } : spec.labels;
8152
+ renderAxes(canvas, scales, layout.plotArea, axisLabels, spec.theme);
6225
8153
  for (const geom of spec.geoms) {
6226
8154
  let geomData;
6227
8155
  let geomAes = spec.aes;
@@ -7165,28 +9093,17 @@ function geom_abline(options = {}) {
7165
9093
  // src/geoms/qq.ts
7166
9094
  function geom_qq(options = {}) {
7167
9095
  return {
7168
- type: "point",
7169
- stat: "qq",
7170
- params: {
7171
- distribution: options.distribution ?? "norm",
7172
- dparams: options.dparams,
7173
- size: options.size ?? 1,
7174
- shape: options.shape ?? "●",
7175
- color: options.color,
7176
- alpha: options.alpha ?? 1
7177
- }
7178
- };
7179
- }
7180
- function geom_qq_line(options = {}) {
7181
- return {
7182
- type: "segment",
7183
- stat: "qq_line",
9096
+ type: "qq",
9097
+ stat: "identity",
9098
+ position: "identity",
7184
9099
  params: {
7185
- distribution: options.distribution ?? "norm",
7186
- dparams: options.dparams,
7187
- color: options.color ?? "gray",
7188
- linetype: options.linetype ?? "dashed",
7189
- alpha: options.alpha ?? 1
9100
+ distribution: options.distribution ?? "normal",
9101
+ show_line: options.show_line ?? true,
9102
+ show_ci: options.show_ci ?? false,
9103
+ conf_level: options.conf_level ?? 0.95,
9104
+ line_color: options.line_color ?? "#ff0000",
9105
+ point_char: options.point_char ?? "●",
9106
+ standardize: options.standardize ?? true
7190
9107
  }
7191
9108
  };
7192
9109
  }
@@ -7490,11 +9407,358 @@ function geom_volcano(options = {}) {
7490
9407
  };
7491
9408
  }
7492
9409
 
9410
+ // src/geoms/ma.ts
9411
+ function geom_ma(options = {}) {
9412
+ return {
9413
+ type: "ma",
9414
+ stat: "identity",
9415
+ position: "identity",
9416
+ params: {
9417
+ fc_threshold: options.fc_threshold ?? 1,
9418
+ p_threshold: options.p_threshold ?? 0.05,
9419
+ p_col: options.p_col,
9420
+ x_is_log2: options.x_is_log2 ?? false,
9421
+ up_color: options.up_color ?? "#e41a1c",
9422
+ down_color: options.down_color ?? "#377eb8",
9423
+ ns_color: options.ns_color ?? "#999999",
9424
+ show_baseline: options.show_baseline ?? true,
9425
+ show_thresholds: options.show_thresholds ?? true,
9426
+ linetype: options.linetype ?? "dashed",
9427
+ n_labels: options.n_labels ?? 0,
9428
+ size: options.size ?? 1,
9429
+ alpha: options.alpha ?? 0.6,
9430
+ point_char: options.point_char ?? "●",
9431
+ show_smooth: options.show_smooth ?? false
9432
+ }
9433
+ };
9434
+ }
9435
+
9436
+ // src/geoms/manhattan.ts
9437
+ function geom_manhattan(options = {}) {
9438
+ return {
9439
+ type: "manhattan",
9440
+ stat: "identity",
9441
+ position: "identity",
9442
+ params: {
9443
+ suggestive_threshold: options.suggestive_threshold ?? 0.00001,
9444
+ genome_wide_threshold: options.genome_wide_threshold ?? 0.00000005,
9445
+ chr_col: options.chr_col,
9446
+ pos_col: options.pos_col,
9447
+ p_col: options.p_col,
9448
+ y_is_neglog10: options.y_is_neglog10 ?? false,
9449
+ chr_colors: options.chr_colors ?? DEFAULT_CHR_COLORS,
9450
+ highlight_color: options.highlight_color ?? "#e41a1c",
9451
+ suggestive_color: options.suggestive_color ?? "#ff7f00",
9452
+ show_thresholds: options.show_thresholds ?? true,
9453
+ threshold_linetype: options.threshold_linetype ?? "dashed",
9454
+ n_labels: options.n_labels ?? 0,
9455
+ label_col: options.label_col,
9456
+ size: options.size ?? 1,
9457
+ alpha: options.alpha ?? 0.6,
9458
+ point_char: options.point_char ?? "●",
9459
+ chr_gap: options.chr_gap ?? 0.02
9460
+ }
9461
+ };
9462
+ }
9463
+ var DEFAULT_CHR_COLORS;
9464
+ var init_manhattan = __esm(() => {
9465
+ DEFAULT_CHR_COLORS = ["#1f78b4", "#a6cee3"];
9466
+ });
9467
+
9468
+ // src/geoms/heatmap.ts
9469
+ function geom_heatmap(options = {}) {
9470
+ return {
9471
+ type: "heatmap",
9472
+ stat: "identity",
9473
+ position: "identity",
9474
+ params: {
9475
+ x_col: options.x_col,
9476
+ y_col: options.y_col,
9477
+ value_col: options.value_col ?? "value",
9478
+ low_color: options.low_color ?? "#313695",
9479
+ mid_color: options.mid_color ?? "#ffffbf",
9480
+ high_color: options.high_color ?? "#a50026",
9481
+ na_color: options.na_color ?? "#808080",
9482
+ midpoint: options.midpoint,
9483
+ cluster_rows: options.cluster_rows ?? false,
9484
+ cluster_cols: options.cluster_cols ?? false,
9485
+ clustering_method: options.clustering_method ?? "complete",
9486
+ clustering_distance: options.clustering_distance ?? "euclidean",
9487
+ show_row_dendrogram: options.show_row_dendrogram ?? true,
9488
+ show_col_dendrogram: options.show_col_dendrogram ?? true,
9489
+ dendrogram_ratio: options.dendrogram_ratio ?? 0.15,
9490
+ show_row_labels: options.show_row_labels ?? true,
9491
+ show_col_labels: options.show_col_labels ?? true,
9492
+ show_values: options.show_values ?? false,
9493
+ value_format: options.value_format ?? ".2f",
9494
+ cell_char: options.cell_char ?? "█",
9495
+ border: options.border ?? false,
9496
+ scale: options.scale ?? "none"
9497
+ }
9498
+ };
9499
+ }
9500
+
9501
+ // src/geoms/biplot.ts
9502
+ function geom_biplot(options = {}) {
9503
+ return {
9504
+ type: "biplot",
9505
+ stat: "identity",
9506
+ position: "identity",
9507
+ params: {
9508
+ pc1_col: options.pc1_col ?? "PC1",
9509
+ pc2_col: options.pc2_col ?? "PC2",
9510
+ loadings: options.loadings,
9511
+ var_explained: options.var_explained,
9512
+ show_scores: options.show_scores ?? true,
9513
+ score_color: options.score_color,
9514
+ score_size: options.score_size ?? 1,
9515
+ score_alpha: options.score_alpha ?? 0.8,
9516
+ score_char: options.score_char ?? "●",
9517
+ show_score_labels: options.show_score_labels ?? false,
9518
+ show_loadings: options.show_loadings ?? true,
9519
+ loading_color: options.loading_color ?? "#e41a1c",
9520
+ loading_scale: options.loading_scale,
9521
+ arrow_char: options.arrow_char ?? "→",
9522
+ show_loading_labels: options.show_loading_labels ?? true,
9523
+ show_origin: options.show_origin ?? true,
9524
+ origin_color: options.origin_color ?? "#999999",
9525
+ show_circle: options.show_circle ?? false,
9526
+ circle_color: options.circle_color ?? "#cccccc"
9527
+ }
9528
+ };
9529
+ }
9530
+
9531
+ // src/geoms/kaplan-meier.ts
9532
+ function geom_kaplan_meier(options = {}) {
9533
+ return {
9534
+ type: "kaplan_meier",
9535
+ stat: "identity",
9536
+ position: "identity",
9537
+ params: {
9538
+ show_ci: options.show_ci ?? false,
9539
+ conf_level: options.conf_level ?? 0.95,
9540
+ show_censored: options.show_censored ?? true,
9541
+ censor_char: options.censor_char ?? "+",
9542
+ show_risk_table: options.show_risk_table ?? false,
9543
+ linetype: options.linetype ?? "solid",
9544
+ show_median: options.show_median ?? false,
9545
+ step_type: options.step_type ?? "post"
9546
+ }
9547
+ };
9548
+ }
9549
+
9550
+ // src/geoms/forest.ts
9551
+ function geom_forest(options = {}) {
9552
+ return {
9553
+ type: "forest",
9554
+ stat: "identity",
9555
+ position: "identity",
9556
+ params: {
9557
+ null_line: options.null_line ?? 1,
9558
+ log_scale: options.log_scale ?? false,
9559
+ show_summary: options.show_summary ?? false,
9560
+ summary_row: options.summary_row,
9561
+ null_line_color: options.null_line_color ?? "#888888",
9562
+ null_line_type: options.null_line_type ?? "dashed",
9563
+ point_char: options.point_char ?? "■",
9564
+ show_weights: options.show_weights ?? false,
9565
+ min_size: options.min_size ?? 1,
9566
+ max_size: options.max_size ?? 3
9567
+ }
9568
+ };
9569
+ }
9570
+
9571
+ // src/geoms/roc.ts
9572
+ function geom_roc(options = {}) {
9573
+ return {
9574
+ type: "roc",
9575
+ stat: "identity",
9576
+ position: "identity",
9577
+ params: {
9578
+ show_diagonal: options.show_diagonal ?? true,
9579
+ diagonal_color: options.diagonal_color ?? "#888888",
9580
+ diagonal_type: options.diagonal_type ?? "dashed",
9581
+ show_auc: options.show_auc ?? true,
9582
+ show_optimal: options.show_optimal ?? false,
9583
+ optimal_char: options.optimal_char ?? "●",
9584
+ show_ci: options.show_ci ?? false,
9585
+ conf_level: options.conf_level ?? 0.95,
9586
+ fill_auc: options.fill_auc ?? false,
9587
+ fill_alpha: options.fill_alpha ?? 0.3
9588
+ }
9589
+ };
9590
+ }
9591
+
9592
+ // src/geoms/bland-altman.ts
9593
+ function geom_bland_altman(options = {}) {
9594
+ return {
9595
+ type: "bland_altman",
9596
+ stat: "identity",
9597
+ position: "identity",
9598
+ params: {
9599
+ show_limits: options.show_limits ?? true,
9600
+ show_bias: options.show_bias ?? true,
9601
+ limit_multiplier: options.limit_multiplier ?? 1.96,
9602
+ bias_color: options.bias_color ?? "#0000ff",
9603
+ limit_color: options.limit_color ?? "#ff0000",
9604
+ linetype: options.linetype ?? "dashed",
9605
+ show_ci: options.show_ci ?? false,
9606
+ conf_level: options.conf_level ?? 0.95,
9607
+ point_char: options.point_char ?? "●",
9608
+ percent_diff: options.percent_diff ?? false,
9609
+ precomputed: options.precomputed ?? false
9610
+ }
9611
+ };
9612
+ }
9613
+
9614
+ // src/geoms/ecdf.ts
9615
+ function geom_ecdf(options = {}) {
9616
+ return {
9617
+ type: "ecdf",
9618
+ stat: "identity",
9619
+ position: "identity",
9620
+ params: {
9621
+ pad: options.pad ?? true,
9622
+ show_ci: options.show_ci ?? false,
9623
+ conf_level: options.conf_level ?? 0.95,
9624
+ step_type: options.step_type ?? "post",
9625
+ show_points: options.show_points ?? false,
9626
+ line_char: options.line_char ?? "─",
9627
+ complement: options.complement ?? false
9628
+ }
9629
+ };
9630
+ }
9631
+
9632
+ // src/geoms/funnel.ts
9633
+ function geom_funnel(options = {}) {
9634
+ return {
9635
+ type: "funnel",
9636
+ stat: "identity",
9637
+ position: "identity",
9638
+ params: {
9639
+ show_contours: options.show_contours ?? true,
9640
+ contour_levels: options.contour_levels ?? [0.95],
9641
+ show_significance: options.show_significance ?? false,
9642
+ summary_effect: options.summary_effect,
9643
+ show_summary_line: options.show_summary_line ?? true,
9644
+ y_is_se: options.y_is_se ?? true,
9645
+ invert_y: options.invert_y ?? true,
9646
+ point_char: options.point_char ?? "●",
9647
+ contour_color: options.contour_color ?? "#888888"
9648
+ }
9649
+ };
9650
+ }
9651
+
9652
+ // src/geoms/control.ts
9653
+ function geom_control(options = {}) {
9654
+ return {
9655
+ type: "control",
9656
+ stat: "identity",
9657
+ position: "identity",
9658
+ params: {
9659
+ chart_type: options.chart_type ?? "i",
9660
+ sigma: options.sigma ?? 3,
9661
+ show_center: options.show_center ?? true,
9662
+ show_ucl: options.show_ucl ?? true,
9663
+ show_lcl: options.show_lcl ?? true,
9664
+ show_warning: options.show_warning ?? false,
9665
+ center: options.center,
9666
+ ucl: options.ucl,
9667
+ lcl: options.lcl,
9668
+ center_color: options.center_color ?? "#0000ff",
9669
+ limit_color: options.limit_color ?? "#ff0000",
9670
+ warning_color: options.warning_color ?? "#ffa500",
9671
+ connect_points: options.connect_points ?? true,
9672
+ highlight_ooc: options.highlight_ooc ?? true,
9673
+ ooc_char: options.ooc_char ?? "◆",
9674
+ point_char: options.point_char ?? "●"
9675
+ }
9676
+ };
9677
+ }
9678
+
9679
+ // src/geoms/scree.ts
9680
+ function geom_scree(options = {}) {
9681
+ return {
9682
+ type: "scree",
9683
+ stat: "identity",
9684
+ position: "identity",
9685
+ params: {
9686
+ show_cumulative: options.show_cumulative ?? false,
9687
+ show_kaiser: options.show_kaiser ?? false,
9688
+ show_elbow: options.show_elbow ?? false,
9689
+ show_broken_stick: options.show_broken_stick ?? false,
9690
+ connect_points: options.connect_points ?? true,
9691
+ show_bars: options.show_bars ?? false,
9692
+ point_char: options.point_char ?? "●",
9693
+ color: options.color,
9694
+ cumulative_color: options.cumulative_color ?? "#ff0000",
9695
+ kaiser_color: options.kaiser_color ?? "#888888",
9696
+ y_format: options.y_format ?? "percentage",
9697
+ threshold: options.threshold,
9698
+ threshold_color: options.threshold_color ?? "#00aa00"
9699
+ }
9700
+ };
9701
+ }
9702
+
9703
+ // src/geoms/upset.ts
9704
+ function geom_upset(options = {}) {
9705
+ return {
9706
+ type: "upset",
9707
+ stat: "identity",
9708
+ position: "identity",
9709
+ params: {
9710
+ sets: options.sets,
9711
+ min_size: options.min_size ?? 1,
9712
+ max_intersections: options.max_intersections ?? 20,
9713
+ sort_by: options.sort_by ?? "size",
9714
+ sort_order: options.sort_order ?? "desc",
9715
+ show_set_sizes: options.show_set_sizes ?? true,
9716
+ dot_char: options.dot_char ?? "●",
9717
+ empty_char: options.empty_char ?? "○",
9718
+ line_char: options.line_char ?? "│",
9719
+ bar_char: options.bar_char ?? "█",
9720
+ color: options.color,
9721
+ show_degree: options.show_degree ?? false
9722
+ }
9723
+ };
9724
+ }
9725
+
9726
+ // src/geoms/dendrogram.ts
9727
+ function geom_dendrogram(options = {}) {
9728
+ return {
9729
+ type: "dendrogram",
9730
+ stat: "identity",
9731
+ position: "identity",
9732
+ params: {
9733
+ orientation: options.orientation ?? "vertical",
9734
+ labels: options.labels,
9735
+ show_labels: options.show_labels ?? true,
9736
+ hang: options.hang ?? false,
9737
+ cut_height: options.cut_height,
9738
+ k: options.k,
9739
+ branch_char: options.branch_char ?? "│",
9740
+ h_connector: options.h_connector ?? "─",
9741
+ v_connector: options.v_connector ?? "│",
9742
+ corner_tl: options.corner_tl ?? "┌",
9743
+ corner_tr: options.corner_tr ?? "┐",
9744
+ corner_bl: options.corner_bl ?? "└",
9745
+ corner_br: options.corner_br ?? "┘",
9746
+ leaf_char: options.leaf_char ?? "○",
9747
+ cluster_colors: options.cluster_colors,
9748
+ line_style: options.line_style ?? "square",
9749
+ parent_col: options.parent_col ?? "parent",
9750
+ height_col: options.height_col ?? "height",
9751
+ id_col: options.id_col ?? "id"
9752
+ }
9753
+ };
9754
+ }
9755
+
7493
9756
  // src/geoms/index.ts
7494
9757
  var init_geoms = __esm(() => {
7495
9758
  init_ridgeline();
7496
9759
  init_sparkline();
7497
9760
  init_braille();
9761
+ init_manhattan();
7498
9762
  });
7499
9763
 
7500
9764
  // src/scales/continuous.ts