{"spec_id":"network-weighted","library":"muix","language":"javascript","code":"// anyplot.ai\n// network-weighted: Weighted Network Graph with Edge Thickness\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 86/100 | Updated: 2026-10-24\n//# anyplot-orientation: square\n\nimport { useState } from \"react\";\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { useXScale, useYScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"network-weighted · javascript · muix · anyplot.ai\";\nconst TITLE_H = 58;\nconst LEGEND_H = 112;\nconst AREA = 4.5;\nconst ITERATIONS = 500;\nconst INITIAL_TEMP = 0.12;\nconst COOLING_FACTOR = 0.99;\nconst PAD_MULT = 1.25;\nconst NODE_MIN_R = 15;\nconst NODE_MAX_R = 40;\nconst EDGE_MIN_W = 2;\nconst EDGE_MAX_W = 13;\n\n// Columns: set these to your data's column names\nconst NODE_ID = \"Lab code\"; // role: node\nconst NODE_LABEL = \"Research institute\"; // role: label\nconst DOMAIN = \"Research domain\"; // role: group\nconst SOURCE = \"Source lab\"; // role: source\nconst TARGET = \"Partner lab\"; // role: target\nconst WEIGHT = \"Co-authored papers\"; // role: weight\n\n// Data: replace this block with your own records\nconst nodes: Array<Record<string, string>> = [\n  { [NODE_ID]: \"GEN\", [NODE_LABEL]: \"Genomics Lab\", [DOMAIN]: \"Life Sciences\" },\n  { [NODE_ID]: \"IMM\", [NODE_LABEL]: \"Immunology Institute\", [DOMAIN]: \"Life Sciences\" },\n  { [NODE_ID]: \"NEU\", [NODE_LABEL]: \"Neuroscience Institute\", [DOMAIN]: \"Life Sciences\" },\n  { [NODE_ID]: \"MAR\", [NODE_LABEL]: \"Marine Biology Station\", [DOMAIN]: \"Life Sciences\" },\n  { [NODE_ID]: \"QPL\", [NODE_LABEL]: \"Quantum Physics Lab\", [DOMAIN]: \"Physical Sciences\" },\n  { [NODE_ID]: \"MAT\", [NODE_LABEL]: \"Materials Science Institute\", [DOMAIN]: \"Physical Sciences\" },\n  { [NODE_ID]: \"AST\", [NODE_LABEL]: \"Astrophysics Observatory\", [DOMAIN]: \"Physical Sciences\" },\n  { [NODE_ID]: \"CLI\", [NODE_LABEL]: \"Climate Science Center\", [DOMAIN]: \"Physical Sciences\" },\n  { [NODE_ID]: \"AIR\", [NODE_LABEL]: \"AI Research Center\", [DOMAIN]: \"Computer Science\" },\n  { [NODE_ID]: \"DSI\", [NODE_LABEL]: \"Data Science Institute\", [DOMAIN]: \"Computer Science\" },\n  { [NODE_ID]: \"ROB\", [NODE_LABEL]: \"Robotics Lab\", [DOMAIN]: \"Computer Science\" },\n  { [NODE_ID]: \"CHE\", [NODE_LABEL]: \"Chemical Engineering Lab\", [DOMAIN]: \"Engineering\" },\n  { [NODE_ID]: \"BIO\", [NODE_LABEL]: \"Bioengineering Institute\", [DOMAIN]: \"Engineering\" },\n  { [NODE_ID]: \"ENV\", [NODE_LABEL]: \"Environmental Engineering Lab\", [DOMAIN]: \"Engineering\" },\n];\n\nconst data: Array<Record<string, string | number>> = [\n  { [SOURCE]: \"GEN\", [TARGET]: \"IMM\", [WEIGHT]: 42 },\n  { [SOURCE]: \"GEN\", [TARGET]: \"NEU\", [WEIGHT]: 16 },\n  { [SOURCE]: \"GEN\", [TARGET]: \"BIO\", [WEIGHT]: 22 },\n  { [SOURCE]: \"IMM\", [TARGET]: \"BIO\", [WEIGHT]: 12 },\n  { [SOURCE]: \"IMM\", [TARGET]: \"NEU\", [WEIGHT]: 6 },\n  { [SOURCE]: \"NEU\", [TARGET]: \"AIR\", [WEIGHT]: 19 },\n  { [SOURCE]: \"MAR\", [TARGET]: \"ENV\", [WEIGHT]: 27 },\n  { [SOURCE]: \"MAR\", [TARGET]: \"CLI\", [WEIGHT]: 31 },\n  { [SOURCE]: \"QPL\", [TARGET]: \"MAT\", [WEIGHT]: 36 },\n  { [SOURCE]: \"QPL\", [TARGET]: \"AST\", [WEIGHT]: 21 },\n  { [SOURCE]: \"MAT\", [TARGET]: \"CHE\", [WEIGHT]: 33 },\n  { [SOURCE]: \"MAT\", [TARGET]: \"ENV\", [WEIGHT]: 9 },\n  { [SOURCE]: \"AST\", [TARGET]: \"CLI\", [WEIGHT]: 8 },\n  { [SOURCE]: \"CLI\", [TARGET]: \"ENV\", [WEIGHT]: 24 },\n  { [SOURCE]: \"AIR\", [TARGET]: \"DSI\", [WEIGHT]: 45 },\n  { [SOURCE]: \"AIR\", [TARGET]: \"ROB\", [WEIGHT]: 29 },\n  { [SOURCE]: \"DSI\", [TARGET]: \"ROB\", [WEIGHT]: 18 },\n  { [SOURCE]: \"DSI\", [TARGET]: \"GEN\", [WEIGHT]: 15 },\n  { [SOURCE]: \"DSI\", [TARGET]: \"CLI\", [WEIGHT]: 12 },\n  { [SOURCE]: \"DSI\", [TARGET]: \"MAT\", [WEIGHT]: 7 },\n  { [SOURCE]: \"DSI\", [TARGET]: \"BIO\", [WEIGHT]: 10 },\n  { [SOURCE]: \"ROB\", [TARGET]: \"BIO\", [WEIGHT]: 14 },\n  { [SOURCE]: \"CHE\", [TARGET]: \"BIO\", [WEIGHT]: 20 },\n  { [SOURCE]: \"CHE\", [TARGET]: \"ENV\", [WEIGHT]: 17 },\n];\n\n// Plot: reads only data and the constants above\ninterface LabNode {\n  id: string;\n  label: string;\n  domainName: string;\n  domainIndex: number;\n  weightedDegree: number;\n  radius: number;\n  x: number;\n  y: number;\n}\n\nconst domains: string[] = [];\nconst nodeIndexById = new Map<string, number>();\nconst layoutNodes: LabNode[] = [];\n\nfor (const row of nodes) {\n  const id = String(row[NODE_ID]);\n  const dom = String(row[DOMAIN]);\n  if (!domains.includes(dom)) domains.push(dom);\n  nodeIndexById.set(id, layoutNodes.length);\n  layoutNodes.push({\n    id,\n    label: String(row[NODE_LABEL]),\n    domainName: dom,\n    domainIndex: domains.indexOf(dom),\n    weightedDegree: 0,\n    radius: NODE_MIN_R,\n    x: 0,\n    y: 0,\n  });\n}\n\ninterface LabEdge {\n  sourceIdx: number;\n  targetIdx: number;\n  weight: number;\n  strokeWidth: number;\n  ratio: number;\n}\n\nconst edges: LabEdge[] = [];\nfor (const row of data) {\n  const sIdx = nodeIndexById.get(String(row[SOURCE]))!;\n  const tIdx = nodeIndexById.get(String(row[TARGET]))!;\n  const weight = Number(row[WEIGHT]);\n  layoutNodes[sIdx].weightedDegree += weight;\n  layoutNodes[tIdx].weightedDegree += weight;\n  edges.push({ sourceIdx: sIdx, targetIdx: tIdx, weight, strokeWidth: EDGE_MIN_W, ratio: 0 });\n}\n\nconst edgeWeights = edges.map((e) => e.weight);\nconst minWeight = Math.min(...edgeWeights);\nconst maxWeight = Math.max(...edgeWeights);\nconst weightSpan = maxWeight - minWeight;\n\nfor (const edge of edges) {\n  edge.ratio = (edge.weight - minWeight) / weightSpan;\n  edge.strokeWidth = EDGE_MIN_W + edge.ratio * (EDGE_MAX_W - EDGE_MIN_W);\n}\n\nconst degrees = layoutNodes.map((n) => n.weightedDegree);\nconst minDegree = Math.min(...degrees);\nconst maxDegree = Math.max(...degrees);\nconst degreeSpan = maxDegree - minDegree;\n\nfor (const node of layoutNodes) {\n  const ratio = (node.weightedDegree - minDegree) / degreeSpan;\n  node.radius = NODE_MIN_R + ratio * (NODE_MAX_R - NODE_MIN_R);\n}\n\nlet lcgState = 42;\nconst nCount = layoutNodes.length;\nconst kForce = Math.sqrt(AREA / nCount);\n\nfor (let i = 0; i < nCount; i += 1) {\n  lcgState = (lcgState * 1664525 + 1013904223) % 4294967296;\n  const rx = (lcgState / 4294967296) * 2 - 1;\n  lcgState = (lcgState * 1664525 + 1013904223) % 4294967296;\n  const ry = (lcgState / 4294967296) * 2 - 1;\n  layoutNodes[i].x = rx;\n  layoutNodes[i].y = ry;\n}\n\nlet temperature = INITIAL_TEMP;\nfor (let iter = 0; iter < ITERATIONS; iter += 1) {\n  const dispX = new Array<number>(nCount).fill(0);\n  const dispY = new Array<number>(nCount).fill(0);\n\n  for (let i = 0; i < nCount; i += 1) {\n    for (let j = i + 1; j < nCount; j += 1) {\n      const dx = layoutNodes[i].x - layoutNodes[j].x;\n      const dy = layoutNodes[i].y - layoutNodes[j].y;\n      const dist = Math.sqrt(dx * dx + dy * dy) || 0.01;\n      const force = (kForce * kForce) / dist;\n      const ux = dx / dist;\n      const uy = dy / dist;\n      dispX[i] += ux * force;\n      dispY[i] += uy * force;\n      dispX[j] -= ux * force;\n      dispY[j] -= uy * force;\n    }\n  }\n\n  for (const edge of edges) {\n    const i = edge.sourceIdx;\n    const j = edge.targetIdx;\n    const dx = layoutNodes[i].x - layoutNodes[j].x;\n    const dy = layoutNodes[i].y - layoutNodes[j].y;\n    const dist = Math.sqrt(dx * dx + dy * dy) || 0.01;\n    const idealDist = kForce * (1.5 - 1.0 * edge.ratio);\n    const force = (dist * dist) / idealDist;\n    const ux = dx / dist;\n    const uy = dy / dist;\n    dispX[i] -= ux * force;\n    dispY[i] -= uy * force;\n    dispX[j] += ux * force;\n    dispY[j] += uy * force;\n  }\n\n  for (let i = 0; i < nCount; i += 1) {\n    const dx = dispX[i];\n    const dy = dispY[i];\n    const dist = Math.sqrt(dx * dx + dy * dy) || 0.01;\n    const limited = Math.min(dist, temperature);\n    layoutNodes[i].x += (dx / dist) * limited;\n    layoutNodes[i].y += (dy / dist) * limited;\n  }\n  temperature *= COOLING_FACTOR;\n}\n\nconst centroidX = layoutNodes.reduce((s, n) => s + n.x, 0) / nCount;\nconst centroidY = layoutNodes.reduce((s, n) => s + n.y, 0) / nCount;\nfor (const node of layoutNodes) {\n  node.x -= centroidX;\n  node.y -= centroidY;\n}\n\nconst rangeX = Math.max(...layoutNodes.map((n) => Math.abs(n.x)));\nconst rangeY = Math.max(...layoutNodes.map((n) => Math.abs(n.y)));\nconst xHalf = rangeX * PAD_MULT;\nconst yHalf = rangeY * PAD_MULT;\n\nconst edgeOpacity = (ratio: number) => 0.22 + ratio * 0.4;\n\nconst sortedEdges = [...edges].sort((a, b) => a.weight - b.weight);\nconst midWeight = Math.round((minWeight + maxWeight) / 2);\nconst weightSamples = [minWeight, midWeight, maxWeight].map((weight) => {\n  const ratio = (weight - minWeight) / weightSpan;\n  return { weight, ratio, strokeWidth: EDGE_MIN_W + ratio * (EDGE_MAX_W - EDGE_MIN_W) };\n});\n\n// Label direction per node: bisector of the widest angular gap between its edges\nfunction labelAngle(nodeIdx: number, px: (n: LabNode) => [number, number]): number {\n  const [cx, cy] = px(layoutNodes[nodeIdx]);\n  const angles = edges\n    .filter((e) => e.sourceIdx === nodeIdx || e.targetIdx === nodeIdx)\n    .map((e) => {\n      const other = layoutNodes[e.sourceIdx === nodeIdx ? e.targetIdx : e.sourceIdx];\n      const [ox, oy] = px(other);\n      return Math.atan2(oy - cy, ox - cx);\n    })\n    .sort((a, b) => a - b);\n  if (angles.length === 0) return -Math.PI / 2;\n  let bestGap = -1;\n  let bestAngle = -Math.PI / 2;\n  angles.forEach((a, i) => {\n    const next = i === angles.length - 1 ? angles[0] + 2 * Math.PI : angles[i + 1];\n    if (next - a > bestGap) {\n      bestGap = next - a;\n      bestAngle = (a + next) / 2;\n    }\n  });\n  return bestAngle;\n}\n\ninterface HoverInfo {\n  label: string;\n  detail: string;\n  x: number;\n  y: number;\n}\n\nfunction WeightedNetworkOverlay({\n  hover,\n  onHoverChange,\n}: {\n  hover: HoverInfo | null;\n  onHoverChange: (info: HoverInfo | null) => void;\n}) {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const drawingArea = useDrawingArea();\n  const toPx = (n: LabNode): [number, number] => [Number(xScale(n.x)), Number(yScale(n.y))];\n\n  return (\n    <g>\n      {sortedEdges.map((edge, i) => {\n        const s = layoutNodes[edge.sourceIdx];\n        const d = layoutNodes[edge.targetIdx];\n        const x1 = Number(xScale(s.x));\n        const y1 = Number(yScale(s.y));\n        const x2 = Number(xScale(d.x));\n        const y2 = Number(yScale(d.y));\n        const tooltip: HoverInfo = {\n          label: `${s.label} ↔ ${d.label}`,\n          detail: `${edge.weight} (${WEIGHT})`,\n          x: (x1 + x2) / 2,\n          y: (y1 + y2) / 2,\n        };\n        return (\n          <g key={`${s.id}-${d.id}-${i}`}>\n            <line\n              x1={x1}\n              y1={y1}\n              x2={x2}\n              y2={y2}\n              stroke={t.ink}\n              strokeOpacity={edgeOpacity(edge.ratio)}\n              strokeWidth={edge.strokeWidth}\n              strokeLinecap=\"round\"\n            />\n            <line\n              x1={x1}\n              y1={y1}\n              x2={x2}\n              y2={y2}\n              stroke=\"transparent\"\n              strokeWidth={Math.max(edge.strokeWidth, 18)}\n              style={{ cursor: \"pointer\" }}\n              onMouseEnter={() => onHoverChange(tooltip)}\n              onMouseLeave={() => onHoverChange(null)}\n            />\n          </g>\n        );\n      })}\n      {layoutNodes.map((node, idx) => {\n        const [cx, cy] = toPx(node);\n        const radius = node.radius;\n        const chipW = node.id.length * 10 + 8;\n        const chipH = 20;\n        const angle = labelAngle(idx, toPx);\n        const cosA = Math.cos(angle);\n        const sinA = Math.sin(angle);\n        const toChipEdge = Math.min(\n          chipW / 2 / Math.max(Math.abs(cosA), 1e-6),\n          chipH / 2 / Math.max(Math.abs(sinA), 1e-6),\n        );\n        const labelX = cx + cosA * (radius + 6 + toChipEdge);\n        const labelY = cy + sinA * (radius + 6 + toChipEdge);\n        const tooltip: HoverInfo = {\n          label: node.label,\n          detail: `${node.domainName} · weighted degree ${node.weightedDegree}`,\n          x: cx,\n          y: cy - radius - 10,\n        };\n        return (\n          <g key={node.id}>\n            <circle\n              cx={cx}\n              cy={cy}\n              r={radius}\n              fill={t.palette[node.domainIndex]}\n              stroke={t.pageBg}\n              strokeWidth={3}\n              style={{ cursor: \"pointer\" }}\n              onMouseEnter={() => onHoverChange(tooltip)}\n              onMouseLeave={() => onHoverChange(null)}\n            />\n            <rect\n              x={labelX - chipW / 2}\n              y={labelY - chipH / 2}\n              width={chipW}\n              height={chipH}\n              rx={4}\n              fill={t.pageBg}\n              fillOpacity={0.86}\n              style={{ pointerEvents: \"none\" }}\n            />\n            <text\n              x={labelX}\n              y={labelY}\n              textAnchor=\"middle\"\n              dominantBaseline=\"central\"\n              fontSize={16}\n              fontWeight={600}\n              fill={t.ink}\n              style={{ pointerEvents: \"none\" }}\n            >\n              {node.id}\n            </text>\n          </g>\n        );\n      })}\n\n      {hover && (\n        <g style={{ pointerEvents: \"none\" }}>\n          <rect\n            x={Math.min(\n              Math.max(\n                hover.x - (Math.max(hover.label.length, hover.detail.length) * 8 + 24) / 2,\n                8,\n              ),\n              drawingArea.left +\n                drawingArea.width -\n                (Math.max(hover.label.length, hover.detail.length) * 8 + 24) -\n                8,\n            )}\n            y={Math.max(hover.y - 52 - 12, 8)}\n            width={Math.max(hover.label.length, hover.detail.length) * 8 + 24}\n            height={52}\n            rx={6}\n            fill={t.elevatedBg}\n            stroke={t.inkSoft}\n            strokeOpacity={0.4}\n          />\n          <text\n            x={hover.x}\n            y={Math.max(hover.y - 52 - 12, 8) + 21}\n            textAnchor=\"middle\"\n            fontSize={14}\n            fontWeight={600}\n            fill={t.ink}\n          >\n            {hover.label}\n          </text>\n          <text\n            x={hover.x}\n            y={Math.max(hover.y - 52 - 12, 8) + 40}\n            textAnchor=\"middle\"\n            fontSize={14}\n            fill={t.inkSoft}\n          >\n            {hover.detail}\n          </text>\n        </g>\n      )}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const [hover, setHover] = useState<HoverInfo | null>(null);\n  const chartHeight = height - TITLE_H - LEGEND_H;\n\n  return (\n    <div\n      style={{\n        width,\n        height,\n        backgroundColor: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n        fontFamily: \"Inter, system-ui, sans-serif\",\n      }}\n    >\n      <div\n        style={{\n          height: TITLE_H,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n        }}\n      >\n        <span style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>{TITLE}</span>\n      </div>\n      <ChartsContainer\n        width={width}\n        height={chartHeight}\n        margin={{ top: 28, right: 60, bottom: 28, left: 60 }}\n        series={[]}\n        skipAnimation\n        disableAxisListener\n        xAxis={[{ scaleType: \"linear\", min: -xHalf, max: xHalf, position: \"none\" }]}\n        yAxis={[{ scaleType: \"linear\", min: -yHalf, max: yHalf, position: \"none\" }]}\n      >\n        <WeightedNetworkOverlay hover={hover} onHoverChange={setHover} />\n      </ChartsContainer>\n      <div\n        style={{\n          minHeight: LEGEND_H,\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 12,\n          padding: \"8px 40px 14px\",\n          boxSizing: \"border-box\",\n        }}\n      >\n        <div\n          style={{\n            display: \"flex\",\n            flexWrap: \"wrap\",\n            alignItems: \"center\",\n            justifyContent: \"center\",\n            gap: 28,\n          }}\n        >\n          {domains.map((name, i) => (\n            <span\n              key={name}\n              style={{\n                display: \"inline-flex\",\n                alignItems: \"center\",\n                gap: 8,\n                fontSize: 15,\n                color: t.inkSoft,\n              }}\n            >\n              <span\n                style={{\n                  width: 14,\n                  height: 14,\n                  borderRadius: \"50%\",\n                  backgroundColor: t.palette[i],\n                  display: \"inline-block\",\n                }}\n              />\n              <span>{name}</span>\n            </span>\n          ))}\n        </div>\n        <div\n          style={{\n            display: \"flex\",\n            flexWrap: \"wrap\",\n            alignItems: \"center\",\n            justifyContent: \"center\",\n            gap: 24,\n            fontSize: 14,\n            color: t.inkSoft,\n          }}\n        >\n          <span>{`Edge width = ${WEIGHT} · node size = weighted degree:`}</span>\n          {weightSamples.map((sample) => (\n            <span\n              key={sample.weight}\n              style={{ display: \"inline-flex\", alignItems: \"center\", gap: 8 }}\n            >\n              <svg width={52} height={16}>\n                <line\n                  x1={4}\n                  y1={8}\n                  x2={48}\n                  y2={8}\n                  stroke={t.ink}\n                  strokeOpacity={edgeOpacity(sample.ratio)}\n                  strokeWidth={sample.strokeWidth}\n                  strokeLinecap=\"round\"\n                />\n              </svg>\n              <span>{sample.weight}</span>\n            </span>\n          ))}\n        </div>\n      </div>\n    </div>\n  );\n}\n"}