{"spec_id":"line-tanabe-sugano","library":"muix","language":"javascript","code":"// anyplot.ai\n// line-tanabe-sugano: Tanabe-Sugano Diagram for Crystal Field Theory\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 89/100 | Updated: 2026-10-24\n//# anyplot-orientation: square\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\nconst { width: WIDTH, height: HEIGHT } = window.ANYPLOT_SIZE;\n\n// Constants\nconst LABEL_MIN_GAP_PX = 25;\nconst LABEL_FONT_PX = 19;\nconst ENERGY_TICK_STEP = 10;\nconst SHIFT: Record<\"base\" | \"sup\" | \"sub\", number> = {\n  base: 0,\n  sup: -0.42,\n  sub: 0.26,\n};\nconst SUP_MAP: Record<string, string> = {\n  \"⁰\": \"0\",\n  \"¹\": \"1\",\n  \"²\": \"2\",\n  \"³\": \"3\",\n  \"⁴\": \"4\",\n  \"⁵\": \"5\",\n  \"⁶\": \"6\",\n  \"⁷\": \"7\",\n  \"⁸\": \"8\",\n  \"⁹\": \"9\",\n  \"⁺\": \"+\",\n  \"⁻\": \"-\",\n};\nconst SUB_MAP: Record<string, string> = {\n  \"₀\": \"0\",\n  \"₁\": \"1\",\n  \"₂\": \"2\",\n  \"₃\": \"3\",\n  \"₄\": \"4\",\n  \"₅\": \"5\",\n  \"₆\": \"6\",\n  \"₇\": \"7\",\n  \"₈\": \"8\",\n  \"₉\": \"9\",\n  \"ₒ\": \"o\",\n};\n\n// Columns: set these to your data's column names\nconst DELTA_OVER_B = \"Ligand-field strength Δo / B\"; // role: delta_over_b\nconst TERM = \"Term symbol\"; // role: term\nconst ENERGY_OVER_B = \"Term energy E / B\"; // role: energy_over_b\nconst SPIN_ALLOWED = \"Spin allowed\"; // role: spin_allowed\n\n// Data: replace this block with your own records\nconst CONFIG = \"d³ (Cr³⁺)\";\nconst C_OVER_B = 4.5;\nconst EXAMPLE_COMPLEX = \"[Cr(H₂O)₆]³⁺\";\nconst EXAMPLE_FIELD = 17400 / 700;\nconst ENERGY_CEILING = 90; // top of the plotted E/B range\n\n// Tanabe-Sugano d³ energy matrices (Tanabe & Sugano 1954) in the strong-field\n// basis t₂g³⁻ⁿ egⁿ: E = b·B + c·C + n·Δo, in units of B; A is dropped\nconst R2 = Math.SQRT2;\nconst R3 = Math.sqrt(3);\nconst BLOCKS: Array<{\n  symbol: string;\n  roots: string[];\n  b: number[][];\n  c: number[][];\n  eg: number[];\n}> = [\n  { symbol: \"⁴A₂g\", roots: [\"\"], b: [[0]], c: [[0]], eg: [0] },\n  { symbol: \"⁴T₂g\", roots: [\"\"], b: [[0]], c: [[0]], eg: [1] },\n  {\n    symbol: \"⁴T₁g\",\n    roots: [\"(F)\", \"(P)\"],\n    b: [\n      [12, 6],\n      [6, 3],\n    ],\n    c: [\n      [0, 0],\n      [0, 0],\n    ],\n    eg: [1, 2],\n  },\n  { symbol: \"²A₁g\", roots: [\"\"], b: [[4]], c: [[3]], eg: [1] },\n  { symbol: \"²A₂g\", roots: [\"\"], b: [[24]], c: [[3]], eg: [1] },\n  {\n    symbol: \"²Eg\",\n    roots: [\"(1)\", \"(2)\", \"(3)\", \"(4)\"],\n    b: [\n      [9, -3 * R2, -6 * R2, 0],\n      [-3 * R2, 14, 10, -2 * R3],\n      [-6 * R2, 10, 23, -2 * R3],\n      [0, -2 * R3, -2 * R3, 7],\n    ],\n    c: [\n      [3, 0, 0, 0],\n      [0, 3, 0, 0],\n      [0, 0, 6, -R3],\n      [0, 0, -R3, 4],\n    ],\n    eg: [0, 1, 1, 3],\n  },\n  {\n    symbol: \"²T₁g\",\n    roots: [\"(1)\", \"(2)\", \"(3)\", \"(4)\", \"(5)\"],\n    b: [\n      [9, -3, 3, -2 * R3, 0],\n      [-3, 9, -3, R3, -3],\n      [3, -3, 15, -3 * R3, 3],\n      [-2 * R3, R3, -3 * R3, 13, -2 * R3],\n      [0, -3, 3, -2 * R3, 9],\n    ],\n    c: [\n      [3, 0, 0, 0, 0],\n      [0, 3, 0, 0, 0],\n      [0, 0, 3, 0, 0],\n      [0, 0, 0, 3, 0],\n      [0, 0, 0, 0, 3],\n    ],\n    eg: [0, 1, 1, 2, 2],\n  },\n  {\n    symbol: \"²T₂g\",\n    roots: [\"(1)\", \"(2)\", \"(3)\", \"(4)\", \"(5)\"],\n    b: [\n      [15, -5 * R3, -3 * R3, 2, 4],\n      [-5 * R3, 19, 3, R3, -R3],\n      [-3 * R3, 3, 9, -3 * R3, -3 * R3],\n      [2, R3, -3 * R3, 13, 10],\n      [4, -R3, -3 * R3, 10, 21],\n    ],\n    c: [\n      [5, 0, 0, 0, 2],\n      [0, 3, 0, 0, 0],\n      [0, 0, 3, 0, 0],\n      [0, 0, 0, 3, 0],\n      [2, 0, 0, 0, 5],\n    ],\n    eg: [0, 1, 1, 2, 2],\n  },\n];\n\n// Cyclic Jacobi rotations: eigenvalues of a real symmetric matrix, ascending\nfunction symmetricEigenvalues(matrix: number[][]): number[] {\n  const a = matrix.map((row) => [...row]);\n  const n = a.length;\n  for (let sweep = 0; sweep < 50; sweep += 1) {\n    let offDiagonal = 0;\n    for (let p = 0; p < n; p += 1) {\n      for (let q = p + 1; q < n; q += 1) offDiagonal += a[p][q] ** 2;\n    }\n    if (offDiagonal < 1e-20) break;\n    for (let p = 0; p < n; p += 1) {\n      for (let q = p + 1; q < n; q += 1) {\n        if (Math.abs(a[p][q]) < 1e-15) continue;\n        const theta = (a[q][q] - a[p][p]) / (2 * a[p][q]);\n        const tan =\n          Math.sign(theta || 1) / (Math.abs(theta) + Math.hypot(theta, 1));\n        const cos = 1 / Math.hypot(tan, 1);\n        const sin = tan * cos;\n        for (let k = 0; k < n; k += 1) {\n          const akp = a[k][p];\n          const akq = a[k][q];\n          a[k][p] = cos * akp - sin * akq;\n          a[k][q] = sin * akp + cos * akq;\n        }\n        for (let k = 0; k < n; k += 1) {\n          const apk = a[p][k];\n          const aqk = a[q][k];\n          a[p][k] = cos * apk - sin * aqk;\n          a[q][k] = sin * apk + cos * aqk;\n        }\n      }\n    }\n  }\n  return a.map((row, i) => row[i]).sort((x, y) => x - y);\n}\n\nconst N_STEPS = 320;\nconst data: Array<Record<string, number | string | boolean>> = [];\nfor (let step = 0; step <= N_STEPS; step += 1) {\n  const d = (step * 40) / N_STEPS;\n  const levels = BLOCKS.flatMap((block) =>\n    symmetricEigenvalues(\n      block.b.map((row, i) =>\n        row.map(\n          (bij, j) =>\n            bij + C_OVER_B * block.c[i][j] + (i === j ? block.eg[i] * d : 0),\n        ),\n      ),\n    ).map((energy, k) => ({\n      term: `${block.symbol}${block.roots[k]}`,\n      multiplicity: block.symbol[0],\n      energy,\n    })),\n  );\n  const ground = levels.reduce((lo, lvl) => (lvl.energy < lo.energy ? lvl : lo));\n  for (const lvl of levels) {\n    const energy = lvl.energy - ground.energy;\n    if (energy > ENERGY_CEILING) continue;\n    data.push({\n      [DELTA_OVER_B]: d,\n      [TERM]: lvl.term,\n      [ENERGY_OVER_B]: energy,\n      [SPIN_ALLOWED]: lvl.multiplicity === ground.multiplicity,\n    });\n  }\n}\n\n// Plot: reads only data and the constants above\ninterface TypesetRun {\n  text: string;\n  dyFactor: number;\n  fontScale: number;\n}\n\nconst subtitleText = `${CONFIG} in an octahedral field · C/B = ${C_OVER_B} · colour marks symmetry · spin-allowed terms solid, spin-forbidden dashed`;\nconst complexMarkerText = `${EXAMPLE_COMPLEX} · Δo / B = ${EXAMPLE_FIELD.toFixed(1)}`;\n\nconst stringsToParse = new Set<string>([\n  DELTA_OVER_B,\n  subtitleText,\n  complexMarkerText,\n  \"ν₁\",\n  \"ν₂\",\n]);\nfor (const row of data) {\n  stringsToParse.add(String(row[TERM]));\n}\n\nconst parsedRunsByText: Record<string, TypesetRun[]> = {};\nfor (const rawText of stringsToParse) {\n  const rawSegments: Array<{ kind: \"base\" | \"sup\" | \"sub\"; text: string }> = [];\n  let inMulliken = false;\n  for (let i = 0; i < rawText.length; i += 1) {\n    const ch = rawText[i];\n    const prev = i > 0 ? rawText[i - 1] : \"\";\n    let kind: \"base\" | \"sup\" | \"sub\" = \"base\";\n    let mapped = ch;\n    if (ch in SUP_MAP) {\n      kind = \"sup\";\n      mapped = SUP_MAP[ch];\n      inMulliken = false;\n    } else if (ch in SUB_MAP) {\n      kind = \"sub\";\n      mapped = SUB_MAP[ch];\n    } else if ((ch === \"g\" || ch === \"u\") && inMulliken) {\n      kind = \"sub\";\n      inMulliken = false;\n    } else if (ch === \"o\" && prev === \"Δ\") {\n      kind = \"sub\";\n    } else {\n      inMulliken = ch === \"A\" || ch === \"B\" || ch === \"E\" || ch === \"T\";\n    }\n    const last = rawSegments[rawSegments.length - 1];\n    if (last && last.kind === kind) {\n      last.text += mapped;\n    } else {\n      rawSegments.push({ kind, text: mapped });\n    }\n  }\n  let offset = 0;\n  parsedRunsByText[rawText] = rawSegments.map((seg) => {\n    const dyFactor = SHIFT[seg.kind] - offset;\n    offset = SHIFT[seg.kind];\n    return {\n      text: seg.text,\n      dyFactor,\n      fontScale: seg.kind === \"base\" ? 1 : 0.66,\n    };\n  });\n}\n\nconst terms: string[] = [];\nfor (const row of data) {\n  const termName = String(row[TERM]);\n  if (!terms.includes(termName)) terms.push(termName);\n}\n\n// Colour by Mulliken symmetry: the key without multiplicity and root suffix\nconst symmetryOf = (termName: string) =>\n  termName.replace(/\\(.*\\)$/, \"\").replace(/^[⁰¹²³⁴⁵⁶⁷⁸⁹]+/, \"\");\nconst symmetries: string[] = [];\nfor (const termName of terms) {\n  if (!symmetries.includes(symmetryOf(termName))) {\n    symmetries.push(symmetryOf(termName));\n  }\n}\n\nconst fieldSet: number[] = [];\nfor (const row of data) {\n  const f = Number(row[DELTA_OVER_B]);\n  if (!fieldSet.includes(f)) fieldSet.push(f);\n}\nconst fieldStrengths = [...fieldSet].sort((a, b) => a - b);\nconst fieldMin = fieldStrengths[0];\nconst fieldMax = fieldStrengths[fieldStrengths.length - 1];\n\nconst allEnergies = data.map((r) => Number(r[ENERGY_OVER_B]));\nconst energyMin = Math.min(...allEnergies);\nconst energyMax =\n  Math.ceil(Math.max(...allEnergies) / ENERGY_TICK_STEP) * ENERGY_TICK_STEP;\n\nconst termSeries = terms.map((termName, i) => {\n  const rows = data\n    .filter((r) => String(r[TERM]) === termName)\n    .sort((a, b) => Number(a[DELTA_OVER_B]) - Number(b[DELTA_OVER_B]));\n  const spinAllowed = Boolean(rows[0][SPIN_ALLOWED]);\n  const points = rows.map((r) => ({\n    x: Number(r[DELTA_OVER_B]),\n    y: Number(r[ENERGY_OVER_B]),\n  }));\n  const energyAt = new Map(points.map((p) => [p.x, p.y]));\n  const yValues = fieldStrengths.map((f) => energyAt.get(f) ?? null);\n  const lastPoint = points[points.length - 1];\n  let exampleEnergy: number | null = null;\n  for (let j = 0; j < points.length - 1; j += 1) {\n    if (\n      EXAMPLE_FIELD >= points[j].x &&\n      EXAMPLE_FIELD <= points[j + 1].x\n    ) {\n      const span = points[j + 1].x - points[j].x;\n      const frac = (EXAMPLE_FIELD - points[j].x) / span;\n      exampleEnergy = points[j].y + frac * (points[j + 1].y - points[j].y);\n      break;\n    }\n  }\n  return {\n    id: `term-${i}`,\n    label: termName,\n    runs: parsedRunsByText[termName],\n    color: t.palette[symmetries.indexOf(symmetryOf(termName))],\n    spinAllowed,\n    yValues,\n    lastPoint,\n    leavesTop: lastPoint.x < fieldMax,\n    exampleEnergy,\n  };\n});\n\n// The two lowest spin-allowed excited terms at the example complex's field\nconst bandTransitions = termSeries\n  .filter((s) => s.spinAllowed && s.exampleEnergy !== null && s.lastPoint.y > 0)\n  .sort((a, b) => Number(a.exampleEnergy) - Number(b.exampleEnergy))\n  .slice(0, 2)\n  .map((s, idx) => ({\n    id: `nu-${idx + 1}`,\n    runs: parsedRunsByText[idx === 0 ? \"ν₁\" : \"ν₂\"],\n    targetEnergy: Number(s.exampleEnergy),\n    dx: idx === 0 ? -12 : 12,\n  }));\n\nfunction TypesetText({\n  runs,\n  fontSize,\n}: {\n  runs: TypesetRun[];\n  fontSize: number;\n}) {\n  return (\n    <>\n      {runs.map((r, idx) => (\n        <tspan key={idx} dy={r.dyFactor * fontSize} fontSize={fontSize * r.fontScale}>\n          {r.text}\n        </tspan>\n      ))}\n    </>\n  );\n}\n\nfunction TanabeSuganoLayer() {\n  const { left, top, width, height } = useDrawingArea();\n  const xScale = useXScale(\"field\") as (v: number) => number;\n  const yScale = useYScale(\"energy\") as (v: number) => number;\n  const labelWidth = (s: (typeof termSeries)[number]) =>\n    s.runs.reduce(\n      (sum, r) => sum + r.text.length * LABEL_FONT_PX * r.fontScale * 0.62,\n      0,\n    );\n\n  // Right-edge labels for curves that reach Δo/B max, stacked top to bottom\n  let lowestY = -Infinity;\n  const edgeLabels = termSeries\n    .filter((s) => !s.leavesTop)\n    .map((s) => ({ ...s, rawY: yScale(s.lastPoint.y) }))\n    .sort((a, b) => a.rawY - b.rawY)\n    .map((s) => {\n      const placedY = Math.max(s.rawY, lowestY + LABEL_MIN_GAP_PX);\n      lowestY = placedY;\n      return { ...s, placedY };\n    });\n\n  // Top-edge labels for curves that leave through the ceiling, left to right\n  let rightmostX = -Infinity;\n  const topLabels = termSeries\n    .filter((s) => s.leavesTop)\n    .map((s) => ({ ...s, rawX: xScale(s.lastPoint.x), w: labelWidth(s) }))\n    .sort((a, b) => a.rawX - b.rawX)\n    .map((s) => {\n      const placedX = Math.max(s.rawX - s.w / 2, rightmostX + 10);\n      rightmostX = placedX + s.w;\n      return { ...s, placedX };\n    });\n\n  const exX = xScale(EXAMPLE_FIELD);\n  const yZero = yScale(0);\n  const edgeX = left + width;\n\n  return (\n    <g>\n      <defs>\n        <marker\n          id=\"band-arrow\"\n          markerUnits=\"userSpaceOnUse\"\n          markerWidth={14}\n          markerHeight={14}\n          refX={7}\n          refY={7}\n          orient=\"auto\"\n        >\n          <path d=\"M0,0 L14,7 L0,14 z\" fill={t.inkSoft} />\n        </marker>\n      </defs>\n\n      {/* Observed UV-Vis transition arrows at example complex field strength */}\n      {bandTransitions.map((b) => {\n        const yTarget = yScale(b.targetEnergy);\n        return (\n          <g key={b.id}>\n            <line\n              x1={exX + b.dx}\n              y1={yZero}\n              x2={exX + b.dx}\n              y2={yTarget + 7}\n              stroke={t.inkSoft}\n              strokeWidth={2}\n              markerEnd=\"url(#band-arrow)\"\n            />\n            <text\n              x={exX + b.dx + Math.sign(b.dx) * 9}\n              y={(yZero + yTarget) / 2}\n              fill={t.inkSoft}\n              fontSize={17}\n              textAnchor={b.dx < 0 ? \"end\" : \"start\"}\n              dominantBaseline=\"middle\"\n            >\n              <TypesetText runs={b.runs} fontSize={17} />\n            </text>\n          </g>\n        );\n      })}\n\n      {/* Example complex label in the open corner right of its marker */}\n      <text\n        x={exX + 26}\n        y={yZero - 36}\n        fill={t.inkSoft}\n        fontSize={15}\n      >\n        <TypesetText runs={parsedRunsByText[complexMarkerText]} fontSize={15} />\n      </text>\n\n      {/* Right-margin term symbols with true super/subscripts and leaders */}\n      {edgeLabels.map((lbl) => (\n        <g key={lbl.id}>\n          <polyline\n            points={`${edgeX + 2},${lbl.rawY} ${edgeX + 8},${lbl.rawY} ${edgeX + 16},${lbl.placedY}`}\n            fill=\"none\"\n            stroke={lbl.color}\n            strokeWidth={1.2}\n          />\n          <text\n            x={edgeX + 20}\n            y={lbl.placedY}\n            fill={lbl.color}\n            fontSize={LABEL_FONT_PX}\n            fontWeight={lbl.spinAllowed ? 700 : 500}\n            dominantBaseline=\"middle\"\n          >\n            <TypesetText runs={lbl.runs} fontSize={LABEL_FONT_PX} />\n          </text>\n        </g>\n      ))}\n\n      {/* Term symbols above the ceiling where their curve leaves the plot */}\n      {topLabels.map((lbl) => (\n        <g key={lbl.id}>\n          <line\n            x1={lbl.rawX}\n            y1={top - 2}\n            x2={lbl.placedX + lbl.w / 2}\n            y2={top - 12}\n            stroke={lbl.color}\n            strokeWidth={1.2}\n          />\n          <text\n            x={lbl.placedX}\n            y={top - 20}\n            fill={lbl.color}\n            fontSize={LABEL_FONT_PX}\n            fontWeight={lbl.spinAllowed ? 700 : 500}\n          >\n            <TypesetText runs={lbl.runs} fontSize={LABEL_FONT_PX} />\n          </text>\n        </g>\n      ))}\n\n      {/* Title, subtitle, and axis titles */}\n      <text\n        x={left + width / 2}\n        y={40}\n        fill={t.ink}\n        fontSize={22}\n        fontWeight={600}\n        textAnchor=\"middle\"\n      >\n        line-tanabe-sugano · javascript · muix · anyplot.ai\n      </text>\n      <text\n        x={left + width / 2}\n        y={70}\n        fill={t.inkSoft}\n        fontSize={15}\n        textAnchor=\"middle\"\n      >\n        <TypesetText runs={parsedRunsByText[subtitleText]} fontSize={15} />\n      </text>\n      <text\n        x={left + width / 2}\n        y={HEIGHT - 24}\n        fill={t.ink}\n        fontSize={17}\n        textAnchor=\"middle\"\n      >\n        <TypesetText runs={parsedRunsByText[DELTA_OVER_B]} fontSize={17} />\n      </text>\n      <text\n        x={28}\n        y={top + height / 2}\n        fill={t.ink}\n        fontSize={17}\n        textAnchor=\"middle\"\n        transform={`rotate(-90 28 ${top + height / 2})`}\n      >\n        {ENERGY_OVER_B}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <div style={{ width: WIDTH, height: HEIGHT, background: t.pageBg }}>\n      <ChartsContainer\n        width={WIDTH}\n        height={HEIGHT}\n        skipAnimation\n        margin={{ top: 136, right: 150, bottom: 48, left: 44 }}\n        series={termSeries.map((s) => ({\n          type: \"line\",\n          id: s.id,\n          xAxisId: \"field\",\n          yAxisId: \"energy\",\n          label: s.label,\n          color: s.color,\n          showMark: false,\n          curve: \"linear\",\n          data: s.yValues,\n        }))}\n        xAxis={[\n          {\n            id: \"field\",\n            data: fieldStrengths,\n            scaleType: \"linear\",\n            min: fieldMin,\n            max: fieldMax,\n            tickNumber: 9,\n            height: 40,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            tickSize: 7,\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"energy\",\n            min: energyMin,\n            max: energyMax,\n            tickNumber: energyMax / ENERGY_TICK_STEP,\n            width: 52,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            tickSize: 7,\n          },\n        ]}\n        sx={Object.fromEntries(\n          termSeries.map((s) => [\n            `& .MuiLineChart-line[data-series=\"${s.id}\"]`,\n            s.spinAllowed\n              ? { strokeWidth: 4.2 }\n              : { strokeWidth: 2.2, strokeDasharray: \"11 7\" },\n          ]),\n        )}\n      >\n        <ChartsGrid vertical horizontal />\n        <ChartsReferenceLine\n          x={EXAMPLE_FIELD}\n          axisId=\"field\"\n          lineStyle={{\n            stroke: t.inkSoft,\n            strokeWidth: 2,\n            strokeDasharray: \"6 7\",\n          }}\n        />\n        <LinePlot skipAnimation />\n        <ChartsXAxis axisId=\"field\" />\n        <ChartsYAxis axisId=\"energy\" />\n        <TanabeSuganoLayer />\n        <ChartsTooltip trigger=\"axis\" />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}