{"spec_id":"heatmap-clustered","library":"muix","language":"javascript","code":"// anyplot.ai\n// heatmap-clustered: Clustered Heatmap\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-24\n//# anyplot-orientation: square\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useXScale, useYScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst SIZE = window.ANYPLOT_SIZE;\nconst TITLE = \"heatmap-clustered · javascript · muix · anyplot.ai\";\n\nconst HEADER_H = 80;\nconst COL_DENDRO_H = 92;\nconst ANNOT_H = 16;\nconst ROW_DENDRO_LEFT = 22;\nconst ROW_DENDRO_W = 112;\nconst ROW_ANNOT_W = 16;\nconst Y_AXIS_WIDTH = 92;\nconst X_AXIS_HEIGHT = 96;\n\nconst MARGIN = {\n  top: HEADER_H + COL_DENDRO_H + ANNOT_H + 16,\n  right: 176,\n  bottom: 24,\n  left: ROW_DENDRO_LEFT + ROW_DENDRO_W + 8 + ROW_ANNOT_W + 8,\n};\n\n// Columns: set these to your data's column names\nconst GENE = \"Gene\"; // role: row_labels\nconst PATHWAY = \"Pathway\";\nconst SAMPLE = \"Sample\"; // role: column_labels\nconst CONDITION = \"Condition\";\nconst LOG2_FC = \"Log2 fold change\"; // role: matrix\n\n// Data: replace this block with your own records\n// gene|pathway|control base|treated base — each pathway holds two sub-modules\nconst GENE_SPECS = [\n  \"IL6|Inflammatory|-0.6|2.8\",\n  \"TNF|Inflammatory|-0.6|2.8\",\n  \"IL1B|Inflammatory|-0.6|2.8\",\n  \"IFNG|Inflammatory|-0.4|2.1\",\n  \"CXCL10|Inflammatory|-0.4|2.1\",\n  \"STAT1|Inflammatory|-0.4|2.1\",\n  \"COL1A1|Fibrosis|0.4|-2.6\",\n  \"COL3A1|Fibrosis|0.4|-2.6\",\n  \"FN1|Fibrosis|0.4|-2.6\",\n  \"ACTA2|Fibrosis|0.2|-1.8\",\n  \"VIM|Fibrosis|0.2|-1.8\",\n  \"MKI67|Proliferation|1.4|0.7\",\n  \"PCNA|Proliferation|1.4|0.7\",\n  \"TOP2A|Proliferation|1.4|0.7\",\n  \"CCND1|Proliferation|0.9|0.2\",\n  \"CDK4|Proliferation|0.9|0.2\",\n];\n\n// sample|condition|response scale — two replicate sub-groups per condition\nconst SAMPLE_SPECS = [\n  \"Control-01|Control|0.6\",\n  \"Control-02|Control|0.6\",\n  \"Control-03|Control|0.6\",\n  \"Control-04|Control|1.4\",\n  \"Control-05|Control|1.4\",\n  \"Control-06|Control|1.4\",\n  \"Treated-01|Treated|0.75\",\n  \"Treated-02|Treated|0.75\",\n  \"Treated-03|Treated|0.75\",\n  \"Treated-04|Treated|1.2\",\n  \"Treated-05|Treated|1.2\",\n  \"Treated-06|Treated|1.2\",\n];\n\nlet lcgState = 42 >>> 0;\nconst geneOffsets = GENE_SPECS.map(() => {\n  lcgState = (lcgState * 1664525 + 1013904223) >>> 0;\n  return ((lcgState / 4294967296) * 2 - 1) * 0.15;\n});\nconst sampleBatches = SAMPLE_SPECS.map(() => {\n  lcgState = (lcgState * 1664525 + 1013904223) >>> 0;\n  return ((lcgState / 4294967296) * 2 - 1) * 0.12;\n});\n\nconst data: Record<string, string | number>[] = [];\nfor (let i = 0; i < GENE_SPECS.length; i++) {\n  const [gene, pathway, ctrlStr, trtStr] = GENE_SPECS[i].split(\"|\");\n  const ctrlBase = Number(ctrlStr);\n  const trtBase = Number(trtStr);\n  for (let j = 0; j < SAMPLE_SPECS.length; j++) {\n    const [sample, condition, scaleStr] = SAMPLE_SPECS[j].split(\"|\");\n    lcgState = (lcgState * 1664525 + 1013904223) >>> 0;\n    const cellNoise = ((lcgState / 4294967296) * 2 - 1) * 0.2;\n    const base = (condition === \"Control\" ? ctrlBase : trtBase) * Number(scaleStr);\n    const val = Number((base + geneOffsets[i] + sampleBatches[j] + cellNoise).toFixed(4));\n    data.push({\n      [GENE]: gene,\n      [PATHWAY]: pathway,\n      [SAMPLE]: sample,\n      [CONDITION]: condition,\n      [LOG2_FC]: val,\n    });\n  }\n}\n\n// Plot: reads only data and the constants above\nconst genes = Array.from(new Set(data.map((r) => String(r[GENE]))));\nconst samples = Array.from(new Set(data.map((r) => String(r[SAMPLE]))));\nconst conditions = Array.from(new Set(data.map((r) => String(r[CONDITION]))));\nconst pathways = Array.from(new Set(data.map((r) => String(r[PATHWAY]))));\n\nconst usedPaletteColors = new Set<string>([t.div[0].toUpperCase(), t.div[2].toUpperCase()]);\nconst conditionColorMap = new Map<string, string>();\nconditions.forEach((c, idx) => {\n  const col = t.palette[idx];\n  conditionColorMap.set(c, col);\n  usedPaletteColors.add(col.toUpperCase());\n});\nconst availablePathwayColors = t.palette.filter((col) => !usedPaletteColors.has(col.toUpperCase()));\nconst pathwayColorMap = new Map<string, string>();\npathways.forEach((p, idx) => {\n  pathwayColorMap.set(p, availablePathwayColors[idx]);\n});\n\nconst geneToPathway = new Map<string, string>();\nconst sampleToCondition = new Map<string, string>();\nconst valLookup = new Map<string, number>();\nfor (const r of data) {\n  const g = String(r[GENE]);\n  const s = String(r[SAMPLE]);\n  geneToPathway.set(g, String(r[PATHWAY]));\n  sampleToCondition.set(s, String(r[CONDITION]));\n  valLookup.set(`${g}|${s}`, Number(r[LOG2_FC]));\n}\n\nconst rowVectors = genes.map((g) => samples.map((s) => valLookup.get(`${g}|${s}`)!));\nconst colVectors = samples.map((s) => genes.map((g) => valLookup.get(`${g}|${s}`)!));\n\nconst allAbsVals = data.map((r) => Math.abs(Number(r[LOG2_FC])));\nconst colorDomain = Math.ceil(Math.max(...allAbsVals) * 10) / 10;\n\ntype ClusterNode = {\n  id: number;\n  height: number;\n  leaves: number[];\n  leftId: number | null;\n  rightId: number | null;\n  pos: number;\n  centroid: number[];\n  size: number;\n};\n\ntype DendroSeg = { p1: number; d1: number; p2: number; d2: number };\n\nconst clusterTargets = [\n  { vectors: rowVectors, orderOut: [] as number[], segsOut: [] as DendroSeg[], maxHeight: 0 },\n  { vectors: colVectors, orderOut: [] as number[], segsOut: [] as DendroSeg[], maxHeight: 0 },\n];\n\nfor (const target of clusterTargets) {\n  const vecs = target.vectors;\n  const allNodes: ClusterNode[] = vecs.map((v, i) => ({\n    id: i,\n    height: 0,\n    leaves: [i],\n    leftId: null,\n    rightId: null,\n    pos: 0,\n    centroid: v.slice(),\n    size: 1,\n  }));\n  const activeIds = vecs.map((_, i) => i);\n\n  while (activeIds.length > 1) {\n    let minCost = Infinity;\n    let bestAIdx = 0;\n    let bestBIdx = 1;\n    for (let i = 0; i < activeIds.length; i++) {\n      for (let j = i + 1; j < activeIds.length; j++) {\n        const nodeA = allNodes[activeIds[i]];\n        const nodeB = allNodes[activeIds[j]];\n        let sqDist = 0;\n        for (let k = 0; k < nodeA.centroid.length; k++) {\n          const diff = nodeA.centroid[k] - nodeB.centroid[k];\n          sqDist += diff * diff;\n        }\n        const cost = ((nodeA.size * nodeB.size) / (nodeA.size + nodeB.size)) * sqDist;\n        if (cost < minCost) {\n          minCost = cost;\n          bestAIdx = i;\n          bestBIdx = j;\n        }\n      }\n    }\n    const idA = activeIds[bestAIdx];\n    const idB = activeIds[bestBIdx];\n    const nodeA = allNodes[idA];\n    const nodeB = allNodes[idB];\n    const mergedSize = nodeA.size + nodeB.size;\n    const mergedCentroid = nodeA.centroid.map(\n      (v, k) => (v * nodeA.size + nodeB.centroid[k] * nodeB.size) / mergedSize,\n    );\n    const newId = allNodes.length;\n    allNodes.push({\n      id: newId,\n      height: Math.sqrt(minCost),\n      leaves: [...nodeA.leaves, ...nodeB.leaves],\n      leftId: idA,\n      rightId: idB,\n      pos: 0,\n      centroid: mergedCentroid,\n      size: mergedSize,\n    });\n    activeIds.splice(bestBIdx, 1);\n    activeIds.splice(bestAIdx, 1);\n    activeIds.push(newId);\n  }\n\n  const rootNode = allNodes[activeIds[0]];\n  target.maxHeight = rootNode.height;\n\n  const stack = [rootNode.id];\n  while (stack.length > 0) {\n    const curr = allNodes[stack.pop()!];\n    if (curr.leftId === null || curr.rightId === null) {\n      target.orderOut.push(curr.leaves[0]);\n    } else {\n      stack.push(curr.rightId);\n      stack.push(curr.leftId);\n    }\n  }\n\n  const posByLeaf = new Map<number, number>();\n  target.orderOut.forEach((leafIdx, pos) => {\n    posByLeaf.set(leafIdx, pos);\n  });\n\n  for (const node of allNodes) {\n    if (node.leftId === null || node.rightId === null) {\n      node.pos = posByLeaf.get(node.leaves[0])!;\n    } else {\n      node.pos = (allNodes[node.leftId].pos + allNodes[node.rightId].pos) / 2;\n      const lNode = allNodes[node.leftId];\n      const rNode = allNodes[node.rightId];\n      target.segsOut.push(\n        { p1: lNode.pos, d1: node.height, p2: rNode.pos, d2: node.height },\n        { p1: lNode.pos, d1: lNode.height, p2: lNode.pos, d2: node.height },\n        { p1: rNode.pos, d1: rNode.height, p2: rNode.pos, d2: node.height },\n      );\n    }\n  }\n}\n\nconst rowOrder = clusterTargets[0].orderOut;\nconst rowSegments = clusterTargets[0].segsOut;\nconst rowMaxHeight = clusterTargets[0].maxHeight;\n\nconst colOrder = clusterTargets[1].orderOut;\nconst colSegments = clusterTargets[1].segsOut;\nconst colMaxHeight = clusterTargets[1].maxHeight;\n\nconst orderedGeneLabels = rowOrder.map((i) => genes[i]);\nconst orderedSampleLabels = colOrder.map((j) => samples[j]);\n\nconst divStopInts = t.div.map((hex) => parseInt(hex.slice(1), 16));\nconst divStopsRgb: [number, number, number][] = divStopInts.map((v) => [\n  (v >> 16) & 255,\n  (v >> 8) & 255,\n  v & 255,\n]);\n\nconst cells: { id: string; x: string; y: string; fill: string }[] = [];\nfor (let pr = 0; pr < orderedGeneLabels.length; pr++) {\n  for (let pc = 0; pc < orderedSampleLabels.length; pc++) {\n    const gLabel = orderedGeneLabels[pr];\n    const sLabel = orderedSampleLabels[pc];\n    const value = valLookup.get(`${gLabel}|${sLabel}`);\n    if (value === undefined) continue;\n    const pos = Math.min(1, Math.max(0, (value + colorDomain) / (2 * colorDomain)));\n    const isLowerHalf = pos < 0.5;\n    const start = isLowerHalf ? divStopsRgb[0] : divStopsRgb[1];\n    const end = isLowerHalf ? divStopsRgb[1] : divStopsRgb[2];\n    const localRatio = isLowerHalf ? pos / 0.5 : (pos - 0.5) / 0.5;\n    const r = Math.round(start[0] + (end[0] - start[0]) * localRatio);\n    const g = Math.round(start[1] + (end[1] - start[1]) * localRatio);\n    const b = Math.round(start[2] + (end[2] - start[2]) * localRatio);\n    cells.push({\n      id: `${gLabel}-${sLabel}`,\n      x: sLabel,\n      y: gLabel,\n      fill: `rgb(${r}, ${g}, ${b})`,\n    });\n  }\n}\n\nconst colorbarTicks = [\n  -colorDomain,\n  Number((-colorDomain / 2).toFixed(1)),\n  0,\n  Number((colorDomain / 2).toFixed(1)),\n  colorDomain,\n];\n\nfunction ClusteredOverlay() {\n  const xScale = useXScale() as unknown as ((v: string) => number) & { bandwidth: () => number };\n  const yScale = useYScale() as unknown as ((v: string) => number) & { bandwidth: () => number };\n  const drawingArea = useDrawingArea();\n\n  const bw = xScale.bandwidth();\n  const bh = yScale.bandwidth();\n\n  const nCols = orderedSampleLabels.length;\n  const nRows = orderedGeneLabels.length;\n  const colStep = drawingArea.width / nCols;\n  const rowStep = drawingArea.height / nRows;\n\n  const colDendroYBottom = drawingArea.top - ANNOT_H - 10;\n  const colDendroYTop = HEADER_H + 8;\n\n  const rowDendroXLeft = ROW_DENDRO_LEFT;\n  const rowDendroXRight = ROW_DENDRO_LEFT + ROW_DENDRO_W;\n  const rowStripLeft = rowDendroXRight + 8;\n\n  const stripTop = drawingArea.top - ANNOT_H - 4;\n\n  const cbX = drawingArea.left + drawingArea.width + 28;\n  const cbW = 18;\n  const cbTop = drawingArea.top + drawingArea.height * 0.25;\n  const cbH = drawingArea.height * 0.52;\n\n  const legX = drawingArea.left + drawingArea.width + 18;\n  const legY = HEADER_H + 6;\n  const pwStartY = legY + 22 + conditions.length * 22 + 14;\n\n  return (\n    <g>\n      <defs>\n        <linearGradient id=\"clusteredHeatmapDivGrad\" x1=\"0\" y1=\"1\" x2=\"0\" y2=\"0\">\n          <stop offset=\"0%\" stopColor={t.div[0]} />\n          <stop offset=\"50%\" stopColor={t.div[1]} />\n          <stop offset=\"100%\" stopColor={t.div[2]} />\n        </linearGradient>\n      </defs>\n\n      {/* Heatmap cells */}\n      {cells.map((cell) => (\n        <rect\n          key={cell.id}\n          x={xScale(cell.x)}\n          y={yScale(cell.y)}\n          width={bw}\n          height={bh}\n          fill={cell.fill}\n        />\n      ))}\n\n      {/* Sample condition annotation strip */}\n      {orderedSampleLabels.map((sLabel, pos) => {\n        const cond = sampleToCondition.get(sLabel)!;\n        const cx = drawingArea.left + colStep * (pos + 0.5);\n        return (\n          <rect\n            key={`col-strip-${sLabel}`}\n            x={cx - colStep / 2}\n            y={stripTop}\n            width={colStep}\n            height={ANNOT_H}\n            fill={conditionColorMap.get(cond)}\n          />\n        );\n      })}\n\n      {/* Gene pathway annotation strip */}\n      {orderedGeneLabels.map((gLabel, pos) => {\n        const pathway = geneToPathway.get(gLabel)!;\n        const cy = drawingArea.top + rowStep * (pos + 0.5);\n        return (\n          <rect\n            key={`row-strip-${gLabel}`}\n            x={rowStripLeft}\n            y={cy - rowStep / 2}\n            width={ROW_ANNOT_W}\n            height={rowStep}\n            fill={pathwayColorMap.get(pathway)}\n          />\n        );\n      })}\n\n      {/* Column dendrogram (samples) */}\n      {colSegments.map((s, i) => {\n        const x1 = drawingArea.left + colStep * (s.p1 + 0.5);\n        const x2 = drawingArea.left + colStep * (s.p2 + 0.5);\n        const y1 = colDendroYBottom - (s.d1 / colMaxHeight) * (colDendroYBottom - colDendroYTop);\n        const y2 = colDendroYBottom - (s.d2 / colMaxHeight) * (colDendroYBottom - colDendroYTop);\n        return (\n          <line\n            key={`col-seg-${i}`}\n            x1={x1}\n            y1={y1}\n            x2={x2}\n            y2={y2}\n            stroke={t.ink}\n            strokeWidth={1.5}\n            strokeLinecap=\"round\"\n          />\n        );\n      })}\n\n      {/* Row dendrogram (genes) */}\n      {rowSegments.map((s, i) => {\n        const x1 = rowDendroXRight - (s.d1 / rowMaxHeight) * (rowDendroXRight - rowDendroXLeft);\n        const x2 = rowDendroXRight - (s.d2 / rowMaxHeight) * (rowDendroXRight - rowDendroXLeft);\n        const y1 = drawingArea.top + rowStep * (s.p1 + 0.5);\n        const y2 = drawingArea.top + rowStep * (s.p2 + 0.5);\n        return (\n          <line\n            key={`row-seg-${i}`}\n            x1={x1}\n            y1={y1}\n            x2={x2}\n            y2={y2}\n            stroke={t.ink}\n            strokeWidth={1.5}\n            strokeLinecap=\"round\"\n          />\n        );\n      })}\n\n      {/* Condition & Pathway legend with square swatches and section titles */}\n      <text x={legX} y={legY} fontSize={14} fontWeight={600} fill={t.ink} dominantBaseline=\"central\">\n        {CONDITION}\n      </text>\n      {conditions.map((cond, idx) => {\n        const cy = legY + 22 + idx * 22;\n        return (\n          <g key={`cond-leg-${cond}`}>\n            <rect x={legX} y={cy - 6} width={12} height={12} rx={2} fill={conditionColorMap.get(cond)} />\n            <text\n              x={legX + 18}\n              y={cy}\n              fontSize={14}\n              fill={t.inkSoft}\n              dominantBaseline=\"central\"\n            >\n              {cond}\n            </text>\n          </g>\n        );\n      })}\n      <text x={legX} y={pwStartY} fontSize={14} fontWeight={600} fill={t.ink} dominantBaseline=\"central\">\n        {PATHWAY}\n      </text>\n      {pathways.map((pw, idx) => {\n        const py = pwStartY + 22 + idx * 22;\n        return (\n          <g key={`pw-leg-${pw}`}>\n            <rect x={legX} y={py - 6} width={12} height={12} rx={2} fill={pathwayColorMap.get(pw)} />\n            <text x={legX + 18} y={py} fontSize={14} fill={t.inkSoft} dominantBaseline=\"central\">\n              {pw}\n            </text>\n          </g>\n        );\n      })}\n\n      {/* Diverging colorbar */}\n      <rect x={cbX} y={cbTop} width={cbW} height={cbH} fill=\"url(#clusteredHeatmapDivGrad)\" rx={3} />\n      {colorbarTicks.map((tick) => {\n        const ty = cbTop + cbH * (1 - (tick + colorDomain) / (2 * colorDomain));\n        return (\n          <g key={tick}>\n            <line x1={cbX + cbW} y1={ty} x2={cbX + cbW + 6} y2={ty} stroke={t.inkSoft} strokeWidth={1} />\n            <text\n              x={cbX + cbW + 10}\n              y={ty}\n              fontSize={14}\n              fill={t.inkSoft}\n              dominantBaseline=\"central\"\n            >\n              {tick.toFixed(1)}\n            </text>\n          </g>\n        );\n      })}\n      <text\n        x={cbX + cbW + 64}\n        y={cbTop + cbH / 2}\n        fontSize={14}\n        fill={t.inkSoft}\n        textAnchor=\"middle\"\n        transform={`rotate(-90, ${cbX + cbW + 64}, ${cbTop + cbH / 2})`}\n      >\n        {LOG2_FC}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const subtitle = `Ward hierarchical clustering of ${LOG2_FC} (${orderedGeneLabels.length} ${GENE}s × ${orderedSampleLabels.length} ${SAMPLE}s)`;\n\n  return (\n    <ChartsContainer\n      width={SIZE.width}\n      height={SIZE.height}\n      series={[]}\n      margin={MARGIN}\n      skipAnimation\n      xAxis={[\n        {\n          scaleType: \"band\",\n          data: orderedSampleLabels,\n          height: X_AXIS_HEIGHT,\n          categoryGapRatio: 0.1,\n          disableLine: true,\n          disableTicks: true,\n          tickLabelStyle: { fontSize: 14, fill: t.inkSoft, angle: -45, textAnchor: \"end\" },\n        },\n      ]}\n      yAxis={[\n        {\n          scaleType: \"band\",\n          data: orderedGeneLabels,\n          width: Y_AXIS_WIDTH,\n          categoryGapRatio: 0.1,\n          disableLine: true,\n          disableTicks: true,\n          tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n        },\n      ]}\n    >\n      <ClusteredOverlay />\n      <ChartsXAxis />\n      <ChartsYAxis />\n      <text\n        x={SIZE.width / 2}\n        y={34}\n        fontSize={22}\n        fontWeight={600}\n        fill={t.ink}\n        textAnchor=\"middle\"\n      >\n        {TITLE}\n      </text>\n      <text\n        x={SIZE.width / 2}\n        y={60}\n        fontSize={15}\n        fill={t.inkSoft}\n        textAnchor=\"middle\"\n      >\n        {subtitle}\n      </text>\n    </ChartsContainer>\n  );\n}\n"}