{"spec_id":"smith-chart-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// smith-chart-basic: Smith Chart for RF/Impedance\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\n//# anyplot-orientation: square\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst Z0 = 50; // reference impedance for normalization, ohms (the spec's default)\nconst RESISTANCE_CIRCLES = [0.2, 0.5, 1, 2, 5]; // normalized r of the standard grid\nconst REACTANCE_ARCS = [0.2, 0.5, 1, 2, 5]; // normalized |x| of the standard grid\nconst GAMMA_LIMIT = 1.15; // the unit disk plus room for the reactance labels\nconst LABEL_COUNT = 6; // frequency labels spread evenly along the sweep\nconst LABEL_FONT_PX = 15;\nconst GRID_FONT_PX = 14;\nconst GLYPH_EM = 0.62; // average glyph width in em, to size a label's box before it is drawn\nconst LABEL_GAP_PX = 14; // nearest distance from a labelled point to its label box\nconst LABEL_GAP_MAX_PX = 90; // farthest the search steps out along the normal\nconst LABEL_STEP_PX = 4;\nconst LABEL_CLEAR_PX = 13; // room a label box keeps from the locus, the rim and other labels\nconst LABEL_SAMPLE_PX = 3; // spacing of the points the clearance is measured against\n\n// Columns: set these to your data's column names\nconst FREQUENCY = \"Frequency (GHz)\"; // role: frequency\nconst RESISTANCE = \"Resistance (Ω)\"; // role: z_real\nconst REACTANCE = \"Reactance (Ω)\"; // role: z_imag\n\n// Data: replace this block with your own records, one object per row\n// Antenna feed impedance swept 1-6 GHz: a series R-L-C model whose radiation resistance\n// rises gently with frequency while the reactance swings through resonance.\nconst data: Record<string, number>[] = [];\nfor (let i = 0; i <= 40; i += 1) {\n  const fGHz = 1 + i * 0.125;\n  const omega = 2 * Math.PI * fGHz * 1e9;\n  data.push({\n    [FREQUENCY]: fGHz,\n    [RESISTANCE]: Number((35 + 3 * (fGHz - 1)).toFixed(2)),\n    [REACTANCE]: Number((omega * 5e-9 - 1 / (omega * 0.4e-12)).toFixed(2)),\n  });\n}\n\n// Plot: reads only data and the constants above\nconst { width: W, height: H } = window.ANYPLOT_SIZE;\nconst sweep = [...data].sort((a, b) => a[FREQUENCY] - b[FREQUENCY]);\n\n// Γ = (z - 1) / (z + 1) with z = (R + jX) / Z0\nconst locus = sweep.map((d) => {\n  const zr = d[RESISTANCE] / Z0;\n  const zi = d[REACTANCE] / Z0;\n  const den = (zr + 1) ** 2 + zi ** 2;\n  return { f: d[FREQUENCY], re: (zr * zr + zi * zi - 1) / den, im: (2 * zi) / den };\n});\nconst labelIdx = [...new Set(Array.from({ length: LABEL_COUNT }, (_, k) => Math.round((k * (locus.length - 1)) / (LABEL_COUNT - 1))))];\nconst freqUnit = FREQUENCY.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\nconst impedanceUnit = RESISTANCE.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\n\n// Grid: constant-reactance arcs run from the open-circuit point (1, 0) to Γ(jx) on the boundary\nconst arcs = REACTANCE_ARCS.flatMap((x) => [x, -x]).map((x) => ({\n  x,\n  radius: 1 / Math.abs(x),\n  endRe: (x * x - 1) / (x * x + 1),\n  endIm: (2 * x) / (x * x + 1),\n}));\n\n// Layout: a square drawing area, so one unit of Γ is the same length on both axes\nconst HEADER_H = 84;\nconst V_MARGIN = 30;\nconst chartH = H - HEADER_H;\nconst side = Math.min(W, chartH) - 2 * V_MARGIN;\nconst hMargin = (W - side) / 2;\nconst vMargin = (chartH - side) / 2;\n\nconst title = \"smith-chart-basic · javascript · muix · anyplot.ai\";\nconst subtitle = `n = ${sweep.length} points · ${FREQUENCY} ${sweep[0][FREQUENCY]} to ${sweep[sweep.length - 1][FREQUENCY]} · impedance normalized to Z₀ = ${Z0} ${impedanceUnit}, matched point at the centre`;\n\nfunction SmithChart() {\n  const xScale = useXScale() as (v: number) => number;\n  const yScale = useYScale() as (v: number) => number;\n  const unit = xScale(1) - xScale(0);\n  const cx = xScale(0);\n  const cy = yScale(0);\n  const grid = { fill: \"none\", stroke: t.inkSoft, strokeWidth: 1, opacity: 0.55 };\n  const pts = locus.map((p) => [xScale(p.re), yScale(p.im)]);\n  const locusPath = pts.map(([x, y], i) => `${i === 0 ? \"M\" : \"L\"}${x},${y}`).join(\" \");\n  const rLabels = RESISTANCE_CIRCLES.map((r) => ({ r, x: xScale((r - 1) / (r + 1)) - 4, y: cy + 18 }));\n  const xLabels = arcs.map((a) => ({\n    x: a.x,\n    text: `${a.x > 0 ? \"+\" : \"−\"}j${Math.abs(a.x)}`,\n    px: xScale(a.endRe * 1.07),\n    py: yScale(a.endIm * 1.07),\n  }));\n\n  // The locus and the rim as points a few px apart, to measure the room a label box keeps from them\n  const rimSamples = Math.ceil((2 * Math.PI * unit) / LABEL_SAMPLE_PX);\n  const obstacles = [\n    ...pts.flatMap(([x0, y0], i) => {\n      const [x1, y1] = pts[Math.min(i + 1, pts.length - 1)];\n      const steps = Math.max(1, Math.ceil(Math.hypot(x1 - x0, y1 - y0) / LABEL_SAMPLE_PX));\n      return Array.from({ length: steps }, (_, s) => [x0 + ((x1 - x0) * s) / steps, y0 + ((y1 - y0) * s) / steps]);\n    }),\n    ...Array.from({ length: rimSamples }, (_, k) => [\n      cx + unit * Math.cos((2 * Math.PI * k) / rimSamples),\n      cy + unit * Math.sin((2 * Math.PI * k) / rimSamples),\n    ]),\n  ];\n  // Text boxes already on the chart: the grid values, then each frequency label as it is placed\n  const gridHalfH = GRID_FONT_PX * 0.6;\n  const boxes = [\n    ...rLabels.map((l) => {\n      const hw = (`${l.r}`.length * GRID_FONT_PX * GLYPH_EM) / 2;\n      return { x: l.x - hw, y: l.y - GRID_FONT_PX * 0.35, hw, hh: gridHalfH };\n    }),\n    ...xLabels.map((l) => ({ x: l.px, y: l.py, hw: (l.text.length * GRID_FONT_PX * GLYPH_EM) / 2, hh: gridHalfH })),\n  ];\n  // Each frequency label sits on the locus normal at its point, on the side and at the smallest\n  // distance that keep its box clear of the curve, the rim and every other label\n  const freqLabels = labelIdx.map((i) => {\n    const [px, py] = pts[i];\n    const [ax, ay] = pts[Math.max(0, i - 1)];\n    const [bx, by] = pts[Math.min(pts.length - 1, i + 1)];\n    const len = Math.hypot(bx - ax, by - ay) || 1;\n    const text = `${locus[i].f} ${freqUnit}`;\n    const hw = (text.length * LABEL_FONT_PX * GLYPH_EM) / 2;\n    const hh = LABEL_FONT_PX * 0.6;\n    let best = { x: px, y: py, room: -Infinity };\n    for (let gap = LABEL_GAP_PX; gap <= LABEL_GAP_MAX_PX && best.room < LABEL_CLEAR_PX; gap += LABEL_STEP_PX) {\n      for (const side of [1, -1]) {\n        const nx = (-(by - ay) / len) * side;\n        const ny = ((bx - ax) / len) * side;\n        const reach = gap + Math.abs(nx) * hw + Math.abs(ny) * hh;\n        const x = px + nx * reach;\n        const y = py + ny * reach;\n        const room = Math.min(\n          ...obstacles.map(([qx, qy]) => Math.hypot(Math.max(Math.abs(qx - x) - hw, 0), Math.max(Math.abs(qy - y) - hh, 0))),\n          ...boxes.map((b) => Math.max(Math.abs(b.x - x) - b.hw - hw, Math.abs(b.y - y) - b.hh - hh)),\n        );\n        if (room > best.room) best = { x, y, room };\n      }\n    }\n    boxes.push({ x: best.x, y: best.y, hw, hh });\n    return { f: locus[i].f, px, py, text, x: best.x, y: best.y };\n  });\n  return (\n    <g>\n      <line x1={xScale(-1)} y1={cy} x2={xScale(1)} y2={cy} stroke={t.inkSoft} strokeWidth={1.5} />\n      {RESISTANCE_CIRCLES.map((r) => (\n        <circle key={`r-${r}`} cx={xScale(r / (1 + r))} cy={cy} r={unit / (1 + r)} {...grid} />\n      ))}\n      {arcs.map((a) => (\n        <path\n          key={`x-${a.x}`}\n          d={`M ${xScale(1)} ${cy} A ${a.radius * unit} ${a.radius * unit} 0 0 ${a.x > 0 ? 1 : 0} ${xScale(a.endRe)} ${yScale(a.endIm)}`}\n          {...grid}\n        />\n      ))}\n      <circle cx={cx} cy={cy} r={unit} fill=\"none\" stroke={t.ink} strokeWidth={2.5} />\n      {rLabels.map((l) => (\n        <text key={`rl-${l.r}`} x={l.x} y={l.y} textAnchor=\"end\" fontSize={GRID_FONT_PX} fill={t.inkSoft}>\n          {l.r}\n        </text>\n      ))}\n      {xLabels.map((l) => (\n        <text\n          key={`xl-${l.x}`}\n          x={l.px}\n          y={l.py}\n          textAnchor=\"middle\"\n          dominantBaseline=\"central\"\n          fontSize={GRID_FONT_PX}\n          fill={t.inkSoft}\n        >\n          {l.text}\n        </text>\n      ))}\n      <circle cx={cx} cy={cy} r={5} fill=\"none\" stroke={t.ink} strokeWidth={2} />\n      <path d={locusPath} fill=\"none\" stroke={t.palette[0]} strokeWidth={3.5} strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n      {freqLabels.map((l) => (\n        <g key={`f-${l.f}`}>\n          <circle cx={l.px} cy={l.py} r={8} fill={t.palette[0]} stroke={t.pageBg} strokeWidth={2.5} />\n          <text\n            x={l.x}\n            y={l.y}\n            textAnchor=\"middle\"\n            dominantBaseline=\"central\"\n            fontSize={LABEL_FONT_PX}\n            fontWeight={600}\n            fill={t.ink}\n            paintOrder=\"stroke\"\n            stroke={t.pageBg}\n            strokeWidth={4}\n            strokeLinejoin=\"round\"\n          >\n            {l.text}\n          </text>\n        </g>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <div style={{ width: W, height: H, 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: 6,\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      <ChartsContainer\n        width={W}\n        height={chartH}\n        margin={{ top: vMargin, bottom: vMargin, left: hMargin, right: hMargin }}\n        series={[]}\n        skipAnimation\n        xAxis={[{ scaleType: \"linear\", min: -GAMMA_LIMIT, max: GAMMA_LIMIT, position: \"none\" }]}\n        yAxis={[{ scaleType: \"linear\", min: -GAMMA_LIMIT, max: GAMMA_LIMIT, position: \"none\" }]}\n      >\n        <SmithChart />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}