{"spec_id":"dendrogram-radial","library":"muix","language":"javascript","code":"// anyplot.ai\n// dendrogram-radial: Radial Dendrogram\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 88/100 | Updated: 2026-10-24\n//# anyplot-orientation: square\n\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\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 TITLE = \"dendrogram-radial · javascript · muix · anyplot.ai\";\nconst FONT = \"Inter, system-ui, -apple-system, sans-serif\";\nconst REF_RINGS = [0.25, 0.5, 0.75, 1.0];\nconst RING_INNER = 1.06;\nconst RING_OUTER = 1.13;\nconst RING_MID = (RING_INNER + RING_OUTER) / 2;\nconst LABEL_RADIUS = 1.21;\nconst DOMAIN_LIMIT = 1.38;\nconst ARC_STEPS = 14;\n\n// Columns: set these to your data's column names\nconst SAMPLE_ID = \"Sample ID\"; // role: labels\nconst REGION = \"Origin region\"; // role: clusters\nconst ACIDITY = \"Acidity\"; // role: linkage_matrix\nconst BODY = \"Body\"; // role: linkage_matrix\nconst SWEETNESS = \"Sweetness\"; // role: linkage_matrix\nconst FLORAL = \"Floral aroma\"; // role: linkage_matrix\nconst EARTHINESS = \"Earthiness\"; // role: linkage_matrix\n\n// Data: replace this block with your own records\nconst data = (() => {\n  const sampleProfiles = [\n    { code: \"ETH\", name: \"Ethiopian Highlands\", center: [8.5, 3.0, 7.0, 8.5, 1.0] },\n    { code: \"KEN\", name: \"Kenyan Highlands\", center: [8.8, 4.0, 6.0, 5.0, 1.5] },\n    { code: \"COL\", name: \"Colombian Andes\", center: [5.5, 6.0, 7.5, 2.5, 2.0] },\n    { code: \"GUA\", name: \"Guatemalan Volcanic\", center: [6.0, 5.0, 5.5, 4.0, 2.5] },\n    { code: \"SUM\", name: \"Sumatran Lowlands\", center: [2.0, 8.5, 3.0, 1.0, 8.5] },\n  ];\n  const rows: Record<string, string | number>[] = [];\n  let lcgState = 42 >>> 0;\n  for (const reg of sampleProfiles) {\n    for (let s = 0; s < 6; s++) {\n      const vals: number[] = [];\n      for (let d = 0; d < 5; d++) {\n        lcgState = (Math.imul(1664525, lcgState) + 1013904223) >>> 0;\n        const u1 = Math.max(lcgState / 4294967296, 1e-9);\n        lcgState = (Math.imul(1664525, lcgState) + 1013904223) >>> 0;\n        const u2 = lcgState / 4294967296;\n        const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n        vals.push(reg.center[d] + z * 0.7);\n      }\n      rows.push({\n        [SAMPLE_ID]: `${reg.code}-${s + 1}`,\n        [REGION]: reg.name,\n        [ACIDITY]: vals[0],\n        [BODY]: vals[1],\n        [SWEETNESS]: vals[2],\n        [FLORAL]: vals[3],\n        [EARTHINESS]: vals[4],\n      });\n    }\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst FEATURE_COLS = [ACIDITY, BODY, SWEETNESS, FLORAL, EARTHINESS];\nconst n = data.length;\nconst nodeCount = 2 * n - 1;\nconst REGION_NAMES = Array.from(new Set(data.map((d) => String(d[REGION]))));\nconst REGION_COLORS = Object.fromEntries(\n  REGION_NAMES.map((reg, i) => [reg, t.palette[i]]),\n);\n\nconst D = Array.from({ length: nodeCount }, () => new Array(nodeCount).fill(Infinity));\nfor (let i = 0; i < n; i++) {\n  for (let j = i + 1; j < n; j++) {\n    let sumSq = 0;\n    for (const col of FEATURE_COLS) {\n      const diff = Number(data[i][col]) - Number(data[j][col]);\n      sumSq += diff * diff;\n    }\n    const dist = Math.sqrt(sumSq);\n    D[i][j] = dist;\n    D[j][i] = dist;\n  }\n}\n\nconst active = new Set(Array.from({ length: n }, (_, i) => i));\nconst linkage: [number, number, number][] = [];\nlet nextId = n;\nwhile (active.size > 1) {\n  let a = -1;\n  let b = -1;\n  let best = Infinity;\n  const ids = Array.from(active);\n  for (let i = 0; i < ids.length; i++) {\n    for (let j = i + 1; j < ids.length; j++) {\n      if (D[ids[i]][ids[j]] < best) {\n        best = D[ids[i]][ids[j]];\n        a = ids[i];\n        b = ids[j];\n      }\n    }\n  }\n  const newId = nextId++;\n  active.forEach((c) => {\n    if (c === a || c === b) return;\n    const d = Math.max(D[a][c], D[b][c]);\n    D[newId][c] = d;\n    D[c][newId] = d;\n  });\n  linkage.push([a, b, best]);\n  active.delete(a);\n  active.delete(b);\n  active.add(newId);\n}\n\nconst root = nextId - 1;\nconst maxHeight = Math.max(...linkage.map((row) => row[2]));\n\nconst order: number[] = [];\nconst stack: number[] = [root];\nwhile (stack.length > 0) {\n  const nodeId = stack.pop()!;\n  if (nodeId < n) {\n    order.push(nodeId);\n  } else {\n    const [a, b] = linkage[nodeId - n];\n    stack.push(b);\n    stack.push(a);\n  }\n}\n\nconst angleOf = new Array(nodeCount).fill(0);\nconst radiusOf = new Array(nodeCount).fill(0);\nconst regionOf: (string | null)[] = new Array(nodeCount).fill(null);\n\norder.forEach((leafId, idx) => {\n  angleOf[leafId] = Math.PI / 2 - idx * ((2 * Math.PI) / n);\n  radiusOf[leafId] = 1;\n  regionOf[leafId] = String(data[leafId][REGION]);\n});\n\nfor (let id = n; id < nodeCount; id++) {\n  const [a, b, height] = linkage[id - n];\n  angleOf[id] = (angleOf[a] + angleOf[b]) / 2;\n  radiusOf[id] = 1 - height / maxHeight;\n  regionOf[id] =\n    regionOf[a] !== null && regionOf[a] === regionOf[b] ? regionOf[a] : null;\n}\n\nconst SUBTITLE = `${n} leaves across ${REGION_NAMES.length} ${REGION}s · complete-linkage clustering over ${FEATURE_COLS.length} features`;\n\nconst scatterSeries = REGION_NAMES.map((reg) => ({\n  type: \"scatter\" as const,\n  id: reg,\n  data: data\n    .map((row, i) => ({ row, i }))\n    .filter(({ row }) => String(row[REGION]) === reg)\n    .map(({ row, i }) => ({\n      id: String(row[SAMPLE_ID]),\n      x: Math.cos(angleOf[i]),\n      y: Math.sin(angleOf[i]),\n    })),\n  label: reg,\n  color: REGION_COLORS[reg],\n  markerSize: 8,\n  xAxisId: \"x\",\n  yAxisId: \"y\",\n}));\n\nfunction RadialDendrogram() {\n  const xs = useXScale(\"x\") as any;\n  const ys = useYScale(\"y\") as any;\n\n  const cx = xs(0);\n  const cy = ys(0);\n  const unitPx = Math.abs(xs(1) - cx);\n  const ringThickness = Math.abs(xs(RING_OUTER) - xs(RING_INNER));\n\n  const branches = [];\n  for (let id = n; id < nodeCount; id++) {\n    const [a, b] = linkage[id - n];\n    const rParent = radiusOf[id];\n    const bridgeColor =\n      regionOf[id] !== null ? REGION_COLORS[regionOf[id]!] : t.inkSoft;\n\n    let diff = angleOf[b] - angleOf[a];\n    while (diff > Math.PI) diff -= 2 * Math.PI;\n    while (diff < -Math.PI) diff += 2 * Math.PI;\n    let dArc = \"\";\n    for (let k = 0; k <= ARC_STEPS; k++) {\n      const th = angleOf[a] + (diff * k) / ARC_STEPS;\n      const px = xs(rParent * Math.cos(th));\n      const py = ys(rParent * Math.sin(th));\n      dArc += `${k === 0 ? \"M\" : \"L\"}${px.toFixed(1)},${py.toFixed(1)} `;\n    }\n    branches.push(\n      <path\n        key={`arc-${id}`}\n        d={dArc}\n        fill=\"none\"\n        stroke={bridgeColor}\n        strokeWidth={2.5}\n        strokeLinecap=\"round\"\n      />,\n    );\n\n    for (const child of [a, b]) {\n      const childColor =\n        regionOf[child] !== null ? REGION_COLORS[regionOf[child]!] : t.inkSoft;\n      const th = angleOf[child];\n      const rChild = radiusOf[child];\n      branches.push(\n        <line\n          key={`seg-${id}-${child}`}\n          x1={xs(rParent * Math.cos(th))}\n          y1={ys(rParent * Math.sin(th))}\n          x2={xs(rChild * Math.cos(th))}\n          y2={ys(rChild * Math.sin(th))}\n          stroke={childColor}\n          strokeWidth={2.5}\n          strokeLinecap=\"round\"\n        />,\n      );\n    }\n  }\n\n  const halfLeafSpan = (Math.PI / n) * 0.72;\n  const metadataRing = order.map((leafId) => {\n    const th0 = angleOf[leafId] - halfLeafSpan;\n    const th1 = angleOf[leafId] + halfLeafSpan;\n    let dRing = \"\";\n    for (let k = 0; k <= 4; k++) {\n      const th = th0 + ((th1 - th0) * k) / 4;\n      const px = xs(RING_MID * Math.cos(th));\n      const py = ys(RING_MID * Math.sin(th));\n      dRing += `${k === 0 ? \"M\" : \"L\"}${px.toFixed(1)},${py.toFixed(1)} `;\n    }\n    return (\n      <path\n        key={`ring-${leafId}`}\n        d={dRing}\n        fill=\"none\"\n        stroke={REGION_COLORS[String(data[leafId][REGION])]}\n        strokeWidth={ringThickness}\n        strokeLinecap=\"butt\"\n      />\n    );\n  });\n\n  const labels = order.map((leafId) => {\n    const theta = angleOf[leafId];\n    const px = xs(LABEL_RADIUS * Math.cos(theta));\n    const py = ys(LABEL_RADIUS * Math.sin(theta));\n    const rotDeg = (Math.atan2(py - cy, px - cx) * 180) / Math.PI;\n    const flip = Math.cos(theta) < 0;\n    return (\n      <text\n        key={`label-${leafId}`}\n        x={px}\n        y={py}\n        transform={`rotate(${flip ? rotDeg + 180 : rotDeg}, ${px}, ${py})`}\n        textAnchor={flip ? \"end\" : \"start\"}\n        dominantBaseline=\"middle\"\n        fontSize={14}\n        fontWeight={500}\n        fontFamily={FONT}\n        fill={t.inkSoft}\n      >\n        {String(data[leafId][SAMPLE_ID])}\n      </text>\n    );\n  });\n\n  return (\n    <g>\n      {REF_RINGS.map((frac) => (\n        <circle\n          key={`ref-${frac}`}\n          cx={cx}\n          cy={cy}\n          r={unitPx * frac}\n          fill=\"none\"\n          stroke={t.grid}\n          strokeWidth={1}\n        />\n      ))}\n      {metadataRing}\n      {branches}\n      <circle cx={cx} cy={cy} r={5} fill={t.inkSoft} />\n      {labels}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const W = window.ANYPLOT_SIZE.width;\n  const H = window.ANYPLOT_SIZE.height;\n  const HEADER_H = 84;\n  const LEGEND_H = 76;\n  const chartSize = Math.min(W, H - HEADER_H - LEGEND_H);\n\n  return (\n    <div\n      style={{\n        width: W,\n        height: H,\n        background: t.pageBg,\n        fontFamily: FONT,\n        display: \"flex\",\n        flexDirection: \"column\",\n        alignItems: \"center\",\n      }}\n    >\n      <div\n        style={{\n          height: HEADER_H,\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 4,\n          paddingTop: 10,\n        }}\n      >\n        <span style={{ fontSize: 22, fontWeight: 700, color: t.ink }}>{TITLE}</span>\n        <span style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</span>\n      </div>\n      <ChartsDataProvider\n        width={chartSize}\n        height={chartSize}\n        skipAnimation\n        series={scatterSeries}\n        margin={{ top: 16, right: 16, bottom: 16, left: 16 }}\n        xAxis={[{ id: \"x\", min: -DOMAIN_LIMIT, max: DOMAIN_LIMIT, position: \"none\" }]}\n        yAxis={[{ id: \"y\", min: -DOMAIN_LIMIT, max: DOMAIN_LIMIT, position: \"none\" }]}\n      >\n        <ChartsWrapper\n          legendPosition={{ horizontal: \"center\", vertical: \"bottom\" }}\n          legendDirection=\"horizontal\"\n        >\n          <ChartsLegend sx={{ fontSize: 14, fontFamily: FONT, color: t.ink, gap: 3.5, pt: 3 }} />\n          <ChartsSurface>\n            <RadialDendrogram />\n            <ScatterPlot />\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}