{"spec_id":"heatmap-rainflow","library":"muix","language":"javascript","code":"// anyplot.ai\n// heatmap-rainflow: Rainflow Counting Matrix for Fatigue Analysis\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 90/100 | Updated: 2026-11-08\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ContinuousColorLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { useXScale, useYScale, useZColorScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Columns: set these to your data's column names\nconst MEAN = \"Cycle mean, blade-root flapwise moment (kN·m)\"; // role: mean\nconst AMPLITUDE = \"Cycle amplitude, half-range (kN·m)\"; // role: amplitude\nconst COUNT = \"Cycle count\"; // role: count\n\n// Data: replace this block with your own records, one object per amplitude-mean bin\n// Synthetic wind-turbine blade-root flapwise bending moment: a slow operating\n// trend (gusts, pitch changes) carries fast turbulent fluctuations. Three-point\n// rainflow counting (ASTM E1049; full cycles weigh 1, the residual half-cycles\n// 0.5) reduces it to cycles, binned into a 20 x 20 amplitude-by-mean matrix.\nconst data = (() => {\n  let state = 42 >>> 0;\n  const rng = () => {\n    state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n    return state / 4294967296;\n  };\n\n  const signal = Array.from({ length: 6000 }, (_, i) => {\n    const trend = 620 + 180 * Math.sin((2 * Math.PI * i) / 900) + 90 * Math.sin((2 * Math.PI * i) / 2600 + 1.1);\n    const turbulence =\n      140 * Math.sin((2 * Math.PI * i) / 41) +\n      70 * Math.sin((2 * Math.PI * i) / 17 + 0.6) +\n      40 * Math.sin((2 * Math.PI * i) / 6.3 + 2.4) +\n      50 * (rng() - 0.5);\n    return trend + turbulence;\n  });\n\n  // Rainflow counting works on reversals only: keep the turning points\n  const turningPoints = [signal[0]];\n  for (let i = 1; i < signal.length - 1; i += 1) {\n    if (signal[i] > signal[i - 1] !== signal[i + 1] > signal[i]) turningPoints.push(signal[i]);\n  }\n  turningPoints.push(signal[signal.length - 1]);\n\n  const stack: number[] = [];\n  const cycles: { amplitude: number; mean: number; weight: number }[] = [];\n  for (const point of turningPoints) {\n    stack.push(point);\n    while (stack.length >= 3) {\n      const n = stack.length;\n      const innerRange = Math.abs(stack[n - 2] - stack[n - 3]);\n      const outerRange = Math.abs(stack[n - 1] - stack[n - 2]);\n      if (innerRange > outerRange) break;\n      cycles.push({ amplitude: innerRange / 2, mean: (stack[n - 2] + stack[n - 3]) / 2, weight: 1 });\n      stack.splice(n - 3, 2);\n    }\n  }\n  for (let i = 0; i < stack.length - 1; i += 1) {\n    cycles.push({ amplitude: Math.abs(stack[i + 1] - stack[i]) / 2, mean: (stack[i + 1] + stack[i]) / 2, weight: 0.5 });\n  }\n\n  const binCount = 20;\n  const amplitudeMax = Math.max(...cycles.map((c) => c.amplitude));\n  const meanMin = Math.min(...cycles.map((c) => c.mean));\n  const meanMax = Math.max(...cycles.map((c) => c.mean));\n  const amplitudeWidth = amplitudeMax / binCount;\n  const meanWidth = (meanMax - meanMin) / binCount;\n  const weights = new Array(binCount * binCount).fill(0);\n  for (const c of cycles) {\n    const a = Math.min(binCount - 1, Math.floor(c.amplitude / amplitudeWidth));\n    const m = Math.min(binCount - 1, Math.floor((c.mean - meanMin) / meanWidth));\n    weights[a * binCount + m] += c.weight;\n  }\n  return weights.map((w, k) => ({\n    [MEAN]: Number((meanMin + ((k % binCount) + 0.5) * meanWidth).toFixed(1)),\n    [AMPLITUDE]: Number(((Math.floor(k / binCount) + 0.5) * amplitudeWidth).toFixed(1)),\n    [COUNT]: Math.round(w),\n  }));\n})();\n\n// Plot: reads only data and the constants above\nconst meanCenters = [...new Set(data.map((d) => d[MEAN]))].sort((a, b) => a - b);\nconst amplitudeCenters = [...new Set(data.map((d) => d[AMPLITUDE]))].sort((a, b) => a - b);\n// Bin width = the smallest step between neighbouring bin centres\nconst meanBin = Math.min(...meanCenters.slice(1).map((v, i) => v - meanCenters[i]));\nconst amplitudeBin = Math.min(...amplitudeCenters.slice(1).map((v, i) => v - amplitudeCenters[i]));\n\nconst counted = data.filter((d) => d[COUNT] > 0);\nconst empty = data.filter((d) => !(d[COUNT] > 0));\nconst countMin = Math.min(...counted.map((d) => d[COUNT]));\nconst countMax = Math.max(...counted.map((d) => d[COUNT]));\nconst totalCycles = counted.reduce((s, d) => s + d[COUNT], 0);\nconst peak = counted.filter((d) => d[COUNT] === countMax).slice(0, 1);\n// Draw order: empty bins as faint outlines, counted bins filled, the peak bin outlined on top\nconst cellLayers = [\n  ...empty.map((d) => ({ d, filled: false, stroke: t.grid, strokeWidth: 1 })),\n  ...counted.map((d) => ({ d, filled: true, stroke: \"none\", strokeWidth: 0 })),\n  ...peak.map((d) => ({ d, filled: false, stroke: t.ink, strokeWidth: 3 })),\n];\n\nconst TITLE = \"heatmap-rainflow · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${totalCycles.toLocaleString(\"en-US\")} counted cycles in ${meanCenters.length} × ${amplitudeCenters.length} bins · empty bins left unfilled · outlined: peak bin, ${countMax.toLocaleString(\"en-US\")} cycles`;\nconst HEADER_H = 82;\nconst LEGEND_W = 170;\nconst CELL_GAP = 2; // px between neighbouring cells\n\n// Cells in data coordinates: each bin spans its centre ± half a bin width\nfunction RainflowCells() {\n  const xScale = useXScale() as (v: number) => number;\n  const yScale = useYScale() as (v: number) => number;\n  const colorScale = useZColorScale() as (v: number) => string;\n  return (\n    <g>\n      {cellLayers.map(({ d, filled, stroke, strokeWidth }, i) => {\n        const x0 = xScale(d[MEAN] - meanBin / 2);\n        const x1 = xScale(d[MEAN] + meanBin / 2);\n        const y0 = yScale(d[AMPLITUDE] + amplitudeBin / 2);\n        const y1 = yScale(d[AMPLITUDE] - amplitudeBin / 2);\n        return (\n          <rect\n            key={i}\n            x={x0 + CELL_GAP / 2}\n            y={y0 + CELL_GAP / 2}\n            width={Math.max(x1 - x0 - CELL_GAP, 0)}\n            height={Math.max(y1 - y0 - CELL_GAP, 0)}\n            fill={filled ? colorScale(Math.log(d[COUNT])) : \"none\"}\n            stroke={stroke}\n            strokeWidth={strokeWidth}\n          />\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartH = height - HEADER_H;\n\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\", overflow: \"hidden\" }}>\n      <Box sx={{ height: HEADER_H, pt: \"16px\", textAlign: \"center\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.3 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.5 }}>{SUBTITLE}</Typography>\n      </Box>\n      <ChartsDataProvider\n        width={width - LEGEND_W}\n        height={chartH}\n        series={[]}\n        skipAnimation\n        margin={{ top: 16, right: 24, bottom: 16, left: 24 }}\n        xAxis={[\n          {\n            scaleType: \"linear\",\n            min: meanCenters[0] - meanBin / 2,\n            max: meanCenters[meanCenters.length - 1] + meanBin / 2,\n            height: 64,\n            label: MEAN,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: amplitudeCenters[0] - amplitudeBin / 2,\n            max: amplitudeCenters[amplitudeCenters.length - 1] + amplitudeBin / 2,\n            width: 84,\n            label: AMPLITUDE,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        // Log colour scale: rainflow matrices are heavily right-skewed\n        zAxis={[\n          {\n            colorMap: {\n              type: \"continuous\",\n              min: Math.log(countMin),\n              max: Math.log(countMax),\n              color: [t.seq[0], t.seq[1]],\n            },\n          },\n        ]}\n      >\n        <ChartsWrapper\n          legendPosition={{ vertical: \"middle\", horizontal: \"end\" }}\n          legendDirection=\"vertical\"\n          sx={{ width, height: chartH }}\n        >\n          <Box\n            sx={{\n              gridArea: \"legend\",\n              width: LEGEND_W,\n              height: chartH * 0.6,\n              display: \"flex\",\n              flexDirection: \"column\",\n              alignItems: \"center\",\n            }}\n          >\n            <Typography sx={{ color: t.ink, fontSize: 15, mb: \"8px\", textAlign: \"center\", lineHeight: 1.3 }}>\n              {COUNT}\n              <br />\n              (log scale)\n            </Typography>\n            <ContinuousColorLegend\n              direction=\"vertical\"\n              thickness={20}\n              labelPosition=\"end\"\n              minLabel={({ value }) => Math.round(Math.exp(Number(value))).toLocaleString(\"en-US\")}\n              maxLabel={({ value }) => Math.round(Math.exp(Number(value))).toLocaleString(\"en-US\")}\n              sx={{ flex: 1, color: t.inkSoft, fontSize: 14 }}\n            />\n          </Box>\n          <ChartsSurface>\n            <RainflowCells />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </Box>\n  );\n}\n"}