{"spec_id":"line-stress-strain","library":"muix","language":"javascript","code":"// anyplot.ai\n// line-stress-strain: Engineering Stress-Strain Curve\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 OFFSET = 0.002; // strain offset of the yield construction (the 0.2% offset method)\nconst ELASTIC_SECANT_SHARE = 0.95; // a sample is elastic while its secant modulus stays within this share of the first one\nconst OFFSET_LINE_OVERSHOOT = 0.3; // the offset line continues this share of the yield stress past the curve\nconst X_PAD_SHARE = 0.04; // share of the strain range added right of the fracture point\nconst Y_PAD_SHARE = 0.12; // share of the peak stress added above it for the labels\n\n// Columns: set these to your data's column names\nconst STRAIN = \"Engineering strain (mm/mm)\"; // role: strain\nconst STRESS = \"Engineering stress (MPa)\"; // role: stress_mpa\n\n// Data: replace this block with your own records, one object per row\n// Tensile test of a mild-steel specimen: elastic line, serrated yield plateau, strain hardening, necking.\nconst data = (() => {\n  const modulus = 200000;\n  const yieldStress = 250;\n  const elasticEnd = yieldStress / modulus;\n  const plateauStart = elasticEnd + 0.002;\n  const plateauEnd = 0.02;\n  const utsStrain = 0.2;\n  const utsStress = 450;\n  const fractureStrain = 0.26;\n  const fractureStress = 300;\n  let seed = 42;\n  const rand = () => {\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    return seed / 0x7fffffff;\n  };\n  const span = (a, b, n) => Array.from({ length: n }, (_, i) => a + ((b - a) * i) / (n - 1));\n  const strains = [\n    ...span(0, elasticEnd, 6),\n    ...span(elasticEnd, plateauStart, 6).slice(1),\n    ...span(plateauStart, plateauEnd, 24).slice(1),\n    ...span(plateauEnd, utsStrain, 90).slice(1),\n    ...span(utsStrain, fractureStrain, 46).slice(1),\n  ];\n  return strains.map((strain) => {\n    let stress;\n    if (strain <= elasticEnd) stress = modulus * strain;\n    else if (strain <= plateauEnd) stress = yieldStress + (rand() - 0.5) * 6;\n    else if (strain <= utsStrain) {\n      const f = (strain - plateauEnd) / (utsStrain - plateauEnd);\n      stress = yieldStress + (utsStress - yieldStress) * (2 * f - f * f);\n    } else {\n      const f = (strain - utsStrain) / (fractureStrain - utsStrain);\n      stress = utsStress - (utsStress - fractureStress) * (3 * f * f - 2 * f * f * f);\n    }\n    return { [STRAIN]: Math.round(strain * 1e6) / 1e6, [STRESS]: Math.round(stress * 10) / 10 };\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst rows = [...data].sort((a, b) => a[STRAIN] - b[STRAIN]);\nconst strains = rows.map((d) => d[STRAIN]);\nconst stresses = rows.map((d) => d[STRESS]);\nconst unit = STRESS.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\nconst last = rows.length - 1;\n\n// Elastic region: the leading samples whose secant modulus stays near the first loaded sample's;\n// the modulus is the least-squares slope through the origin over them.\nconst firstLoaded = strains.findIndex((s) => s > 0);\nconst initialSecant = stresses[firstLoaded] / strains[firstLoaded];\nlet elasticEnd = firstLoaded;\nwhile (elasticEnd < last && stresses[elasticEnd + 1] / strains[elasticEnd + 1] >= ELASTIC_SECANT_SHARE * initialSecant) {\n  elasticEnd += 1;\n}\nconst elastic = rows.slice(0, elasticEnd + 1);\nconst modulus =\n  elastic.reduce((sum, d) => sum + d[STRAIN] * d[STRESS], 0) / elastic.reduce((sum, d) => sum + d[STRAIN] ** 2, 0);\n\n// Yield: first crossing of the curve below the offset line, interpolated within the segment\nconst gap = rows.map((d) => d[STRESS] - modulus * (d[STRAIN] - OFFSET));\nconst cross = gap.findIndex((g, i) => i > 0 && gap[i - 1] > 0 && g <= 0);\nconst share = cross > 0 ? gap[cross - 1] / (gap[cross - 1] - gap[cross]) : 0;\nconst yieldPoint =\n  cross > 0\n    ? {\n        strain: strains[cross - 1] + share * (strains[cross] - strains[cross - 1]),\n        stress: stresses[cross - 1] + share * (stresses[cross] - stresses[cross - 1]),\n      }\n    : null;\nconst utsIndex = stresses.indexOf(Math.max(...stresses));\nconst uts = { strain: strains[utsIndex], stress: stresses[utsIndex] };\nconst fracture = { strain: strains[last], stress: stresses[last] };\n\nconst fmtStress = (v: number) => `${Math.round(v).toLocaleString(\"en-US\")} ${unit}`;\nconst offsetTop = (yieldPoint ? yieldPoint.stress * (1 + OFFSET_LINE_OVERSHOOT) : uts.stress);\nconst criticalPoints = [\n  yieldPoint && { ...yieldPoint, text: `Yield ${fmtStress(yieldPoint.stress)}`, anchor: \"start\", dx: 16, dy: -18 },\n  { ...uts, text: `UTS ${fmtStress(uts.stress)}`, anchor: \"middle\", dx: 0, dy: -22 },\n  { ...fracture, text: `Fracture ${fmtStress(fracture.stress)}`, anchor: \"end\", dx: -12, dy: 34 },\n].filter(Boolean);\n\n// Region labels sit above the curve at the middle of the strain span they name, on the side\n// where the curve falls away: left of the anchor on a rising stretch, right of it on a falling one\nconst plasticAt = yieldPoint && utsIndex > cross ? strains.findIndex((s) => s >= (yieldPoint.strain + uts.strain) / 2) : -1;\nconst neckingAt = utsIndex < last ? strains.findIndex((s) => s >= (uts.strain + fracture.strain) / 2) : -1;\nconst regionLabels = [\n  { at: plasticAt, text: \"Plastic (strain hardening)\" },\n  { at: neckingAt, text: \"Necking\" },\n]\n  .filter((r) => r.at > 0 && r.at < last)\n  .map((r) => ({ ...r, rising: stresses[r.at + 1] >= stresses[r.at - 1] }));\nconst elasticMid = elastic[Math.floor(elastic.length / 2)];\n\nconst TITLE = \"line-stress-strain · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${rows.length} samples · E fitted over the first ${elastic.length} samples · yield by the ${OFFSET * 100}% offset method · elongation at fracture ${(fracture.strain * 100).toFixed(1)}%`;\nconst HEADER_H = 80;\n\nfunction CurveAnnotations() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const y0 = yScale(0);\n  return (\n    <g>\n      <line\n        x1={xScale(OFFSET)}\n        y1={y0}\n        x2={xScale(OFFSET + offsetTop / modulus)}\n        y2={yScale(offsetTop)}\n        stroke={t.inkSoft}\n        strokeWidth={2}\n        strokeDasharray=\"8 5\"\n      />\n      <text\n        x={xScale(OFFSET + offsetTop / modulus) + 10}\n        y={yScale(offsetTop)}\n        fontSize={15}\n        fill={t.inkSoft}\n        dominantBaseline=\"middle\"\n      >\n        {`${OFFSET * 100}% offset line, slope E`}\n      </text>\n      <text\n        x={xScale(elasticMid[STRAIN]) + 40}\n        y={yScale(elasticMid[STRESS])}\n        fontSize={16}\n        fontWeight={500}\n        fill={t.ink}\n        dominantBaseline=\"middle\"\n      >\n        {`Elastic · E = ${fmtStress(modulus)}`}\n      </text>\n      {regionLabels.map((r) => (\n        <text\n          key={r.text}\n          x={xScale(strains[r.at]) + (r.rising ? -8 : 8)}\n          y={yScale(stresses[r.at]) - 20}\n          fontSize={16}\n          fontWeight={500}\n          fill={t.ink}\n          textAnchor={r.rising ? \"end\" : \"start\"}\n        >\n          {r.text}\n        </text>\n      ))}\n      {criticalPoints.map((p) => (\n        <g key={p.text}>\n          <line\n            x1={xScale(p.strain)}\n            y1={yScale(p.stress)}\n            x2={xScale(p.strain)}\n            y2={y0}\n            stroke={t.inkSoft}\n            strokeOpacity={0.6}\n            strokeWidth={1.25}\n            strokeDasharray=\"2 4\"\n          />\n          <circle cx={xScale(p.strain)} cy={yScale(p.stress)} r={8} fill={t.palette[0]} stroke={t.pageBg} strokeWidth={3} />\n          <text\n            x={xScale(p.strain) + p.dx}\n            y={yScale(p.stress) + p.dy}\n            fontSize={15}\n            fill={t.inkSoft}\n            textAnchor={p.anchor}\n          >\n            {p.text}\n          </text>\n        </g>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: HEADER_H, padding: \"16px 40px 0 112px\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.25 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, marginTop: 6 }}>{SUBTITLE}</div>\n      </div>\n      <LineChart\n        width={width}\n        height={height - HEADER_H}\n        skipAnimation\n        hideLegend\n        grid={{ horizontal: true }}\n        margin={{ top: 16, right: 48, bottom: 16, left: 24 }}\n        xAxis={[\n          {\n            data: strains,\n            scaleType: \"linear\",\n            min: 0,\n            max: fracture.strain * (1 + X_PAD_SHARE),\n            tickNumber: 14,\n            valueFormatter: (v: number) => v.toFixed(2),\n            label: STRAIN,\n            height: 64,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            max: uts.stress * (1 + Y_PAD_SHARE),\n            label: STRESS,\n            width: 84,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={[\n          {\n            id: \"curve\",\n            data: stresses,\n            label: STRESS,\n            color: t.palette[0],\n            curve: \"linear\",\n            showMark: false,\n            valueFormatter: (v: number | null) => (v == null ? \"\" : fmtStress(v)),\n          },\n        ]}\n        sx={{\n          \"& .MuiLineChart-line\": { strokeWidth: 3.5 },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      >\n        <CurveAnnotations />\n      </LineChart>\n    </div>\n  );\n}\n"}