{"spec_id":"ma-differential-expression","library":"muix","language":"javascript","code":"// anyplot.ai\n// ma-differential-expression: MA Plot for Differential Expression\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 85/100 | Updated: 2026-10-24\n\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\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 { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst LFC_THRESHOLD = 1;\nconst N_SMOOTH_BINS = 24;\nconst SMOOTH_BW_FACTOR = 2.2;\nconst NOT_SIG_ALPHA_HEX = \"55\";\nconst SIG_ALPHA = 0.6;\nconst X_PAD_SHARE = 0.02;\nconst Y_PAD_SHARE = 0.06;\n\nconst NOT_SIG_LABEL = \"Not significant\";\nconst UP_REG_LABEL = \"Up-regulated\";\nconst DOWN_REG_LABEL = \"Down-regulated\";\n\nconst SEMANTIC_COLORS: Record<string, string> = {\n  [UP_REG_LABEL]: t.palette[0],\n  [DOWN_REG_LABEL]: t.palette[4],\n};\n\n// Columns: set these to your data's column names\nconst MEAN_EXPR = \"Mean expression (log₂ A)\"; // role: mean_expression\nconst LFC = \"Log₂ fold change (M)\"; // role: log_fold_change\nconst SIG = \"Significant\"; // role: significant\n\n// Data: replace this block with your own records\nconst N_GENES = 10000;\nconst DE_SHARE = 0.15; // share of genes truly changed by the treatment\nconst MAX_LOG2_MEAN = 15.5;\nconst Z_CUTOFF = 3.3; // Wald |z| equivalent of padj < 0.05 after BH correction\nlet seed = 42 >>> 0;\nconst rand = () => {\n  seed = (Math.imul(1664525, seed) + 1013904223) >>> 0;\n  return (seed + 1) / 0x100000001;\n};\nconst randNormal = () => Math.sqrt(-2 * Math.log(rand())) * Math.cos(2 * Math.PI * rand());\n\nconst data: Array<Record<string, number | boolean>> = [];\nfor (let i = 0; i < N_GENES; i++) {\n  // log2 baseMean: right-skewed gamma(3, 1.9), many low-count genes, long tail to ~15\n  let a: number;\n  do {\n    a = -1.9 * Math.log(rand() * rand() * rand());\n  } while (a > MAX_LOG2_MEAN);\n\n  // Standard error of the fold change shrinks as counts grow\n  const se = 0.12 + 2.0 / (a + 1.2);\n  const isDE = rand() < DE_SHARE;\n  const trueLfc = isDE ? Math.sign(rand() - 0.5) * (0.6 - 1.1 * Math.log(rand())) : 0;\n  const m = trueLfc + se * randNormal();\n  const sig = Math.abs(m) / se > Z_CUTOFF;\n\n  data.push({\n    [MEAN_EXPR]: a,\n    [LFC]: m,\n    [SIG]: sig,\n  });\n}\n\n// Plot: reads only data and the constants above\nlet minA = Infinity;\nlet maxA = -Infinity;\nlet minM = Infinity;\nlet maxM = -Infinity;\nfor (const row of data) {\n  const a = Number(row[MEAN_EXPR]);\n  const m = Number(row[LFC]);\n  if (a < minA) minA = a;\n  if (a > maxA) maxA = a;\n  if (m < minM) minM = m;\n  if (m > maxM) maxM = m;\n}\nconst rawXSpan = maxA - minA;\nconst xAxisMin = minA - rawXSpan * X_PAD_SHARE;\nconst xAxisMax = maxA + rawXSpan * X_PAD_SHARE;\nconst maxAbsM = Math.max(Math.abs(minM), Math.abs(maxM));\nconst yBound = maxAbsM * (1 + Y_PAD_SHARE);\nconst yAxisMin = -yBound;\nconst yAxisMax = yBound;\n\nconst usedColors = new Set(Object.values(SEMANTIC_COLORS));\nlet nextPaletteIdx = 0;\nconst statusColorMap: Record<string, string> = {\n  [NOT_SIG_LABEL]: `${t.inkSoft}${NOT_SIG_ALPHA_HEX}`,\n  [UP_REG_LABEL]: SEMANTIC_COLORS[UP_REG_LABEL],\n  [DOWN_REG_LABEL]: SEMANTIC_COLORS[DOWN_REG_LABEL],\n};\nwhile (usedColors.has(t.palette[nextPaletteIdx])) nextPaletteIdx++;\nconst trendColor = t.palette[nextPaletteIdx];\n\nconst notSigPts: Array<{ id: number; x: number; y: number }> = [];\nconst upRegPts: Array<{ id: number; x: number; y: number }> = [];\nconst downRegPts: Array<{ id: number; x: number; y: number }> = [];\n\nfor (let i = 0; i < data.length; i++) {\n  const row = data[i];\n  const pt = { id: i, x: Number(row[MEAN_EXPR]), y: Number(row[LFC]) };\n  if (!row[SIG]) {\n    notSigPts.push(pt);\n  } else if (pt.y > 0) {\n    upRegPts.push(pt);\n  } else {\n    downRegPts.push(pt);\n  }\n}\n\n// Windowed tricube local average (LOESS trend) across expression range\nconst smoothPoints: Array<{ x: number; y: number }> = [];\nconst xSpan = xAxisMax - xAxisMin;\nconst bw = (xSpan / N_SMOOTH_BINS) * SMOOTH_BW_FACTOR;\nfor (let b = 0; b <= N_SMOOTH_BINS; b++) {\n  const cx = xAxisMin + (b * xSpan) / N_SMOOTH_BINS;\n  let wSum = 0;\n  let wySum = 0;\n  for (let i = 0; i < data.length; i++) {\n    const dx = Math.abs(Number(data[i][MEAN_EXPR]) - cx);\n    if (dx < bw) {\n      const u = dx / bw;\n      const w = Math.pow(1 - u * u * u, 3);\n      wSum += w;\n      wySum += w * Number(data[i][LFC]);\n    }\n  }\n  if (wSum > 0) {\n    smoothPoints.push({ x: cx, y: wySum / wSum });\n  }\n}\n\nfunction MaOverlay() {\n  const xScale = useXScale(\"x\") as (v: number) => number;\n  const yScale = useYScale(\"y\") as (v: number) => number;\n\n  const R = 4.5;\n  const H = R * 0.866;\n\n  const smoothD = smoothPoints\n    .map((p, i) => `${i === 0 ? \"M\" : \"L\"}${xScale(p.x).toFixed(1)},${yScale(p.y).toFixed(1)}`)\n    .join(\" \");\n\n  return (\n    <g>\n      {upRegPts.map((p) => {\n        const x = xScale(p.x);\n        const y = yScale(p.y);\n        return (\n          <polygon\n            key={p.id}\n            points={`${x},${y - R} ${x - H},${y + R * 0.5} ${x + H},${y + R * 0.5}`}\n            fill={statusColorMap[UP_REG_LABEL]}\n            fillOpacity={SIG_ALPHA}\n          />\n        );\n      })}\n      {downRegPts.map((p) => {\n        const x = xScale(p.x);\n        const y = yScale(p.y);\n        return (\n          <polygon\n            key={p.id}\n            points={`${x},${y + R} ${x - H},${y - R * 0.5} ${x + H},${y - R * 0.5}`}\n            fill={statusColorMap[DOWN_REG_LABEL]}\n            fillOpacity={SIG_ALPHA}\n          />\n        );\n      })}\n      <path\n        d={smoothD}\n        fill=\"none\"\n        stroke={trendColor}\n        strokeWidth={3}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      />\n      {/* Reference lines and right-margin threshold labels drawn above the dense cloud */}\n      <line\n        x1={xScale(xAxisMin)}\n        y1={yScale(0)}\n        x2={xScale(xAxisMax)}\n        y2={yScale(0)}\n        stroke={t.ink}\n        strokeWidth={1.8}\n        strokeOpacity={0.75}\n      />\n      <line\n        x1={xScale(xAxisMin)}\n        y1={yScale(LFC_THRESHOLD)}\n        x2={xScale(xAxisMax)}\n        y2={yScale(LFC_THRESHOLD)}\n        stroke={t.ink}\n        strokeWidth={1.6}\n        strokeDasharray=\"8 4\"\n        strokeOpacity={0.85}\n      />\n      <line\n        x1={xScale(xAxisMin)}\n        y1={yScale(-LFC_THRESHOLD)}\n        x2={xScale(xAxisMax)}\n        y2={yScale(-LFC_THRESHOLD)}\n        stroke={t.ink}\n        strokeWidth={1.6}\n        strokeDasharray=\"8 4\"\n        strokeOpacity={0.85}\n      />\n      <text\n        x={xScale(xAxisMax) + 10}\n        y={yScale(LFC_THRESHOLD)}\n        fontSize={14}\n        fill={t.inkSoft}\n        dominantBaseline=\"middle\"\n      >\n        {`log₂FC = +${LFC_THRESHOLD}`}\n      </text>\n      <text\n        x={xScale(xAxisMax) + 10}\n        y={yScale(-LFC_THRESHOLD)}\n        fontSize={14}\n        fill={t.inkSoft}\n        dominantBaseline=\"middle\"\n      >\n        {`log₂FC = −${LFC_THRESHOLD}`}\n      </text>\n    </g>\n  );\n}\n\nconst LEGEND_ITEMS = [\n  { label: NOT_SIG_LABEL, color: t.inkSoft, kind: \"dot\" as const },\n  { label: UP_REG_LABEL, color: statusColorMap[UP_REG_LABEL], kind: \"up\" as const },\n  { label: DOWN_REG_LABEL, color: statusColorMap[DOWN_REG_LABEL], kind: \"down\" as const },\n  { label: \"LOESS trend\", color: trendColor, kind: \"line\" as const },\n];\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const TITLE_H = 54;\n  const LEGEND_H = 42;\n  const chartH = height - TITLE_H - LEGEND_H;\n\n  return (\n    <Box\n      sx={{\n        width,\n        height,\n        display: \"flex\",\n        flexDirection: \"column\",\n        bgcolor: t.pageBg,\n      }}\n    >\n      <Typography\n        sx={{\n          height: TITLE_H,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          fontSize: 22,\n          fontWeight: 500,\n          color: t.ink,\n          px: 4,\n          flexShrink: 0,\n        }}\n      >\n        ma-differential-expression · javascript · muix · anyplot.ai\n      </Typography>\n\n      <ChartsContainer\n        width={width}\n        height={chartH}\n        skipAnimation\n        margin={{ top: 12, right: 116, bottom: 16, left: 20 }}\n        series={[\n          {\n            type: \"scatter\",\n            id: \"notSig\",\n            label: NOT_SIG_LABEL,\n            data: notSigPts,\n            color: statusColorMap[NOT_SIG_LABEL],\n            markerSize: 2.5,\n            xAxisId: \"x\",\n            yAxisId: \"y\",\n          },\n        ]}\n        xAxis={[\n          {\n            id: \"x\",\n            scaleType: \"linear\",\n            min: xAxisMin,\n            max: xAxisMax,\n            height: 54,\n            label: MEAN_EXPR,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            tickNumber: 7,\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"y\",\n            scaleType: \"linear\",\n            min: yAxisMin,\n            max: yAxisMax,\n            width: 76,\n            label: LFC,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            tickNumber: 9,\n          },\n        ]}\n      >\n        <ChartsGrid horizontal />\n        <ScatterPlot />\n        <MaOverlay />\n        <ChartsXAxis axisId=\"x\" />\n        <ChartsYAxis axisId=\"y\" />\n      </ChartsContainer>\n\n      <Box\n        sx={{\n          height: LEGEND_H,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: \"28px\",\n          pb: \"6px\",\n        }}\n      >\n        {LEGEND_ITEMS.map((item) => (\n          <Box\n            key={item.label}\n            sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}\n          >\n            {item.kind === \"dot\" ? (\n              <Box\n                sx={{\n                  width: 9,\n                  height: 9,\n                  borderRadius: \"50%\",\n                  bgcolor: item.color,\n                  opacity: 0.65,\n                }}\n              />\n            ) : item.kind === \"up\" ? (\n              <svg width={14} height={14} viewBox=\"0 0 14 14\">\n                <polygon points=\"7,1 1,12 13,12\" fill={item.color} fillOpacity={SIG_ALPHA} />\n              </svg>\n            ) : item.kind === \"down\" ? (\n              <svg width={14} height={14} viewBox=\"0 0 14 14\">\n                <polygon points=\"7,13 1,2 13,2\" fill={item.color} fillOpacity={SIG_ALPHA} />\n              </svg>\n            ) : (\n              <Box\n                sx={{\n                  width: 20,\n                  height: 3.5,\n                  bgcolor: item.color,\n                  borderRadius: \"2px\",\n                }}\n              />\n            )}\n            <Typography sx={{ color: t.inkSoft, fontSize: \"14px\", lineHeight: 1 }}>\n              {item.label}\n            </Typography>\n          </Box>\n        ))}\n      </Box>\n    </Box>\n  );\n}\n"}