{"spec_id":"sn-curve-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// sn-curve-basic: S-N Curve (Wöhler Curve)\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 89/100 | Updated: 2026-11-08\n\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\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 } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst LCF_HCF_BOUNDARY = 1e4; // cycles: the conventional divide between low-cycle and high-cycle fatigue\nconst LIMIT_LINES = [\n  { key: \"ultimateStrength\", name: \"Ultimate strength\", dash: \"12 6\" },\n  { key: \"yieldStrength\", name: \"Yield strength\", dash: \"6 5\" },\n  { key: \"enduranceLimit\", name: \"Endurance limit\", dash: \"2 5\" },\n];\nconst REGION_NAMES = [\"Low-cycle fatigue\", \"High-cycle fatigue\", \"Infinite life\"];\nconst SPECIMEN_LABEL = \"Test specimens\";\nconst FIT_LABEL = \"Basquin fit\";\nconst X_PAD_SHARE = 0.06; // share of the log cycle span added left of the data\nconst PLATEAU_SHARE = 0.25; // share of the log cycle span shown past the knee, so the endurance plateau reads\nconst Y_PAD_SHARE = 0.08; // share of the log stress span added above and below\nconst Y_TICK_TARGET = 5;\nconst FIT_POINTS = 80;\nconst SUPERSCRIPT = [\"⁰\", \"¹\", \"²\", \"³\", \"⁴\", \"⁵\", \"⁶\", \"⁷\", \"⁸\", \"⁹\"];\n\n// Columns: set these to your data's column names\nconst CYCLES = \"Cycles to failure, N\"; // role: cycles\nconst STRESS = \"Stress amplitude (MPa)\"; // role: stress\n\n// Data: replace this block with your own records, one object per row\n// Material properties of the tested steel, in the stress unit of the records\nconst material = { ultimateStrength: 760, yieldStrength: 620, enduranceLimit: 380 };\n// Constant-amplitude coupon tests: three specimens per stress level, their lives\n// scattered around a Basquin curve that reaches the endurance limit at 10⁶ cycles\nconst data = (() => {\n  let seed = 42;\n  const rand = () => {\n    seed = (Math.imul(1664525, seed) + 1013904223) >>> 0;\n    return seed / 4294967296;\n  };\n  const exponent = Math.log(material.enduranceLimit / 700) / Math.log(1e6 / 1e3);\n  const coefficient = 700 * Math.pow(1e3, -exponent);\n  return [700, 650, 600, 550, 500, 450, 420, 400].flatMap((stress) =>\n    Array.from({ length: 3 }, () => ({\n      [CYCLES]: Math.round(Math.pow(stress / coefficient, 1 / exponent) * Math.pow(10, (rand() - 0.5) * 0.3)),\n      [STRESS]: stress,\n    })),\n  );\n})();\n\n// Plot: reads only data and the constants above\nconst stressUnit = /\\(([^)]+)\\)/.exec(STRESS)?.[1] ?? \"\";\nconst enduranceLimit = material.enduranceLimit;\n\n// Basquin fit S = A · N^b, least squares in log-log space over the finite-life specimens\nconst finite = data.filter((d) => d[STRESS] > enduranceLimit);\nconst logN = finite.map((d) => Math.log10(d[CYCLES]));\nconst logS = finite.map((d) => Math.log10(d[STRESS]));\nconst meanLogN = logN.reduce((a, b) => a + b, 0) / logN.length;\nconst meanLogS = logS.reduce((a, b) => a + b, 0) / logS.length;\nconst sxx = logN.reduce((acc, x) => acc + (x - meanLogN) ** 2, 0);\nconst sxy = logN.reduce((acc, x, i) => acc + (x - meanLogN) * (logS[i] - meanLogS), 0);\nconst basquinExponent = sxy / sxx;\nconst basquinLogA = meanLogS - basquinExponent * meanLogN;\nconst ssRes = logN.reduce((acc, x, i) => acc + (logS[i] - (basquinLogA + basquinExponent * x)) ** 2, 0);\nconst ssTot = logS.reduce((acc, y) => acc + (y - meanLogS) ** 2, 0);\nconst rSquared = 1 - ssRes / ssTot;\nconst logKnee = (Math.log10(enduranceLimit) - basquinLogA) / basquinExponent;\n\n// Axis extents in log space: the data, the knee and every limit line inside the drawing area\nconst allLogN = data.map((d) => Math.log10(d[CYCLES]));\nconst logNLo = Math.min(...allLogN);\nconst logNHi = Math.max(...allLogN, logKnee);\nconst logNSpan = logNHi - logNLo;\nconst xMin = 10 ** (logNLo - logNSpan * X_PAD_SHARE);\nconst xMax = 10 ** (logNHi + logNSpan * PLATEAU_SHARE);\nconst stressValues = [...data.map((d) => d[STRESS]), ...LIMIT_LINES.map((l) => material[l.key])];\nconst logSLo = Math.log10(Math.min(...stressValues));\nconst logSHi = Math.log10(Math.max(...stressValues));\nconst logSPad = (logSHi - logSLo) * Y_PAD_SHARE;\nconst yMin = 10 ** (logSLo - logSPad);\nconst yMax = 10 ** (logSHi + logSPad);\n\nconst cycleTicks = Array.from(\n  { length: Math.floor(Math.log10(xMax)) - Math.ceil(Math.log10(xMin)) + 1 },\n  (_, i) => 10 ** (Math.ceil(Math.log10(xMin)) + i),\n);\nconst rawStep = (yMax - yMin) / Y_TICK_TARGET;\nconst stepMagnitude = 10 ** Math.floor(Math.log10(rawStep));\nconst stressStep = [1, 2, 5, 10].map((m) => m * stepMagnitude).find((s) => s >= rawStep);\nconst stressTicks = Array.from(\n  { length: Math.floor(yMax / stressStep) - Math.ceil(yMin / stressStep) + 1 },\n  (_, i) => (Math.ceil(yMin / stressStep) + i) * stressStep,\n);\n\n// Fit curve on a log-spaced grid: the Basquin line from the left edge down to the knee, where it\n// meets the endurance limit; the limit's reference line carries the plateau beyond\nconst fitCycles = [\n  ...Array.from({ length: FIT_POINTS }, (_, i) =>\n    10 ** (Math.log10(xMin) + (i / (FIT_POINTS - 1)) * (Math.log10(xMax) - Math.log10(xMin))),\n  ).filter((n) => Math.log10(n) < logKnee),\n  10 ** logKnee,\n];\nconst fitStress = fitCycles.map((n) => 10 ** (basquinLogA + basquinExponent * Math.log10(n)));\n\n// Fatigue regions along the cycle axis, clipped to the axis extent\nconst regionEdges = [xMin, Math.min(Math.max(LCF_HCF_BOUNDARY, xMin), xMax), Math.min(10 ** logKnee, xMax), xMax];\nconst regions = REGION_NAMES.map((name, i) => ({ name, from: regionEdges[i], to: regionEdges[i + 1] })).filter(\n  (r) => r.to > r.from,\n);\n\nconst specimens = data.map((d, i) => ({ id: `specimen-${i}`, x: d[CYCLES], y: d[STRESS] }));\nconst levelCount = new Set(data.map((d) => d[STRESS])).size;\nconst kneeExponent = [...String(Math.floor(logKnee))].map((digit) => SUPERSCRIPT[Number(digit)]).join(\"\");\n\nconst TITLE = \"sn-curve-basic · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `n = ${data.length} · ${levelCount} stress levels · ${FIT_LABEL} S = ${Math.round(\n  10 ** basquinLogA,\n)} · N^${basquinExponent.toFixed(3).replace(\"-\", \"−\")} (R² = ${rSquared.toFixed(2)}) · knee at N = ${(\n  10 ** (logKnee - Math.floor(logKnee))\n).toFixed(1)} × 10${kneeExponent}`;\nconst HEADER_H = 80;\nconst LEGEND_H = 40;\nconst X_AXIS_H = 64;\nconst REGION_BAND_H = 52;\n\nfunction FatigueRegions() {\n  const xScale = useXScale(\"cycles\");\n  const { top, height } = useDrawingArea();\n  const lineY = top + height + X_AXIS_H + 14;\n  return (\n    <g stroke={t.inkSoft} strokeWidth={1.2}>\n      {regions.map((r) => {\n        const x0 = xScale(r.from) + 4;\n        const x1 = xScale(r.to) - 4;\n        return (\n          <g key={r.name}>\n            <line x1={x0} y1={lineY} x2={x1} y2={lineY} />\n            <line x1={x0} y1={lineY - 5} x2={x0} y2={lineY + 5} />\n            <line x1={x1} y1={lineY - 5} x2={x1} y2={lineY + 5} />\n            <text\n              x={(x0 + x1) / 2}\n              y={lineY + 24}\n              textAnchor=\"middle\"\n              fontSize={14}\n              stroke=\"none\"\n              fill={t.inkSoft}\n            >\n              {r.name}\n            </text>\n          </g>\n        );\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      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        margin={{ top: 12, right: 48, bottom: REGION_BAND_H, left: 24 }}\n        skipAnimation\n        series={[\n          {\n            type: \"scatter\",\n            id: \"specimens\",\n            xAxisId: \"cycles\",\n            yAxisId: \"stress\",\n            data: specimens,\n            color: t.palette[0],\n            markerSize: 9,\n            label: SPECIMEN_LABEL,\n          },\n          {\n            type: \"line\",\n            id: \"fit\",\n            xAxisId: \"cycles\",\n            yAxisId: \"stress\",\n            data: fitStress,\n            color: t.palette[1],\n            showMark: false,\n            curve: \"linear\",\n            label: FIT_LABEL,\n          },\n        ]}\n        xAxis={[\n          {\n            id: \"cycles\",\n            scaleType: \"log\",\n            data: fitCycles,\n            min: xMin,\n            max: xMax,\n            tickInterval: cycleTicks,\n            valueFormatter: (n) =>\n              `10${[...String(Math.round(Math.log10(n)))].map((digit) => SUPERSCRIPT[Number(digit)]).join(\"\")}`,\n            label: CYCLES,\n            height: X_AXIS_H,\n            tickLabelStyle: { fontSize: 16, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"stress\",\n            scaleType: \"log\",\n            min: yMin,\n            max: yMax,\n            tickInterval: stressTicks,\n            label: STRESS,\n            width: 84,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n      >\n        <ChartsWrapper legendPosition={{ vertical: \"top\", horizontal: \"end\" }} legendDirection=\"horizontal\">\n          <ChartsLegend sx={{ fontSize: 15, color: t.ink, pr: 6 }} />\n          <ChartsSurface\n            sx={{\n              \"& .MuiLineChart-line\": { strokeWidth: 3 },\n              \"& .MuiScatterChart-marker\": { stroke: t.pageBg, strokeWidth: 1.5 },\n              \"& .MuiChartsGrid-line\": { stroke: t.grid },\n            }}\n          >\n            <ChartsGrid horizontal />\n            <LinePlot skipAnimation />\n            {LIMIT_LINES.map((l) => (\n              <ChartsReferenceLine\n                key={l.key}\n                y={material[l.key]}\n                axisId=\"stress\"\n                label={`${l.name} · ${material[l.key]} ${stressUnit}`}\n                labelAlign=\"end\"\n                labelStyle={{ fill: t.inkSoft, fontSize: 14 }}\n                lineStyle={{ stroke: t.inkSoft, strokeDasharray: l.dash, strokeWidth: 1.5 }}\n              />\n            ))}\n            <ScatterPlot />\n            <ChartsXAxis axisId=\"cycles\" />\n            <ChartsYAxis axisId=\"stress\" />\n            <FatigueRegions />\n          </ChartsSurface>\n          <ChartsTooltip trigger=\"item\" />\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}