{"spec_id":"contour-decision-boundary","library":"muix","language":"javascript","code":"// anyplot.ai\n// contour-decision-boundary: Decision Boundary Classifier Visualization\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst K_NEIGHBORS = 13; // k-nearest-neighbour classifier: distance-weighted vote of the 13 closest training points\nconst MESH_STEPS = 200; // prediction mesh nodes per axis, the spec's finest mesh, so the boundary shows no grid steps\nconst PAD_SHARE = 0.12; // feature plane beyond the training points, as a share of each feature's range\nconst REGION_OPACITY = 0.24; // region tint, light enough that the training points stay the strongest marks\n\n// Columns: set these to your data's column names\nconst PETAL_LENGTH = \"Petal length (cm)\"; // role: X1\nconst PETAL_WIDTH = \"Petal width (cm)\"; // role: X2\nconst SPECIES = \"Species\"; // role: y\n\n// Data: replace this block with your own records, one object per training point\n// Synthetic iris-like petal measurements of three species: setosa separates cleanly on these two\n// features, versicolor and virginica overlap near their shared boundary as in the real iris data\nconst data = (() => {\n  let state = 42;\n  const rand = () => {\n    state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n    return state / 4294967296;\n  };\n  const gaussian = () => Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n  const species = [\n    { name: \"Setosa\", meanLength: 1.5, meanWidth: 0.25, sdLength: 0.17, sdWidth: 0.1, n: 50 },\n    { name: \"Versicolor\", meanLength: 4.3, meanWidth: 1.3, sdLength: 0.47, sdWidth: 0.2, n: 55 },\n    { name: \"Virginica\", meanLength: 5.55, meanWidth: 2.03, sdLength: 0.55, sdWidth: 0.27, n: 55 },\n  ];\n  return species.flatMap((sp) =>\n    Array.from({ length: sp.n }, () => {\n      const length = Math.round((sp.meanLength + gaussian() * sp.sdLength) * 100) / 100;\n      const width = Math.round((sp.meanWidth + gaussian() * sp.sdWidth) * 100) / 100;\n      // petals are never thinner than 0.1 cm, the smallest width in the real iris data\n      return { [PETAL_LENGTH]: length, [PETAL_WIDTH]: Math.max(0.1, width), [SPECIES]: sp.name };\n    }),\n  );\n})();\n\n// Plot: reads only data and the constants above\n// Classes in order of first appearance, one palette position each\nconst classes = [...new Set(data.map((d) => d[SPECIES]))];\nconst points = data\n  .filter((d) => Number.isFinite(d[PETAL_LENGTH]) && Number.isFinite(d[PETAL_WIDTH]))\n  .map((d, i) => ({ id: `point-${i}`, x: d[PETAL_LENGTH], y: d[PETAL_WIDTH], cls: classes.indexOf(d[SPECIES]) }));\n\n// Feature plane: the training extent plus a padding share; a feature that is never negative keeps a\n// non-negative axis\nconst [xDomain, yDomain] = [points.map((p) => p.x), points.map((p) => p.y)].map((values) => {\n  const low = Math.min(...values);\n  const high = Math.max(...values);\n  const pad = (high - low) * PAD_SHARE;\n  return [low >= 0 ? Math.max(0, low - pad) : low - pad, high + pad];\n});\nconst meshX = Array.from({ length: MESH_STEPS }, (_, i) => xDomain[0] + (i / (MESH_STEPS - 1)) * (xDomain[1] - xDomain[0]));\nconst meshY = Array.from({ length: MESH_STEPS }, (_, j) => yDomain[0] + (j / (MESH_STEPS - 1)) * (yDomain[1] - yDomain[0]));\n\n// Distance-weighted k-NN votes per class: each of the k nearest training points votes with the weight\n// 1 − d² / d²₍ₖ₊₁₎, which falls to zero at the distance of the next neighbour, so the score changes\n// smoothly as points enter or leave the vote and the boundary can be interpolated between mesh nodes\n// (a plain vote count is piecewise constant and shows the mesh as stair-steps). Every training point\n// is classified leave-one-out (it never votes for itself), every mesh node by all training points.\nconst queries = [\n  ...points.map((p, i) => ({ x: p.x, y: p.y, skip: i })),\n  ...meshY.flatMap((y) => meshX.map((x) => ({ x, y, skip: -1 }))),\n];\nconst votes = queries.map((q) => {\n  const nearest = points\n    .map((p, i) => ({ i, cls: p.cls, d2: (p.x - q.x) ** 2 + (p.y - q.y) ** 2 }))\n    .filter((n) => n.i !== q.skip)\n    .sort((a, b) => a.d2 - b.d2)\n    .slice(0, K_NEIGHBORS + 1);\n  // with fewer than k + 1 other points, or a next neighbour on the same spot, every vote weighs 1\n  const reach = nearest[K_NEIGHBORS]?.d2 || Infinity;\n  return classes.map((_, c) =>\n    nearest\n      .slice(0, K_NEIGHBORS)\n      .filter((n) => n.cls === c)\n      .reduce((s, n) => s + 1 - n.d2 / reach, 0),\n  );\n});\nconst predicted = points.map((_, i) => votes[i].indexOf(Math.max(...votes[i])));\nconst misclassified = points.filter((p, i) => predicted[i] !== p.cls);\n\n// Region of a class: mesh nodes where its votes reach the best other class (margin >= 0). Marching\n// triangles over that margin give the region polygons and a boundary interpolated between nodes.\nconst meshVotes = votes.slice(points.length);\nconst regionPolygons: { x: number; y: number }[][][] = [];\nconst boundaryCuts: { x: number; y: number }[][][] = [];\nclasses.forEach((_, c) => {\n  const margin = meshVotes.map((v) => v[c] - Math.max(...v.filter((_, k) => k !== c)));\n  const polys: { x: number; y: number }[][] = [];\n  const cuts: { x: number; y: number }[][] = [];\n  for (let j = 0; j < MESH_STEPS - 1; j += 1) {\n    for (let i = 0; i < MESH_STEPS - 1; i += 1) {\n      const [sw, se, ne, nw] = [\n        [i, j],\n        [i + 1, j],\n        [i + 1, j + 1],\n        [i, j + 1],\n      ].map(([ii, jj]) => ({ x: meshX[ii], y: meshY[jj], z: margin[jj * MESH_STEPS + ii] }));\n      const centre = { x: (sw.x + se.x) / 2, y: (sw.y + nw.y) / 2, z: (sw.z + se.z + ne.z + nw.z) / 4 };\n      [[sw, se], [se, ne], [ne, nw], [nw, sw]].forEach(([a, b]) => {\n        const tri = [a, b, centre];\n        const inside = tri.map((p) => p.z >= 0);\n        if (inside.every(Boolean)) {\n          polys.push(tri);\n          return;\n        }\n        if (!inside.some(Boolean)) return;\n        const ring: { x: number; y: number }[] = [];\n        const cut: { x: number; y: number }[] = [];\n        tri.forEach((p, k) => {\n          const q = tri[(k + 1) % 3];\n          if (inside[k]) ring.push(p);\n          if (inside[k] !== inside[(k + 1) % 3]) {\n            const r = p.z / (p.z - q.z);\n            const crossing = { x: p.x + r * (q.x - p.x), y: p.y + r * (q.y - p.y) };\n            ring.push(crossing);\n            cut.push(crossing);\n          }\n        });\n        polys.push(ring);\n        cuts.push(cut);\n      });\n    }\n  }\n  regionPolygons.push(polys);\n  boundaryCuts.push(cuts);\n});\n\nconst series = [\n  ...classes.map((name, c) => ({\n    type: \"scatter\" as const,\n    id: `class-${c}`,\n    label: name,\n    color: t.palette[c],\n    markerSize: 8,\n    labelMarkType: \"circle\" as const,\n    data: points.filter((p) => p.cls === c).map(({ id, x, y }) => ({ id, x, y })),\n  })),\n  {\n    type: \"scatter\" as const,\n    id: \"misclassified\",\n    label: \"Misclassified (leave-one-out)\",\n    color: t.ink,\n    markerSize: 13,\n    labelMarkType: \"circle\" as const,\n    data: misclassified.map(({ id, x, y }) => ({ id: `ring-${id}`, x, y })),\n  },\n];\n\nconst TITLE = \"Iris Species by k-NN · contour-decision-boundary · javascript · muix · anyplot.ai\";\nconst subtitle = `${points.length} training points · k = ${K_NEIGHBORS} distance-weighted nearest-neighbour vote on a ${MESH_STEPS} × ${MESH_STEPS} mesh · ${misclassified.length} misclassified in leave-one-out`;\nconst HEADER_H = 84;\nconst LEGEND_W = 280;\n\nfunction RegionLayer() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const toPath = (shapes: { x: number; y: number }[][], close: boolean) =>\n    shapes\n      .map((shape) => shape.map((p, k) => `${k === 0 ? \"M\" : \"L\"}${xScale(p.x)!.toFixed(1)},${yScale(p.y)!.toFixed(1)}`).join(\"\") + (close ? \"Z\" : \"\"))\n      .join(\"\");\n  return (\n    <g>\n      {/* Opaque fills inside one translucent group: no seams between the mesh triangles */}\n      <g opacity={REGION_OPACITY}>\n        {regionPolygons.map((polys, c) => (\n          <path key={`region-${c}`} d={toPath(polys, true)} fill={t.palette[c]} stroke={t.palette[c]} strokeWidth={0.75} />\n        ))}\n      </g>\n      {boundaryCuts.map((cuts, c) => (\n        <path key={`boundary-${c}`} d={toPath(cuts, false)} fill=\"none\" stroke={t.inkSoft} strokeWidth={1.8} strokeLinecap=\"round\" />\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <Box sx={{ height: HEADER_H, display: \"flex\", flexDirection: \"column\", justifyContent: \"center\", alignItems: \"center\", gap: \"6px\", pt: \"8px\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.2 }}>{subtitle}</Typography>\n      </Box>\n      <ChartsDataProvider\n        width={width - LEGEND_W}\n        height={height - HEADER_H}\n        series={series}\n        skipAnimation\n        margin={{ top: 16, bottom: 16, left: 24, right: 24 }}\n        xAxis={[\n          {\n            scaleType: \"linear\",\n            min: xDomain[0],\n            max: xDomain[1],\n            label: PETAL_LENGTH,\n            height: 60,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: yDomain[0],\n            max: yDomain[1],\n            label: PETAL_WIDTH,\n            width: 76,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n      >\n        <ChartsWrapper\n          legendPosition={{ vertical: \"middle\", horizontal: \"end\" }}\n          legendDirection=\"vertical\"\n          sx={{ width, height: height - HEADER_H }}\n        >\n          <ChartsSurface\n            sx={{\n              \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n              \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n              \"& .MuiScatterChart-marker\": { stroke: t.pageBg, strokeWidth: 1.2 },\n              '& [data-series=\"misclassified\"] .MuiScatterChart-marker': { fill: \"none\", stroke: t.ink, strokeWidth: 2.5 },\n            }}\n          >\n            <RegionLayer />\n            <ScatterPlot />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n          <ChartsLegend\n            direction=\"vertical\"\n            sx={{\n              width: LEGEND_W,\n              pl: \"24px\",\n              gap: \"12px\",\n              \"& .MuiChartsLegend-label\": { fontSize: 15, color: t.ink },\n              '& [data-series=\"misclassified\"] .MuiChartsLabelMark-fill': { fill: \"none\", stroke: t.ink, strokeWidth: 2.5, r: 5.5 },\n            }}\n          />\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </Box>\n  );\n}\n"}