{"spec_id":"phase-diagram","library":"muix","language":"javascript","code":"// anyplot.ai\n// phase-diagram: Phase Diagram (State Space Plot)\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 88/100 | Updated: 2026-10-23\n\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\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 { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsText } from \"@mui/x-charts/ChartsText\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Columns: set these to your data's column names\nconst X = \"Position x (m)\"; // role: x\nconst DX_DT = \"Velocity dx/dt (m/s)\"; // role: dx_dt\nconst TIME = \"Time t\"; // role: t\nconst TRAJECTORY = \"Trajectory\"; // role: extra\n\n// Data: replace this block with your own records, one object per row\nconst data = (() => {\n  const omega = 1; // natural frequency, rad/s\n  const zeta = 0.15; // damping ratio (< 1 -> underdamped, spirals to the origin)\n  const omegaD = omega * Math.sqrt(1 - zeta * zeta);\n  const steps = 360;\n  const tMax = (4.5 * 2 * Math.PI) / omegaD;\n  const initials = [\n    [2.2, 0],\n    [-2.0, 0.6],\n    [0, 2.6],\n    [1.3, -2.0],\n  ];\n\n  const rows: {\n    [TRAJECTORY]: string;\n    [TIME]: number;\n    [X]: number;\n    [DX_DT]: number;\n  }[] = [];\n\n  for (const [x0, v0] of initials) {\n    const label = `x₀=${x0}, v₀=${v0}`;\n    const A = x0;\n    const B = (v0 + zeta * omega * A) / omegaD;\n    for (let i = 0; i <= steps; i++) {\n      const time = (i / steps) * tMax;\n      const decay = Math.exp(-zeta * omega * time);\n      const cosTerm = Math.cos(omegaD * time);\n      const sinTerm = Math.sin(omegaD * time);\n      const xVal = decay * (A * cosTerm + B * sinTerm);\n      const vVal =\n        decay *\n        (-zeta * omega * (A * cosTerm + B * sinTerm) +\n          omegaD * (-A * sinTerm + B * cosTerm));\n      rows.push({\n        [TRAJECTORY]: label,\n        [TIME]: time,\n        [X]: xVal,\n        [DX_DT]: vVal,\n      });\n    }\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst trajectoryLabels = Array.from(new Set(data.map((d) => d[TRAJECTORY])));\nconst trajectories = trajectoryLabels.map((label, i) => {\n  // Time order, not row order, decides the path and the direction arrows.\n  const pts = data\n    .filter((d) => d[TRAJECTORY] === label)\n    .sort((a, b) => a[TIME] - b[TIME]);\n  return {\n    axisId: `x-axis-${i}`,\n    color: t.palette[i],\n    label,\n    x: pts.map((d) => d[X]),\n    v: pts.map((d) => d[DX_DT]),\n  };\n});\n\nconst allX = data.map((d) => d[X]);\nconst allV = data.map((d) => d[DX_DT]);\nconst xSpan = Math.max(...allX) - Math.min(...allX);\nconst vSpan = Math.max(...allV) - Math.min(...allV);\nconst X_MIN = Math.min(...allX) - xSpan * 0.12;\nconst X_MAX = Math.max(...allX) + xSpan * 0.12;\nconst V_MIN = Math.min(...allV) - vSpan * 0.12;\nconst V_MAX = Math.max(...allV) + vSpan * 0.12;\n\nconst TITLE =\n  \"Damped Oscillator · phase-diagram · javascript · muix · anyplot.ai\";\nconst TITLE_HEIGHT = 70;\nconst TITLE_FONT_SIZE = Math.max(\n  15,\n  Math.round(22 * Math.min(1, 67 / TITLE.length)),\n);\n\nconst MARGIN = { top: 30, bottom: 20, left: 46, right: 60 };\n\nconst ARROW_FRACTIONS = [0.08, 0.24, 0.44, 0.68];\nconst ARROW_TANGENT_STEP = 2;\nconst ARROW_SIZE = 9;\nconst ARROW_SPREAD = 0.5;\n\n// Equilibrium label sits in the empty upper-left corner, joined by a leader line\nconst LABEL_TEXT = \"Equilibrium (0, 0)\";\nconst LABEL_X = X_MIN + (X_MAX - X_MIN) * 0.08;\nconst LABEL_V = V_MAX - (V_MAX - V_MIN) * 0.08;\n\nfunction PhaseMarkers() {\n  const yScale = useYScale();\n  const xScale = useXScale(trajectories[0].axisId);\n\n  const origin = { x: xScale(0)!, y: yScale(0)! };\n  const label = { x: xScale(LABEL_X)!, y: yScale(LABEL_V)! };\n  const leadAngle = Math.atan2(label.y - origin.y, label.x - origin.x);\n\n  return (\n    <g>\n      {trajectories.map((traj) => {\n        const maxIdx = traj.x.length - 1;\n        const start = { x: xScale(traj.x[0])!, y: yScale(traj.v[0])! };\n        return (\n          <g key={traj.axisId}>\n            {ARROW_FRACTIONS.map((frac) => {\n              const idx = Math.min(\n                maxIdx - ARROW_TANGENT_STEP,\n                Math.round(frac * maxIdx),\n              );\n              const p0 = { x: xScale(traj.x[idx])!, y: yScale(traj.v[idx])! };\n              const p1 = {\n                x: xScale(traj.x[idx + ARROW_TANGENT_STEP])!,\n                y: yScale(traj.v[idx + ARROW_TANGENT_STEP])!,\n              };\n              const angle = Math.atan2(p1.y - p0.y, p1.x - p0.x);\n              const points = [0, Math.PI - ARROW_SPREAD, Math.PI + ARROW_SPREAD]\n                .map(\n                  (a) =>\n                    `${p0.x + Math.cos(angle + a) * ARROW_SIZE},${p0.y + Math.sin(angle + a) * ARROW_SIZE}`,\n                )\n                .join(\" \");\n              return (\n                <polygon\n                  key={`${traj.axisId}-arrow-${frac}`}\n                  points={points}\n                  fill={traj.color}\n                  stroke={t.pageBg}\n                  strokeWidth={1}\n                />\n              );\n            })}\n            <circle\n              cx={start.x}\n              cy={start.y}\n              r={10}\n              fill={traj.color}\n              stroke={t.pageBg}\n              strokeWidth={2.5}\n            />\n          </g>\n        );\n      })}\n      <line\n        x1={origin.x + Math.cos(leadAngle) * 18}\n        y1={origin.y + Math.sin(leadAngle) * 18}\n        x2={label.x}\n        y2={label.y + 14}\n        stroke={t.inkSoft}\n        strokeWidth={1.5}\n        strokeDasharray=\"5 4\"\n      />\n      <circle\n        cx={origin.x}\n        cy={origin.y}\n        r={13}\n        fill={t.ink}\n        stroke={t.pageBg}\n        strokeWidth={3}\n      />\n      <ChartsText\n        x={label.x}\n        y={label.y}\n        text={LABEL_TEXT}\n        style={{\n          fontSize: 16,\n          fill: t.ink,\n          fontWeight: 500,\n          dominantBaseline: \"central\",\n        }}\n      />\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <div\n      style={{\n        width: window.ANYPLOT_SIZE.width,\n        height: window.ANYPLOT_SIZE.height,\n        backgroundColor: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n      }}\n    >\n      <div\n        style={{\n          height: TITLE_HEIGHT,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          fontSize: TITLE_FONT_SIZE,\n          fontWeight: 500,\n          color: t.ink,\n        }}\n      >\n        {TITLE}\n      </div>\n      <ChartsDataProvider\n        width={window.ANYPLOT_SIZE.width}\n        height={window.ANYPLOT_SIZE.height - TITLE_HEIGHT}\n        margin={MARGIN}\n        skipAnimation\n        xAxis={trajectories.map((traj, i) => ({\n          id: traj.axisId,\n          scaleType: \"linear\",\n          data: traj.x,\n          min: X_MIN,\n          max: X_MAX,\n          position: i === 0 ? \"bottom\" : \"none\",\n          height: i === 0 ? 68 : 0,\n          label: i === 0 ? X : undefined,\n          labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n          tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n        }))}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: V_MIN,\n            max: V_MAX,\n            width: 84,\n            label: DX_DT,\n            labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        series={trajectories.map((traj) => ({\n          type: \"line\",\n          data: traj.v,\n          xAxisId: traj.axisId,\n          color: traj.color,\n          label: traj.label,\n          curve: \"linear\",\n          showMark: false,\n        }))}\n      >\n        <ChartsWrapper\n          legendPosition={{ vertical: \"bottom\", horizontal: \"center\" }}\n          legendDirection=\"horizontal\"\n          sx={{ width: \"100%\", height: \"100%\" }}\n        >\n          <ChartsSurface\n            sx={{\n              \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n              \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n              \"& .MuiChartsGrid-line\": { stroke: t.grid },\n            }}\n          >\n            <ChartsGrid horizontal vertical />\n            <ChartsReferenceLine\n              axisId={trajectories[0].axisId}\n              x={0}\n              lineStyle={{ stroke: t.grid, strokeWidth: 2 }}\n            />\n            <ChartsReferenceLine\n              y={0}\n              lineStyle={{ stroke: t.grid, strokeWidth: 2 }}\n            />\n            <LinePlot />\n            <PhaseMarkers />\n            <ChartsXAxis axisId={trajectories[0].axisId} />\n            <ChartsYAxis />\n          </ChartsSurface>\n          <ChartsLegend\n            sx={{\n              fontSize: 14,\n              color: t.inkSoft,\n              pb: \"18px\",\n              \"& .MuiChartsLegend-label\": { fontSize: 14, color: t.inkSoft },\n            }}\n          />\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}