{"spec_id":"ks-test-comparison","library":"muix","language":"javascript","code":"// anyplot.ai\n// ks-test-comparison: Kolmogorov-Smirnov Plot for Distribution Comparison\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst CDF_MIN = 0; // a cumulative proportion runs from 0 to 1\nconst CDF_MAX = 1;\nconst CDF_TICKS = 10; // tick steps between CDF_MIN and CDF_MAX\nconst X_PAD_SHARE = 0.04; // share of the value range shown beyond the smallest and largest value\nconst Y_PAD_SHARE = 0.02; // room below 0 and above 1 so the flat ends of the steps stay visible\nconst KOLMOGOROV_TERMS = 100; // terms of the alternating series for the asymptotic p-value\n\n// Columns: set these to your data's column names\nconst GOOD = \"Good-standing customers\"; // role: sample1\nconst BAD = \"Bad-standing customers\"; // role: sample2\nconst MEASURE = \"Credit score (points)\"; // the quantity both sample columns hold, with its unit: the x-axis title\n\n// Data: replace this block with your own records, one object per row; a shorter sample\n// leaves its cells null\n// Model scores of 400 good- and 400 bad-standing customers of a credit-scoring model that\n// separates the two groups: good ~ N(680, 55), bad ~ N(590, 70).\nconst data = (() => {\n  let seed = 42;\n  const uniform = () => {\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    return seed / 0x7fffffff;\n  };\n  const normal = (mean: number, sd: number) =>\n    mean + sd * Math.sqrt(-2 * Math.log(uniform() || 1e-9)) * Math.cos(2 * Math.PI * uniform());\n  const good = Array.from({ length: 400 }, () => normal(680, 55));\n  const bad = Array.from({ length: 400 }, () => normal(590, 70));\n  return good.map((g, i) => ({ [GOOD]: Number(g.toFixed(1)), [BAD]: Number(bad[i].toFixed(1)) }));\n})();\n\n// Plot: reads only data and the constants above\nconst sample1 = data.map((d) => d[GOOD]).filter((v) => v != null).sort((a, b) => a - b);\nconst sample2 = data.map((d) => d[BAD]).filter((v) => v != null).sort((a, b) => a - b);\nconst n1 = sample1.length;\nconst n2 = sample2.length;\n\n// Both ECDFs on the union of observed values, one step at each value, plus one point\n// beyond each end so the curves start at 0 and reach 1 inside the axis\nconst values = [...new Set([...sample1, ...sample2])].sort((a, b) => a - b);\nconst xPad = (values[values.length - 1] - values[0]) * X_PAD_SHARE;\nconst grid = [values[0] - xPad, ...values, values[values.length - 1] + xPad];\nconst ecdf1: number[] = [];\nconst ecdf2: number[] = [];\nlet below1 = 0;\nlet below2 = 0;\nfor (const x of grid) {\n  while (below1 < n1 && sample1[below1] <= x) below1 += 1;\n  while (below2 < n2 && sample2[below2] <= x) below2 += 1;\n  ecdf1.push(below1 / n1);\n  ecdf2.push(below2 / n2);\n}\n\n// K-S statistic D: the largest vertical distance between the two step functions\nconst gaps = grid.map((_, i) => Math.abs(ecdf1[i] - ecdf2[i]));\nconst dIndex = gaps.indexOf(Math.max(...gaps));\nconst dStatistic = gaps[dIndex];\nconst dX = grid[dIndex];\n\n// Asymptotic two-sample p-value from the Kolmogorov distribution, with the effective\n// sample size n1·n2 / (n1 + n2) and Stephens' small-sample correction\nconst effectiveN = (n1 * n2) / (n1 + n2);\nconst lambda = (Math.sqrt(effectiveN) + 0.12 + 0.11 / Math.sqrt(effectiveN)) * dStatistic;\nlet pSeries = 0;\nfor (let k = 1; k <= KOLMOGOROV_TERMS; k += 1) {\n  pSeries += 2 * (-1) ** (k - 1) * Math.exp(-2 * k * k * lambda * lambda);\n}\nconst pValue = Math.min(1, Math.max(0, pSeries));\nconst pLabel = pValue < 0.001 ? \"p < 0.001\" : `p = ${pValue.toFixed(3)}`;\n\nconst TITLE = \"ks-test-comparison · javascript · muix · anyplot.ai\";\nconst STAT_LINE = `K-S statistic D = ${dStatistic.toFixed(3)} · ${pLabel}`;\nconst SAMPLE_LINE = `two-sample test, n = ${n1} and ${n2} · bar: the largest gap between the two ECDFs`;\nconst HEADER_H = 108;\nconst LEGEND_H = 44;\n\nfunction GapBar() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const x = xScale(dX);\n  const yTop = yScale(Math.max(ecdf1[dIndex], ecdf2[dIndex]));\n  const yBottom = yScale(Math.min(ecdf1[dIndex], ecdf2[dIndex]));\n  return (\n    <g>\n      <line x1={x} x2={x} y1={yTop} y2={yBottom} stroke={t.ink} strokeWidth={4} />\n      <circle cx={x} cy={yTop} r={6} fill={t.ink} stroke={t.pageBg} strokeWidth={1.5} />\n      <circle cx={x} cy={yBottom} r={6} fill={t.ink} stroke={t.pageBg} strokeWidth={1.5} />\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\", overflow: \"hidden\" }}>\n      <Box sx={{ height: HEADER_H, pt: \"14px\", textAlign: \"center\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.3 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 18, fontWeight: 600, color: t.ink, lineHeight: 1.5 }}>{STAT_LINE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.5 }}>{SAMPLE_LINE}</Typography>\n      </Box>\n      <LineChart\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        skipAnimation\n        grid={{ horizontal: true }}\n        margin={{ top: 12, right: 40, bottom: 8, left: 20 }}\n        series={[\n          {\n            id: \"sample1\",\n            data: ecdf1,\n            label: `${GOOD} (n = ${n1})`,\n            color: t.palette[0],\n            curve: \"stepAfter\",\n            showMark: false,\n            labelMarkType: \"line\",\n          },\n          {\n            id: \"sample2\",\n            data: ecdf2,\n            label: `${BAD} (n = ${n2})`,\n            color: t.palette[1],\n            curve: \"stepAfter\",\n            showMark: false,\n            labelMarkType: \"line\",\n          },\n        ]}\n        xAxis={[\n          {\n            data: grid,\n            scaleType: \"linear\",\n            min: grid[0],\n            max: grid[grid.length - 1],\n            label: MEASURE,\n            height: 64,\n            valueFormatter: (v: number) => String(Math.round(v)),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: CDF_MIN - (CDF_MAX - CDF_MIN) * Y_PAD_SHARE,\n            max: CDF_MAX + (CDF_MAX - CDF_MIN) * Y_PAD_SHARE,\n            tickInterval: Array.from({ length: CDF_TICKS + 1 }, (_, i) => CDF_MIN + ((CDF_MAX - CDF_MIN) * i) / CDF_TICKS),\n            valueFormatter: (v: number) => v.toFixed(1),\n            width: 72,\n            label: \"Cumulative proportion\",\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"top\", horizontal: \"center\" },\n            sx: { fontSize: 15, color: t.ink, gap: \"36px\" },\n          },\n        }}\n        sx={{\n          \"& .MuiLineChart-line\": { strokeWidth: 3 },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      >\n        <ChartsReferenceLine\n          x={dX}\n          label={`largest gap at ${Math.round(dX)}`}\n          labelAlign=\"start\"\n          spacing={{ x: 10, y: 8 }}\n          labelStyle={{ fontSize: 15, fill: t.inkSoft }}\n          lineStyle={{ stroke: t.inkSoft, strokeWidth: 1.5, strokeDasharray: \"6 4\" }}\n        />\n        <GapBar />\n      </LineChart>\n    </Box>\n  );\n}\n"}