{"spec_id":"probability-weibull","library":"muix","language":"javascript","code":"// anyplot.ai\n// probability-weibull: Weibull Probability Plot for Reliability Analysis\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-24\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 { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"probability-weibull · javascript · muix · anyplot.ai\";\nconst CHAR_LIFE_PCT = 63.2;\nconst PROB_TICKS = [0.1, 0.5, 1, 2, 5, 10, 20, 30, 50, 63.2, 80, 90, 95, 99, 99.9];\nconst LOG_TICK_MANTISSAS = [1, 1.5, 2, 3, 5, 7];\nconst DEFAULT_MIN_PROB_PCT = 1;\nconst DEFAULT_MAX_PROB_PCT = 99;\nconst Y_PAD_SHARE = 0.08;\nconst X_MIN_FACTOR = 0.72;\nconst X_MAX_FACTOR = 1.38;\nconst MARKER_RADIUS = 7;\nconst HEADER_HEIGHT = 76;\nconst PROB_AXIS_LABEL = \"Cumulative Failure Probability (%)\";\nconst FAILURE_LABEL = \"Failure\";\nconst CENSORED_LABEL = \"Suspended (censored)\";\n\n// Columns: set these to your data's column names\nconst TIME = \"Cycles to Failure (kcycles)\"; // role: x\nconst IS_CENSORED = \"Right Censored\"; // role: group\n\n// Data: replace this block with your own records\nconst BETA_TRUE = 2.4;\nconst ETA_TRUE = 420;\nconst SAMPLE_SIZE = 24;\nconst CENSORED_EVERY = 6;\n\nconst rawSamples: number[] = [];\nlet lcgState = 42 >>> 0;\nfor (let i = 0; i < SAMPLE_SIZE; i += 1) {\n  lcgState = (Math.imul(lcgState, 1664525) + 1013904223) >>> 0;\n  const u = lcgState / 4294967296;\n  const sampleTime = Math.round(ETA_TRUE * Math.pow(-Math.log(1 - u), 1 / BETA_TRUE) * 10) / 10;\n  rawSamples.push(sampleTime);\n}\nrawSamples.sort((a, b) => a - b);\n\nconst data: Array<Record<string, number | boolean>> = rawSamples.map((timeVal, idx) => ({\n  [TIME]: timeVal,\n  [IS_CENSORED]: idx > 0 && (idx + 1) % CENSORED_EVERY === 0,\n}));\n\n// Plot: reads only data and the constants above\nconst sortedObs = [...data].sort((a, b) => Number(a[TIME]) - Number(b[TIME]));\nconst totalN = sortedObs.length;\nlet adjustedRank = 0;\nlet lastProbability = 0;\nconst plottedPoints = sortedObs.map((row, idx) => {\n  const time = Number(row[TIME]);\n  const isCensored = Boolean(row[IS_CENSORED]);\n  const reverseRank = totalN - idx;\n  if (!isCensored) {\n    adjustedRank += (totalN + 1 - adjustedRank) / (1 + reverseRank);\n    lastProbability = (adjustedRank - 0.3) / (totalN + 0.4);\n  }\n  const weibullYVal = Math.log(-Math.log(1 - lastProbability));\n  return {\n    id: `obs-${idx}`,\n    time,\n    isCensored,\n    probability: lastProbability,\n    y: weibullYVal,\n  };\n});\n\nconst failurePoints = plottedPoints.filter((p) => !p.isCensored);\nconst censoredPoints = plottedPoints.filter((p) => p.isCensored);\n\nconst xs = failurePoints.map((p) => Math.log(p.time));\nconst ys = failurePoints.map((p) => p.y);\nconst nFailures = xs.length;\nconst meanX = xs.reduce((a, b) => a + b, 0) / nFailures;\nconst meanY = ys.reduce((a, b) => a + b, 0) / nFailures;\nlet sxy = 0;\nlet sxx = 0;\nfor (let i = 0; i < nFailures; i += 1) {\n  sxy += (xs[i] - meanX) * (ys[i] - meanY);\n  sxx += (xs[i] - meanX) ** 2;\n}\nconst beta = sxy / sxx;\nconst intercept = meanY - beta * meanX;\nconst eta = Math.exp(-intercept / beta);\n\nconst minObsTime = Math.min(...plottedPoints.map((p) => p.time));\nconst maxObsTime = Math.max(...plottedPoints.map((p) => p.time));\nconst xMin = minObsTime * X_MIN_FACTOR;\nconst xMax = maxObsTime * X_MAX_FACTOR;\nconst xTickValues: number[] = [];\nfor (let decade = Math.floor(Math.log10(xMin)); decade <= Math.ceil(Math.log10(xMax)); decade += 1) {\n  for (const m of LOG_TICK_MANTISSAS) {\n    const tick = m * 10 ** decade;\n    if (tick >= xMin && tick <= xMax) xTickValues.push(tick);\n  }\n}\nconst yAtCharLife =Math.log(-Math.log(1 - CHAR_LIFE_PCT / 100));\n\nconst minPlotY = Math.min(...plottedPoints.map((p) => p.y));\nconst maxPlotY = Math.max(...plottedPoints.map((p) => p.y));\nconst plotYSpan = maxPlotY - minPlotY;\nconst yMin = Math.min(\n  minPlotY - plotYSpan * Y_PAD_SHARE,\n  Math.log(-Math.log(1 - DEFAULT_MIN_PROB_PCT / 100)),\n);\nconst yMax = Math.max(\n  maxPlotY + plotYSpan * Y_PAD_SHARE,\n  Math.log(-Math.log(1 - DEFAULT_MAX_PROB_PCT / 100)),\n);\n\nconst activeProbTicks = PROB_TICKS.filter((p) => {\n  const wy = Math.log(-Math.log(1 - p / 100));\n  return wy >= yMin && wy <= yMax;\n});\nconst yTickValues = activeProbTicks.map((p) => Math.log(-Math.log(1 - p / 100)));\nconst yTickLabels = new Map(activeProbTicks.map((p, i) => [yTickValues[i], `${p}%`]));\n\nconst fitXStart = Math.max(xMin, Math.exp((yMin - intercept) / beta));\nconst fitXEnd = Math.min(xMax, Math.exp((yMax - intercept) / beta));\nconst fitLineX = [fitXStart, fitXEnd];\nconst fitLineY = fitLineX.map((x) => beta * Math.log(x) + intercept);\n\nconst timeUnitMatch = /\\(([^)]+)\\)/.exec(TIME);\nconst timeUnit = timeUnitMatch ? timeUnitMatch[1] : \"\";\nconst unitSuffix = timeUnit ? ` ${timeUnit}` : \"\";\nconst fitLegendText = `Fit: β ≈ ${beta.toFixed(2)}, η ≈ ${Math.round(eta)}${unitSuffix}`;\nconst charLifeCalloutText = `${CHAR_LIFE_PCT}% · η ≈ ${Math.round(eta)}${unitSuffix}`;\n\nfunction WeibullOverlay() {\n  const { left, width: drawWidth } = useDrawingArea();\n  const xScale = useXScale();\n  const yScale = useYScale();\n\n  const yPixelChar = Number(yScale(yAtCharLife));\n  const paddingX = 10;\n  const boxWidth = charLifeCalloutText.length * 7.6 + paddingX * 2;\n  const boxHeight = 26;\n  const boxX = left + drawWidth - boxWidth - 10;\n  const boxY = yPixelChar - boxHeight - 8;\n\n  return (\n    <g>\n      {failurePoints.map((pt) => (\n        <circle\n          key={pt.id}\n          cx={xScale(pt.time)}\n          cy={yScale(pt.y)}\n          r={MARKER_RADIUS}\n          fill={t.palette[0]}\n          stroke={t.pageBg}\n          strokeWidth={1.5}\n        />\n      ))}\n      {censoredPoints.map((pt) => (\n        <circle\n          key={pt.id}\n          cx={xScale(pt.time)}\n          cy={yScale(pt.y)}\n          r={MARKER_RADIUS}\n          fill={t.pageBg}\n          stroke={t.palette[0]}\n          strokeWidth={2.5}\n        />\n      ))}\n      <rect\n        x={boxX}\n        y={boxY}\n        width={boxWidth}\n        height={boxHeight}\n        rx={4}\n        fill={t.elevatedBg}\n        stroke={t.inkSoft}\n        strokeWidth={1}\n      />\n      <text\n        x={boxX + boxWidth / 2}\n        y={boxY + boxHeight / 2}\n        textAnchor=\"middle\"\n        dominantBaseline=\"central\"\n        fontSize={14}\n        fill={t.ink}\n      >\n        {charLifeCalloutText}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartHeight = height - HEADER_HEIGHT;\n\n  return (\n    <div\n      style={{\n        width,\n        height,\n        backgroundColor: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n        boxSizing: \"border-box\",\n      }}\n    >\n      <div\n        style={{\n          height: HEADER_HEIGHT,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"space-between\",\n          padding: \"0 48px 0 32px\",\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>{TITLE}</div>\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 28 }}>\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <svg width=\"24\" height=\"14\" aria-hidden=\"true\">\n              <line\n                x1=\"2\"\n                y1=\"7\"\n                x2=\"22\"\n                y2=\"7\"\n                stroke={t.ink}\n                strokeWidth={2.5}\n                strokeDasharray=\"6 3\"\n              />\n            </svg>\n            <span style={{ fontSize: 14, color: t.inkSoft, fontWeight: 500 }}>{fitLegendText}</span>\n          </div>\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <svg width=\"18\" height=\"18\" aria-hidden=\"true\">\n              <circle cx=\"9\" cy=\"9\" r=\"6.5\" fill={t.palette[0]} />\n            </svg>\n            <span style={{ fontSize: 14, color: t.inkSoft, fontWeight: 500 }}>{FAILURE_LABEL}</span>\n          </div>\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <svg width=\"18\" height=\"18\" aria-hidden=\"true\">\n              <circle\n                cx=\"9\"\n                cy=\"9\"\n                r=\"6.5\"\n                fill=\"none\"\n                stroke={t.palette[0]}\n                strokeWidth={2.5}\n              />\n            </svg>\n            <span style={{ fontSize: 14, color: t.inkSoft, fontWeight: 500 }}>\n              {CENSORED_LABEL}\n            </span>\n          </div>\n        </div>\n      </div>\n      <ChartsContainer\n        width={width}\n        height={chartHeight}\n        margin={{ top: 14, right: 48, bottom: 18, left: 20 }}\n        series={[\n          {\n            type: \"line\",\n            id: \"fit\",\n            data: fitLineY,\n            curve: \"linear\",\n            color: t.ink,\n            showMark: false,\n            disableHighlight: true,\n          },\n        ]}\n        xAxis={[\n          {\n            data: fitLineX,\n            scaleType: \"log\",\n            min: xMin,\n            max: xMax,\n            height: 58,\n            tickInterval: xTickValues,\n            valueFormatter: (v: number) => `${Number(v.toPrecision(3))}`,\n            label: TIME,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 15, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: yMin,\n            max: yMax,\n            width: 96,\n            tickInterval: yTickValues,\n            valueFormatter: (v: number) => yTickLabels.get(v) ?? \"\",\n            label: PROB_AXIS_LABEL,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 15, fill: t.ink },\n          },\n        ]}\n        skipAnimation\n      >\n        <ChartsGrid horizontal vertical />\n        <LinePlot\n          skipAnimation\n          slotProps={{ line: { strokeDasharray: \"12 7\", strokeWidth: 2.5 } }}\n        />\n        <ChartsReferenceLine\n          y={yAtCharLife}\n          lineStyle={{\n            stroke: t.inkSoft,\n            strokeDasharray: \"4 4\",\n            strokeWidth: 1.5,\n          }}\n        />\n        <WeibullOverlay />\n        <ChartsXAxis />\n        <ChartsYAxis />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}