{"spec_id":"heatmap-chromagram","library":"muix","language":"javascript","code":"// anyplot.ai\n// heatmap-chromagram: Music Chromagram (Pitch Class Distribution over Time)\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-24\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ContinuousColorLegend } 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 { useDrawingArea, useXScale, useZColorScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst { width, height } = window.ANYPLOT_SIZE;\nconst TITLE = \"heatmap-chromagram · javascript · muix · anyplot.ai\";\nconst FONT = \"Inter, system-ui, sans-serif\";\nconst PITCH_CLASSES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\nconst ENERGY_MIN = 0;\nconst ENERGY_MAX = 1;\nconst LEGEND_W = 110;\nconst LEGEND_H = 520;\n\n// Columns: set these to your data's column names\nconst TIME = \"Time (s)\"; // role: time\nconst PITCH_CLASS = \"Pitch class\"; // role: pitch_class\nconst ENERGY = \"Energy\"; // role: energy\nconst CHORD = \"Chord\";\n\n// Data: replace this block with your own records\nconst N_FRAMES = 80;\nconst SEC_PER_FRAME = 0.05;\n\nconst CHORD_SECTIONS = [\n  \"C major|0,4,7|0|20\",\n  \"G major|7,11,2|20|40\",\n  \"A minor|9,0,4|40|60\",\n  \"F major|5,9,0|60|80\",\n];\n\nconst parsedChords = CHORD_SECTIONS.map((s) => {\n  const [label, pcsStr, startStr, endStr] = s.split(\"|\");\n  const pcs = pcsStr.split(\",\").map(Number);\n  const overtones = pcs.map((p) => (p + 7) % 12);\n  return {\n    label,\n    pcs,\n    overtones,\n    start: Number(startStr),\n    end: Number(endStr),\n  };\n});\n\nlet lcgState = 42 >>> 0;\nconst data: Record<string, string | number>[] = [];\n\nfor (let pc = 0; pc < PITCH_CLASSES.length; pc++) {\n  const pitchName = PITCH_CLASSES[pc];\n  for (let f = 0; f < N_FRAMES; f++) {\n    lcgState = (((lcgState * 1664525) >>> 0) + 1013904223) >>> 0;\n    const randVal = lcgState / 0x100000000;\n    const chord = parsedChords.find((c) => f >= c.start && f < c.end)!;\n    const isActive = chord.pcs.includes(pc);\n    const isOvertone = chord.overtones.includes(pc);\n    const rawEnergy = isActive\n      ? 0.65 + randVal * 0.3\n      : isOvertone\n        ? 0.22 + randVal * 0.18\n        : randVal * 0.16;\n    const energy = Number(Math.min(ENERGY_MAX, rawEnergy).toFixed(4));\n    const timeSec = Number((f * SEC_PER_FRAME).toFixed(3));\n    data.push({\n      [TIME]: timeSec,\n      [PITCH_CLASS]: pitchName,\n      [ENERGY]: energy,\n      [CHORD]: chord.label,\n    });\n  }\n}\n\n// Plot: reads only data and the constants above\nconst pitchOrder = Array.from(new Set(data.map((r) => String(r[PITCH_CLASS]))));\nconst pitchIndexMap = new Map<string, number>(pitchOrder.map((p, idx) => [p, idx]));\nconst uniqueTimes = Array.from(new Set(data.map((r) => Number(r[TIME])))).sort((a, b) => a - b);\nconst frameStepSec = uniqueTimes[1] - uniqueTimes[0];\nconst minTimeSec = uniqueTimes[0];\nconst maxTimeSec = uniqueTimes[uniqueTimes.length - 1] + frameStepSec;\nconst timeUnitMatch = TIME.match(/\\(([^)]+)\\)/);\nconst timeUnit = timeUnitMatch ? timeUnitMatch[1] : \"\";\n\nconst timeToChord = new Map<number, string>();\nfor (const r of data) {\n  const tVal = Number(r[TIME]);\n  if (!timeToChord.has(tVal)) {\n    timeToChord.set(tVal, String(r[CHORD]));\n  }\n}\n\ntype ChordSpan = { label: string; startSec: number; endSec: number };\nconst chordSpans: ChordSpan[] = [];\nfor (const tVal of uniqueTimes) {\n  const lbl = timeToChord.get(tVal)!;\n  const last = chordSpans[chordSpans.length - 1];\n  if (!last || last.label !== lbl) {\n    chordSpans.push({ label: lbl, startSec: tVal, endSec: tVal + frameStepSec });\n  } else {\n    last.endSec = tVal + frameStepSec;\n  }\n}\nconst chordDividers = chordSpans.slice(1).map((c) => c.startSec);\n\nconst cells = data.map((row, idx) => {\n  const timeSec = Number(row[TIME]);\n  const pcIdx = pitchIndexMap.get(String(row[PITCH_CLASS]))!;\n  return {\n    key: `${pcIdx}-${idx}`,\n    pcIdx,\n    timeSec,\n    nextTimeSec: timeSec + frameStepSec,\n    energy: Number(row[ENERGY]),\n  };\n});\n\nfunction ChromagramLayer() {\n  const { top, height: gH } = useDrawingArea();\n  const xScale = useXScale() as (v: number) => number;\n  const colorScale = useZColorScale() as (v: number) => string;\n\n  const nRows = pitchOrder.length;\n  const step = gH / nRows;\n\n  return (\n    <g>\n      {cells.map((cell) => {\n        const x0 = xScale(cell.timeSec);\n        const x1 = xScale(cell.nextTimeSec);\n        return (\n          <rect\n            key={cell.key}\n            x={x0}\n            y={top + (nRows - 1 - cell.pcIdx) * step}\n            width={x1 - x0 + 0.5}\n            height={step + 0.5}\n            fill={colorScale(cell.energy)}\n          />\n        );\n      })}\n\n      {/* Chord-change vertical dividers */}\n      {chordDividers.map((sec) => {\n        const sx = xScale(sec);\n        return (\n          <line\n            key={sec}\n            x1={sx}\n            y1={top}\n            x2={sx}\n            y2={top + gH}\n            stroke={t.ink}\n            strokeOpacity={0.45}\n            strokeWidth={2.5}\n          />\n        );\n      })}\n\n      {/* Chord section headers */}\n      {chordSpans.map((c) => {\n        const midSec = (c.startSec + c.endSec) / 2;\n        return (\n          <text\n            key={`${c.label}-${c.startSec}`}\n            x={xScale(midSec)}\n            y={top - 12}\n            textAnchor=\"middle\"\n            fontSize={14}\n            fontWeight={600}\n            fill={t.inkSoft}\n            fontFamily={FONT}\n          >\n            {c.label}\n          </text>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const chordProgressionText = chordSpans.map((c) => c.label).join(\" → \");\n  const subtitle = `${ENERGY} across ${pitchOrder.length} ${PITCH_CLASS}es · ${chordProgressionText} (${uniqueTimes.length} frames)`;\n\n  return (\n    <ChartsDataProvider\n      width={width - LEGEND_W}\n      height={height}\n      series={[]}\n      skipAnimation\n      zAxis={[\n        {\n          colorMap: {\n            type: \"continuous\",\n            min: ENERGY_MIN,\n            max: ENERGY_MAX,\n            color: [t.seq[0], t.seq[1]],\n          },\n        },\n      ]}\n      xAxis={[\n        {\n          scaleType: \"linear\",\n          min: minTimeSec,\n          max: maxTimeSec,\n          height: 56,\n          label: TIME,\n          valueFormatter: (v: number) => `${v.toFixed(1)}${timeUnit}`,\n          tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontFamily: FONT },\n          labelStyle: { fontSize: 15, fill: t.ink, fontFamily: FONT },\n        },\n      ]}\n      yAxis={[\n        {\n          scaleType: \"band\",\n          data: [...pitchOrder].reverse(),\n          width: 82,\n          label: PITCH_CLASS,\n          tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontFamily: FONT },\n          labelStyle: { fontSize: 15, fill: t.ink, fontFamily: FONT },\n        },\n      ]}\n      margin={{ left: 20, right: 24, top: 112, bottom: 24 }}\n    >\n      <ChartsWrapper\n        legendPosition={{ vertical: \"middle\", horizontal: \"end\" }}\n        legendDirection=\"vertical\"\n        sx={{ width, height }}\n      >\n        <Box\n          sx={{\n            gridArea: \"legend\",\n            width: LEGEND_W,\n            height: LEGEND_H,\n            display: \"flex\",\n            flexDirection: \"column\",\n            alignItems: \"center\",\n            fontFamily: FONT,\n          }}\n        >\n          <Typography sx={{ color: t.ink, fontSize: 15, fontFamily: FONT, mb: \"8px\" }}>\n            {ENERGY}\n          </Typography>\n          <ContinuousColorLegend\n            direction=\"vertical\"\n            thickness={20}\n            labelPosition=\"end\"\n            minLabel={({ value }) => Number(value).toFixed(1)}\n            maxLabel={({ value }) => Number(value).toFixed(1)}\n            sx={{ flex: 1, color: t.inkSoft, fontSize: 14, fontFamily: FONT }}\n          />\n        </Box>\n        <ChartsSurface>\n          <text\n        x={width / 2}\n        y={38}\n        textAnchor=\"middle\"\n        fontSize={22}\n        fontWeight={600}\n        fill={t.ink}\n        fontFamily={FONT}\n      >\n        {TITLE}\n      </text>\n      <text\n        x={width / 2}\n        y={64}\n        textAnchor=\"middle\"\n        fontSize={15}\n        fill={t.inkSoft}\n        fontFamily={FONT}\n      >\n        {subtitle}\n      </text>\n          <ChromagramLayer />\n          <ChartsXAxis />\n          <ChartsYAxis />\n        </ChartsSurface>\n      </ChartsWrapper>\n    </ChartsDataProvider>\n  );\n}\n"}