{"spec_id":"spectrum-nmr","library":"muix","language":"javascript","code":"// anyplot.ai\n// spectrum-nmr: NMR Spectrum (Nuclear Magnetic Resonance)\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst PEAK_THRESHOLD_SHARE = 0.1; // a line must reach this share of the tallest line\nconst RESOLUTION_PPM = 0.008; // a line is the highest point within this distance on either side\nconst MULTIPLET_GAP_PPM = 0.06; // lines closer than this belong to one multiplet\nconst MULTIPLICITY = [\"s\", \"d\", \"t\", \"q\", \"quint\", \"sext\", \"sept\"]; // by line count; more lines read \"m\"\nconst Y_PAD_SHARE = 0.04;\nconst LABEL_HEADROOM_SHARE = 0.14; // room above the tallest line for its label\n\n// Columns: set these to your data's column names\nconst SHIFT = \"Chemical shift δ (ppm)\"; // role: chemical_shift\nconst INTENSITY = \"Intensity (a.u.)\"; // role: intensity\n\n// Data: replace this block with your own records, one object per row\n// Synthetic 1H NMR spectrum of ethanol (CH3-CH2-OH) with TMS as internal standard, built\n// from the sample's signals (first-order multiplets with binomial line intensities,\n// Lorentzian line shapes). A signal's area is proportional to height × binomial sum × half-width,\n// scaled so CH3 : CH2 : OH integrate to 3 : 2 : 1 protons; the TMS height is arbitrary.\nconst signals = [\n  { shift: 0.0, lines: 1, splittingPpm: 0, halfWidthPpm: 0.006, height: 24 }, // TMS singlet\n  { shift: 1.2, lines: 3, splittingPpm: 0.024, halfWidthPpm: 0.004, height: 34 }, // CH3 triplet\n  { shift: 2.6, lines: 1, splittingPpm: 0, halfWidthPpm: 0.012, height: 15.1 }, // OH singlet\n  { shift: 3.7, lines: 4, splittingPpm: 0.024, halfWidthPpm: 0.004, height: 11.3 }, // CH2 quartet\n];\nconst data = (() => {\n  let seed = 42;\n  const rand = () => {\n    seed = (1664525 * seed + 1013904223) >>> 0;\n    return seed / 4294967296;\n  };\n  const count = 6000;\n  const lo = -0.5;\n  const hi = 4.6;\n  return Array.from({ length: count }, (_, i) => {\n    const shift = lo + (i * (hi - lo)) / (count - 1);\n    const noise = rand() * 0.6;\n    const signal = signals.reduce(\n      (acc, a) =>\n        acc +\n        Array.from({ length: a.lines }, (_, k) => {\n          const weight = Array.from({ length: k }, (_, j) => (a.lines - 1 - j) / (j + 1)).reduce((p, v) => p * v, 1);\n          const z = (shift - (a.shift + (k - (a.lines - 1) / 2) * a.splittingPpm)) / a.halfWidthPpm;\n          return (a.height * weight) / (1 + z * z);\n        }).reduce((p, v) => p + v, 0),\n      0,\n    );\n    return { [SHIFT]: shift, [INTENSITY]: noise + signal };\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst rows = [...data].sort((a, b) => a[SHIFT] - b[SHIFT]);\nconst shifts = rows.map((d) => d[SHIFT]);\nconst values = rows.map((d) => d[INTENSITY]);\nconst vMax = Math.max(...values);\nconst vMin = Math.min(...values);\n\n// Lines: local maxima above the threshold that are the highest point within the resolution\nconst lines = rows\n  .map((d, i) => ({ shift: d[SHIFT], value: d[INTENSITY], i }))\n  .filter((p) => p.value >= PEAK_THRESHOLD_SHARE * vMax)\n  .filter((p) =>\n    rows.every((d, j) => j === p.i || Math.abs(d[SHIFT] - p.shift) > RESOLUTION_PPM || d[INTENSITY] < p.value),\n  );\n// Multiplets: neighbouring lines closer than the gap, labelled at their centre above their tallest line\nconst multiplets = lines\n  .reduce((groups, line) => {\n    const last = groups[groups.length - 1];\n    if (last && line.shift - last[last.length - 1].shift < MULTIPLET_GAP_PPM) last.push(line);\n    else groups.push([line]);\n    return groups;\n  }, [])\n  .map((group) => {\n    const centre = group.reduce((acc, l) => acc + l.shift, 0) / group.length;\n    return {\n      centre,\n      top: Math.max(...group.map((l) => l.value)),\n      text: `${Number(centre.toFixed(2)).toFixed(2)} ${MULTIPLICITY[group.length - 1] ?? \"m\"}`,\n    };\n  });\n\nconst yMin = vMin - (vMax - vMin) * Y_PAD_SHARE;\nconst yMax = vMax + (vMax - vMin) * LABEL_HEADROOM_SHARE;\n\nconst TITLE = \"spectrum-nmr · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${rows.length.toLocaleString(\"en-US\")} points from ${Math.min(...shifts)\n  .toFixed(1)\n  .replace(\"-\", \"−\")} to ${Math.max(...shifts).toFixed(1)} ppm · ${multiplets.length} signals, ${lines.length} resolved lines · labels give δ and multiplicity`;\nconst HEADER_H = 80;\n\nfunction MultipletLabels() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g>\n      {multiplets.map((m) => (\n        <text\n          key={m.centre}\n          x={xScale(m.centre)}\n          y={yScale(m.top) - 12}\n          textAnchor=\"middle\"\n          fontSize={15}\n          fontWeight={600}\n          fill={t.ink}\n        >\n          {m.text}\n        </text>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div\n        style={{\n          height: HEADER_H,\n          display: \"flex\",\n          flexDirection: \"column\",\n          justifyContent: \"center\",\n          alignItems: \"center\",\n          gap: 8,\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</div>\n      </div>\n      <LineChart\n        width={width}\n        height={height - HEADER_H}\n        margin={{ top: 12, right: 48, bottom: 12, left: 24 }}\n        skipAnimation\n        hideLegend\n        grid={{ horizontal: true }}\n        xAxis={[\n          {\n            data: shifts,\n            scaleType: \"linear\",\n            reverse: true,\n            min: Math.min(...shifts),\n            max: Math.max(...shifts),\n            label: SHIFT,\n            height: 62,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: yMin,\n            max: yMax,\n            label: INTENSITY,\n            width: 76,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={[\n          {\n            id: \"spectrum\",\n            data: values,\n            curve: \"linear\",\n            showMark: false,\n            color: t.palette[0],\n            label: INTENSITY,\n          },\n        ]}\n        sx={{\n          \"& .MuiLineChart-line\": { strokeWidth: 1.6 },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      >\n        <MultipletLabels />\n      </LineChart>\n    </div>\n  );\n}\n"}