{"spec_id":"skewt-logp-atmospheric","library":"muix","language":"javascript","code":"// anyplot.ai\n// skewt-logp-atmospheric: Skew-T Log-P Atmospheric Diagram\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 89/100 | Updated: 2026-11-08\n//# anyplot-orientation: square\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsClipPath } from \"@mui/x-charts/ChartsClipPath\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst KAPPA = 0.286; // Rd / cp, dry adiabatic exponent\nconst R_D = 287; // J / (kg K), gas constant of dry air\nconst C_P = 1004; // J / (kg K), specific heat of dry air at constant pressure\nconst L_V = 2.5e6; // J / kg, latent heat of vaporization\nconst EPSILON = 0.622; // Rd / Rv\nconst FREEZING_C = 0; // isotherm drawn heavier\nconst MANDATORY_LEVELS = [1000, 850, 700, 500, 400, 300, 250, 200, 150, 100]; // hPa, pressure ticks\nconst ISOTHERM_STEP = 10; // °C\nconst DRY_ADIABAT_STEP = 10; // °C of potential temperature\nconst MOIST_ADIABAT_STEP = 5; // °C at the bottom level\nconst MIXING_RATIOS = [0.4, 1, 2, 3, 5, 8, 12, 16, 20]; // g/kg\nconst MIXING_RATIO_TOP = 400; // hPa, mixing-ratio lines stop here by convention\nconst CURVE_STEP_HPA = 5; // integration and sampling step of the reference curves\nconst X_PAD_SHARE = 0.04; // window padding as a share of the window width\n\n// Columns: set these to your data's column names\nconst PRESSURE = \"Pressure (hPa)\"; // role: pressure\nconst TEMPERATURE = \"Temperature (°C)\"; // role: temperature\nconst DEWPOINT = \"Dewpoint (°C)\"; // role: dewpoint\n\n// Data: replace this block with your own records, one object per row\n// Warm-season radiosonde sounding every 25 hPa: standard lapse rate to an 11 km tropopause,\n// air drying with height and a moist layer near 400 hPa.\nconst data: Record<string, number>[] = [];\nfor (let p = 1000; p >= 100; p -= 25) {\n  const heightM = 44330 * (1 - Math.pow(p / 1000, 1 / 5.255));\n  const temp = heightM <= 11000 ? 22 - 6.5 * (heightM / 1000) : 22 - 6.5 * 11 + 0.6 * ((heightM - 11000) / 1000);\n  const rh = Math.min(0.95, 0.15 + 0.55 * Math.max(0, (p - 100) / 900) + 0.35 * Math.exp(-(((p - 400) / 60) ** 2)));\n  const logRatio = Math.log((rh * 6.112 * Math.exp((17.67 * temp) / (temp + 243.5))) / 6.112);\n  data.push({\n    [PRESSURE]: p,\n    [TEMPERATURE]: Number(temp.toFixed(1)),\n    [DEWPOINT]: Number(((243.5 * logRatio) / (17.67 - logRatio)).toFixed(1)),\n  });\n}\n\n// Plot: reads only data and the constants above\nconst { width: W, height: H } = window.ANYPLOT_SIZE;\nconst levels = [...data].sort((a, b) => b[PRESSURE] - a[PRESSURE]);\nconst pBottom = levels[0][PRESSURE];\nconst pTop = levels[levels.length - 1][PRESSURE];\nconst logSpan = Math.log(pBottom / pTop);\n\n// Layout: the drawing area's aspect sets how far a 45° isotherm shifts per unit of log-pressure\nconst HEADER_H = 84;\nconst LEGEND_H = 48;\nconst MARGIN = { top: 16, right: 32, bottom: 8, left: 16 };\nconst X_AXIS_H = 64;\nconst Y_AXIS_W = 72;\nconst chartH = H - HEADER_H - LEGEND_H;\nconst aspect = (chartH - MARGIN.top - MARGIN.bottom - X_AXIS_H) / (W - MARGIN.left - MARGIN.right - Y_AXIS_W);\n\n// Temperature window at the bottom level: the smallest span that holds every skewed\n// level with padding (a fixed point, since the skew itself scales with the span)\nconst heightShare = levels.map((d) => Math.log(pBottom / d[PRESSURE]) / logSpan);\nlet span = Math.max(...levels.map((d) => d[TEMPERATURE])) - Math.min(...levels.map((d) => d[DEWPOINT]));\nlet skewedMin = 0;\nfor (let k = 0; k < 40; k += 1) {\n  const skewed = levels.flatMap((d, i) => [d[TEMPERATURE], d[DEWPOINT]].map((v) => v + heightShare[i] * aspect * span));\n  skewedMin = Math.min(...skewed);\n  span = (Math.max(...skewed) - skewedMin) / (1 - 2 * X_PAD_SHARE);\n}\nconst xMin = skewedMin - X_PAD_SHARE * span;\nconst xMax = xMin + span;\nconst topShift = aspect * span; // °C an isotherm moves right between the bottom and the top\n\n// Reference families as (temperature, pressure) polylines, covering the window\nconst pressureGrid: number[] = [];\nfor (let p = pBottom; p >= pTop; p -= CURVE_STEP_HPA) pressureGrid.push(p);\nconst isotherms: number[] = [];\nfor (let tc = Math.ceil((xMin - topShift) / ISOTHERM_STEP) * ISOTHERM_STEP; tc <= xMax; tc += ISOTHERM_STEP) {\n  isotherms.push(tc);\n}\nconst thetaMax = (xMax - topShift + 273.15) / Math.pow(pTop / pBottom, KAPPA) - 273.15;\nconst dryAdiabats: { t: number; p: number }[][] = [];\nfor (let th = Math.ceil(xMin / DRY_ADIABAT_STEP) * DRY_ADIABAT_STEP; th <= thetaMax; th += DRY_ADIABAT_STEP) {\n  dryAdiabats.push(pressureGrid.map((p) => ({ t: (th + 273.15) * Math.pow(p / pBottom, KAPPA) - 273.15, p })));\n}\nconst moistAdiabats: { t: number; p: number }[][] = [];\nfor (let t0 = Math.ceil(xMin / MOIST_ADIABAT_STEP) * MOIST_ADIABAT_STEP; t0 <= xMax; t0 += MOIST_ADIABAT_STEP) {\n  let temp = t0;\n  const curve = [{ t: temp, p: pBottom }];\n  for (let p = pBottom; p - CURVE_STEP_HPA >= pTop; p -= CURVE_STEP_HPA) {\n    const es = 6.112 * Math.exp((17.67 * temp) / (temp + 243.5));\n    const ws = (EPSILON * es) / (p - es);\n    const tk = temp + 273.15;\n    const dTdP = ((tk / p) * (R_D / C_P) * (1 + (L_V * ws) / (R_D * tk))) / (1 + (L_V * L_V * ws * EPSILON) / (C_P * R_D * tk * tk));\n    temp -= dTdP * CURVE_STEP_HPA;\n    curve.push({ t: temp, p: p - CURVE_STEP_HPA });\n  }\n  moistAdiabats.push(curve);\n}\nconst mixingLines = MIXING_RATIOS.map((w) =>\n  pressureGrid\n    .filter((p) => p >= MIXING_RATIO_TOP)\n    .map((p) => {\n      const logRatio = Math.log(((w / 1000) * p) / (EPSILON + w / 1000) / 6.112);\n      return { t: (243.5 * logRatio) / (17.67 - logRatio), p };\n    }),\n);\nconst tempProfile = levels.map((d) => ({ t: d[TEMPERATURE], p: d[PRESSURE] }));\nconst dewProfile = levels.map((d) => ({ t: d[DEWPOINT], p: d[PRESSURE] }));\nconst tempColor = t.palette[0];\nconst dewColor = t.palette[2]; // moisture in blue\n\nconst title = \"skewt-logp-atmospheric · javascript · muix · anyplot.ai\";\nconst subtitle = `${levels.length} levels · ${PRESSURE} ${pBottom} to ${pTop} · bottom level: ${TEMPERATURE} ${levels[0][TEMPERATURE]}, ${DEWPOINT} ${levels[0][DEWPOINT]}`;\nconst legendItems = [\n  { label: TEMPERATURE.replace(/ \\(.*\\)$/, \"\"), color: tempColor, width: 3.5, dash: \"\" },\n  { label: DEWPOINT.replace(/ \\(.*\\)$/, \"\"), color: dewColor, width: 3, dash: \"10 6\" },\n  { label: \"Isotherm\", color: t.inkSoft, width: 1.5, dash: \"\", opacity: 0.5 },\n  { label: \"Dry adiabat\", color: t.inkSoft, width: 1.5, dash: \"6 4\" },\n  { label: \"Moist adiabat\", color: t.inkSoft, width: 1.75, dash: \"1.5 4\" },\n  { label: \"Mixing ratio\", color: t.inkSoft, width: 1.5, dash: \"3 2 1 2\" },\n];\n\nfunction SkewTLayer() {\n  const xScale = useXScale(\"temperature\") as (v: number) => number;\n  const yScale = useYScale(\"pressure\") as (v: number) => number;\n  const pxPerDeg = xScale(1) - xScale(0);\n  const toPath = (pts: { t: number; p: number }[]) =>\n    pts\n      .map((pt, i) => `${i === 0 ? \"M\" : \"L\"}${xScale(pt.t + (yScale(pBottom) - yScale(pt.p)) / pxPerDeg)},${yScale(pt.p)}`)\n      .join(\" \");\n  return (\n    <>\n      <ChartsClipPath id=\"skewt-clip\" />\n      <g clipPath=\"url(#skewt-clip)\">\n        {isotherms.map((tc) => (\n          <path\n            key={`iso-${tc}`}\n            d={toPath([{ t: tc, p: pBottom }, { t: tc, p: pTop }])}\n            stroke={t.inkSoft}\n            strokeOpacity={tc === FREEZING_C ? 0.6 : 0.35}\n            strokeWidth={tc === FREEZING_C ? 2 : 1.25}\n          />\n        ))}\n        {dryAdiabats.map((c, i) => (\n          <path key={`dry-${i}`} d={toPath(c)} fill=\"none\" stroke={t.inkSoft} strokeWidth={1.25} strokeDasharray=\"6 4\" opacity={0.55} />\n        ))}\n        {moistAdiabats.map((c, i) => (\n          <path key={`moist-${i}`} d={toPath(c)} fill=\"none\" stroke={t.inkSoft} strokeWidth={1.75} strokeDasharray=\"1.5 4\" strokeLinecap=\"round\" opacity={0.75} />\n        ))}\n        {mixingLines.map((c, i) => (\n          <path key={`mix-${i}`} d={toPath(c)} fill=\"none\" stroke={t.inkSoft} strokeWidth={1.25} strokeDasharray=\"3 2 1 2\" opacity={0.5} />\n        ))}\n        <path d={toPath(dewProfile)} fill=\"none\" stroke={dewColor} strokeWidth={3} strokeDasharray=\"10 6\" />\n        <path d={toPath(tempProfile)} fill=\"none\" stroke={tempColor} strokeWidth={3.5} />\n      </g>\n      {/* Level markers stay unclipped: the window holds every skewed level, and the top and bottom levels sit on the edges */}\n      {levels.map((d) => {\n        const skew = (yScale(pBottom) - yScale(d[PRESSURE])) / pxPerDeg;\n        return (\n          <g key={`level-${d[PRESSURE]}`}>\n            <circle cx={xScale(d[DEWPOINT] + skew)} cy={yScale(d[PRESSURE])} r={3.5} fill={dewColor} stroke={t.pageBg} strokeWidth={1} />\n            <circle cx={xScale(d[TEMPERATURE] + skew)} cy={yScale(d[PRESSURE])} r={3.5} fill={tempColor} stroke={t.pageBg} strokeWidth={1} />\n          </g>\n        );\n      })}\n    </>\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={MARGIN}\n        series={[]}\n        skipAnimation\n        xAxis={[\n          {\n            id: \"temperature\",\n            scaleType: \"linear\",\n            min: xMin,\n            max: xMax,\n            label: `${TEMPERATURE}, isotherms skewed 45°`,\n            height: X_AXIS_H,\n            tickNumber: 8,\n            valueFormatter: (v: number) => v.toFixed(0),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n            sx: { \"& .MuiChartsAxis-line, & .MuiChartsAxis-tick\": { stroke: t.inkSoft } },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"pressure\",\n            scaleType: \"log\",\n            reverse: true,\n            min: pTop,\n            max: pBottom,\n            label: PRESSURE,\n            width: Y_AXIS_W,\n            tickInterval: MANDATORY_LEVELS.filter((p) => p >= pTop && p <= pBottom),\n            valueFormatter: (v: number) => `${v}`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n            sx: { \"& .MuiChartsAxis-line, & .MuiChartsAxis-tick\": { stroke: t.inkSoft } },\n          },\n        ]}\n      >\n        <ChartsGrid horizontal />\n        <SkewTLayer />\n        <ChartsXAxis axisId=\"temperature\" />\n        <ChartsYAxis axisId=\"pressure\" />\n      </ChartsContainer>\n      <div\n        style={{\n          height: LEGEND_H,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 24,\n          fontSize: 16,\n          color: t.ink,\n        }}\n      >\n        {legendItems.map((item) => (\n          <span key={item.label} style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <svg width={34} height={10}>\n              <line\n                x1={1}\n                y1={5}\n                x2={33}\n                y2={5}\n                stroke={item.color}\n                strokeWidth={item.width}\n                strokeDasharray={item.dash || undefined}\n                strokeOpacity={item.opacity ?? 1}\n              />\n            </svg>\n            {item.label}\n          </span>\n        ))}\n      </div>\n    </div>\n  );\n}\n"}