{"spec_id":"tree-decision","library":"muix","language":"javascript","code":"// anyplot.ai\n// tree-decision: Decision Tree Visualization with Probabilities\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst DECISION = \"decision\"; // the three node types of the spec, each drawn as its own shape\nconst CHANCE = \"chance\";\nconst TERMINAL = \"terminal\";\nconst DEPTH_PAD_LEFT = 0.3; // in depth steps: room left of the root for its question\nconst DEPTH_PAD_RIGHT = 0.7; // in depth steps: room right of the deepest terminals for their payoffs\nconst SLOT_PAD = 0.6; // in leaf slots: room above the first and below the last leaf\nconst NODE_R = 18; // half the side of a node mark, px\nconst EDGE_FONT = 15; // branch label size, px\nconst QUESTION_FONT = 16; // question label size, px\nconst QUESTION_GAP = 12; // px between a question's baseline and the steepest edge under it\nconst TITLE = \"tree-decision · javascript · muix · anyplot.ai\";\nconst TITLE_H = 76;\nconst LEGEND_H = 44;\n\n// Columns: set these to your data's column names\nconst NODE_ID = \"Node\"; // role: node_id\nconst NODE_TYPE = \"Node type\"; // role: node_type\nconst PARENT_ID = \"Parent\"; // role: parent_id\nconst BRANCH_LABEL = \"Branch\"; // role: branch_label\nconst PROBABILITY = \"Probability\"; // role: probability\nconst PAYOFF = \"Payoff (USD thousand)\"; // role: payoff\nconst QUESTION = \"Question\"; // role: extra\n\n// Data: replace this block with your own records, one object per row\n// A two-stage product-launch decision: launch or not, then react to the\n// demand that materialises. The parent of the root is null; probabilities\n// sit on chance branches only and payoffs on terminal nodes only.\nconst data = [\n  { [NODE_ID]: \"D0\", [NODE_TYPE]: \"decision\", [PARENT_ID]: null, [BRANCH_LABEL]: null, [PROBABILITY]: null, [PAYOFF]: null, [QUESTION]: \"Launch product?\" },\n  { [NODE_ID]: \"C1\", [NODE_TYPE]: \"chance\", [PARENT_ID]: \"D0\", [BRANCH_LABEL]: \"Launch\", [PROBABILITY]: null, [PAYOFF]: null, [QUESTION]: \"Initial demand\" },\n  { [NODE_ID]: \"T6\", [NODE_TYPE]: \"terminal\", [PARENT_ID]: \"D0\", [BRANCH_LABEL]: \"Don't launch\", [PROBABILITY]: null, [PAYOFF]: 0, [QUESTION]: null },\n  { [NODE_ID]: \"D1\", [NODE_TYPE]: \"decision\", [PARENT_ID]: \"C1\", [BRANCH_LABEL]: \"High demand\", [PROBABILITY]: 0.6, [PAYOFF]: null, [QUESTION]: \"Expand capacity?\" },\n  { [NODE_ID]: \"D2\", [NODE_TYPE]: \"decision\", [PARENT_ID]: \"C1\", [BRANCH_LABEL]: \"Low demand\", [PROBABILITY]: 0.4, [PAYOFF]: null, [QUESTION]: \"Discount price?\" },\n  { [NODE_ID]: \"C2\", [NODE_TYPE]: \"chance\", [PARENT_ID]: \"D1\", [BRANCH_LABEL]: \"Expand\", [PROBABILITY]: null, [PAYOFF]: null, [QUESTION]: \"Sustained demand\" },\n  { [NODE_ID]: \"T3\", [NODE_TYPE]: \"terminal\", [PARENT_ID]: \"D1\", [BRANCH_LABEL]: \"Don't expand\", [PROBABILITY]: null, [PAYOFF]: 500, [QUESTION]: null },\n  { [NODE_ID]: \"T4\", [NODE_TYPE]: \"terminal\", [PARENT_ID]: \"D2\", [BRANCH_LABEL]: \"Discount\", [PROBABILITY]: null, [PAYOFF]: 150, [QUESTION]: null },\n  { [NODE_ID]: \"T5\", [NODE_TYPE]: \"terminal\", [PARENT_ID]: \"D2\", [BRANCH_LABEL]: \"Hold price\", [PROBABILITY]: null, [PAYOFF]: 80, [QUESTION]: null },\n  { [NODE_ID]: \"T1\", [NODE_TYPE]: \"terminal\", [PARENT_ID]: \"C2\", [BRANCH_LABEL]: \"Demand holds\", [PROBABILITY]: 0.7, [PAYOFF]: 850, [QUESTION]: null },\n  { [NODE_ID]: \"T2\", [NODE_TYPE]: \"terminal\", [PARENT_ID]: \"C2\", [BRANCH_LABEL]: \"Demand fades\", [PROBABILITY]: 0.3, [PAYOFF]: 200, [QUESTION]: null },\n];\n\n// Plot: reads only data and the constants above\nconst byId = new Map(data.map((d) => [d[NODE_ID], d]));\nconst children = new Map(data.map((d) => [d[NODE_ID], []]));\ndata.forEach((d) => {\n  if (d[PARENT_ID] != null) children.get(d[PARENT_ID])?.push(d[NODE_ID]);\n});\nconst roots = data.filter((d) => d[PARENT_ID] == null).map((d) => d[NODE_ID]);\n\n// Depth: the number of ancestors above a node\nconst depth = new Map(\n  data.map((d) => {\n    let steps = 0;\n    let parent = d[PARENT_ID];\n    while (parent != null && steps < data.length) {\n      steps += 1;\n      parent = byId.get(parent)?.[PARENT_ID] ?? null;\n    }\n    return [d[NODE_ID], steps];\n  }),\n);\n\n// Leaves take one slot each in depth-first order; a parent sits midway between\n// its first and last child, so subtrees never overlap.\nconst preorder = [];\nconst stack = [...roots].reverse();\nwhile (stack.length > 0) {\n  const id = stack.pop();\n  preorder.push(id);\n  stack.push(...[...children.get(id)].reverse());\n}\nconst slot = new Map();\npreorder\n  .filter((id) => children.get(id).length === 0)\n  .forEach((id, i) => slot.set(id, i));\nconst bottomUp = [...preorder].sort((a, b) => depth.get(b) - depth.get(a));\n\n// EMV rollback, deepest nodes first: a terminal is worth its payoff, a chance\n// node the probability-weighted mean of its branches, a decision node its best\n// branch; every other branch of a decision is pruned. Pruning stays local to\n// the decision that rejected the branch.\nconst emv = new Map();\nconst pruned = new Set();\nbottomUp.forEach((id) => {\n  const node = byId.get(id);\n  const kids = children.get(id);\n  if (kids.length > 0) {\n    const kidSlots = kids.map((k) => slot.get(k));\n    slot.set(id, (Math.min(...kidSlots) + Math.max(...kidSlots)) / 2);\n  }\n  if (kids.length === 0) {\n    emv.set(id, node[PAYOFF]);\n  } else if (node[NODE_TYPE] === CHANCE) {\n    emv.set(id, kids.reduce((sum, k) => sum + byId.get(k)[PROBABILITY] * emv.get(k), 0));\n  } else {\n    const best = kids.reduce((b, k) => (emv.get(k) > emv.get(b) ? k : b), kids[0]);\n    emv.set(id, emv.get(best));\n    kids.filter((k) => k !== best).forEach((k) => pruned.add(k));\n  }\n});\n\nconst maxDepth = Math.max(...depth.values());\nconst slotCount = Math.max(...slot.values());\nconst fmt = new Intl.NumberFormat(\"en-US\", { maximumFractionDigits: 0 });\nconst nodeTypes = [...new Set(data.map((d) => d[NODE_TYPE]))];\nconst typeColor = { [DECISION]: t.palette[0], [CHANCE]: t.palette[1] };\nconst PAYOFF_UNIT = PAYOFF.match(/\\(([^)]+)\\)\\s*$/)?.[1] ?? \"\";\nconst terminalCount = data.filter((d) => children.get(d[NODE_ID]).length === 0).length;\nconst SUBTITLE = `${data.length} nodes, ${terminalCount} terminal payoffs · payoffs and EMV in ${PAYOFF_UNIT}, rolled back from the terminals · root EMV ${fmt.format(emv.get(roots[0]))}`;\n\n// The community package has no tree component: a custom layer draws edges,\n// labels and node marks in the container's linear scales (depth by leaf slot).\nfunction DecisionTree() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const edges = data.filter((d) => d[PARENT_ID] != null && byId.has(d[PARENT_ID]));\n\n  return (\n    <g>\n      {edges.map((d) => {\n        const id = d[NODE_ID];\n        const x1 = xScale(depth.get(d[PARENT_ID]));\n        const y1 = yScale(slot.get(d[PARENT_ID]));\n        const x2 = xScale(depth.get(id));\n        const y2 = yScale(slot.get(id));\n        const mx = (x1 + x2) / 2;\n        const my = (y1 + y2) / 2;\n        const angle = Math.atan2(y2 - y1, x2 - x1);\n        const [cos, sin] = [Math.cos(angle), Math.sin(angle)];\n        const isPruned = pruned.has(id);\n        const probability = d[PROBABILITY];\n        const label = probability != null ? `${d[BRANCH_LABEL]} · p = ${probability.toFixed(2)}` : d[BRANCH_LABEL];\n        // The label sits above a rising branch and below a falling one, pushed\n        // out along the normal far enough that its horizontal box clears the line.\n        const halfW = String(label).length * EDGE_FONT * 0.28;\n        const offset = halfW * Math.abs(sin) + (EDGE_FONT / 2) * Math.abs(cos) + 8;\n        const [nx, ny] = y2 <= y1 ? [sin, -cos] : [-sin, cos];\n        return (\n          <g key={`edge-${id}`}>\n            <g opacity={isPruned ? 0.55 : 1}>\n              <line\n                x1={x1 + cos * NODE_R}\n                y1={y1 + sin * NODE_R}\n                x2={x2 - cos * NODE_R}\n                y2={y2 - sin * NODE_R}\n                stroke={t.inkSoft}\n                strokeWidth={isPruned ? 1.8 : 2.6}\n                strokeDasharray={isPruned ? \"7 5\" : undefined}\n              />\n              {isPruned && (\n                <g stroke={t.ink} strokeWidth={2} transform={`rotate(25 ${mx} ${my})`}>\n                  <line x1={mx - 4} y1={my - 9} x2={mx - 4} y2={my + 9} />\n                  <line x1={mx + 4} y1={my - 9} x2={mx + 4} y2={my + 9} />\n                </g>\n              )}\n            </g>\n            <text\n              x={mx + nx * offset}\n              y={my + ny * offset}\n              fontSize={EDGE_FONT}\n              fill={isPruned ? t.inkSoft : t.ink}\n              textAnchor=\"middle\"\n              dominantBaseline=\"middle\"\n            >\n              {label}\n            </text>\n          </g>\n        );\n      })}\n      {data.map((d) => {\n        const id = d[NODE_ID];\n        const cx = xScale(depth.get(id));\n        const cy = yScale(slot.get(id));\n        const type = d[NODE_TYPE];\n        const isLeaf = children.get(id).length === 0;\n        // The question sits above its node, raised until it clears every edge\n        // that leaves the node upward within the label's half width.\n        const questionHalfW = String(d[QUESTION] ?? \"\").length * QUESTION_FONT * 0.3;\n        const edgeRise = Math.max(\n          0,\n          ...[d[PARENT_ID], ...children.get(id)]\n            .filter((n) => n != null && byId.has(n))\n            .map((n) => {\n              const ny = yScale(slot.get(n));\n              return ny < cy ? (questionHalfW * (cy - ny)) / Math.max(1, Math.abs(xScale(depth.get(n)) - cx)) : 0;\n            }),\n        );\n        const questionY = cy - Math.max(NODE_R + 14, edgeRise + QUESTION_GAP);\n        return (\n          <g key={`node-${id}`}>\n            <g opacity={pruned.has(id) ? 0.55 : 1}>\n              {type === DECISION && (\n                <rect x={cx - NODE_R} y={cy - NODE_R} width={NODE_R * 2} height={NODE_R * 2} fill={typeColor[DECISION]} stroke={t.pageBg} strokeWidth={2.5} />\n              )}\n              {type === CHANCE && <circle cx={cx} cy={cy} r={NODE_R + 2} fill={typeColor[CHANCE]} stroke={t.pageBg} strokeWidth={2.5} />}\n              {type === TERMINAL && (\n                <polygon\n                  points={`${cx - NODE_R * 0.85},${cy - NODE_R * 0.85} ${cx - NODE_R * 0.85},${cy + NODE_R * 0.85} ${cx + NODE_R},${cy}`}\n                  fill={t.elevatedBg}\n                  stroke={t.ink}\n                  strokeWidth={2}\n                />\n              )}\n            </g>\n            {!isLeaf && d[QUESTION] != null && (\n              <text x={cx} y={questionY} fontSize={QUESTION_FONT} fontWeight={600} fill={t.ink} textAnchor=\"middle\">\n                {d[QUESTION]}\n              </text>\n            )}\n            {!isLeaf && (\n              <text x={cx} y={cy + NODE_R + 24} fontSize={15} fontWeight={600} fill={t.inkSoft} textAnchor=\"middle\">\n                EMV {fmt.format(emv.get(id))}\n              </text>\n            )}\n            {isLeaf && (\n              <text x={cx + NODE_R + 12} y={cy} fontSize={16} fontWeight={600} fill={pruned.has(id) ? t.inkSoft : t.ink} dominantBaseline=\"middle\">\n                {fmt.format(d[PAYOFF])}\n              </text>\n            )}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const legendItems = [\n    { key: DECISION, label: \"Decision node\", mark: <rect x={1} y={1} width={16} height={16} fill={typeColor[DECISION]} /> },\n    { key: CHANCE, label: \"Chance node\", mark: <circle cx={9} cy={9} r={8.5} fill={typeColor[CHANCE]} /> },\n    { key: TERMINAL, label: \"Terminal payoff\", mark: <polygon points=\"2,2 2,16 17,9\" fill={t.elevatedBg} stroke={t.ink} strokeWidth={1.6} /> },\n  ].filter((item) => nodeTypes.includes(item.key));\n\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: TITLE_H, padding: \"16px 40px 0\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.2, marginTop: 8 }}>{SUBTITLE}</div>\n      </div>\n      <div style={{ height: LEGEND_H, display: \"flex\", alignItems: \"center\", gap: 32, padding: \"0 40px\" }}>\n        {legendItems.map((item) => (\n          <div key={item.key} style={{ display: \"flex\", alignItems: \"center\", gap: 10 }}>\n            <svg width={18} height={18}>{item.mark}</svg>\n            <span style={{ fontSize: 15, color: t.ink }}>{item.label}</span>\n          </div>\n        ))}\n        {pruned.size > 0 && (\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 10 }}>\n            <svg width={34} height={18}>\n              <line x1={0} y1={9} x2={34} y2={9} stroke={t.inkSoft} strokeWidth={1.8} strokeDasharray=\"6 4\" opacity={0.55} />\n              <line x1={13} y1={2} x2={13} y2={16} stroke={t.ink} strokeWidth={2} transform=\"rotate(25 15 9)\" opacity={0.55} />\n              <line x1={19} y1={2} x2={19} y2={16} stroke={t.ink} strokeWidth={2} transform=\"rotate(25 17 9)\" opacity={0.55} />\n            </svg>\n            <span style={{ fontSize: 15, color: t.ink }}>Pruned branch</span>\n          </div>\n        )}\n      </div>\n      <ChartsContainer\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        series={[]}\n        skipAnimation\n        margin={{ top: 24, right: 40, bottom: 24, left: 40 }}\n        xAxis={[{ id: \"depth\", scaleType: \"linear\", min: -DEPTH_PAD_LEFT, max: maxDepth + DEPTH_PAD_RIGHT, position: \"none\" }]}\n        yAxis={[{ id: \"slot\", scaleType: \"linear\", min: -SLOT_PAD, max: slotCount + SLOT_PAD, reverse: true, position: \"none\" }]}\n      >\n        <DecisionTree />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}