/* Evolution of Equations of State - graduate lecture deck
   Build:  node build_deck.js
   Output: /home/claude/eos_lecture/slides/EOS_Evolution_Lecture.pptx            */

const pptxgen = require("pptxgenjs");
const path = require("path");

const FIG = "/home/claude/eos_lecture/figs";
const EQ = "/home/claude/eos_lecture/eqs";
const OUT = "/home/claude/eos_lecture/slides/EOS_Evolution_Lecture.pptx";

// ------------------------------------------------------------------ palette
const INK = "1C242B";
const GRAPHITE = "333F4A";
const SLATE = "66727C";
const MIST = "B9C1C6";
const NAVY = "1F4E79";
const SKY = "5A91BE";
const AMBER = "E29A2D";
const AMBERD = "B8781C";
const TEAL = "0F6E6B";
const RUST = "BE654C";
const TINT = "F2F5F8"; // very light navy tint for cards
const TINTA = "FCF4E6"; // very light amber tint

const W = 13.333, H = 7.5;
const M = 0.62;              // side margin
const HEAD = "Calibri";
const BODY = "Calibri";

const pres = new pptxgen();
pres.layout = "LAYOUT_WIDE";
pres.author = "Soorathep Kheawhom";
pres.company = "Department of Chemical Engineering, Chulalongkorn University";
pres.title = "Evolution of Equations of State: A Physics-Driven Perspective";

let SLIDE_NO = 0;
const fig = (n) => path.join(FIG, n + ".png");
const eq = (n) => path.join(EQ, n + ".png");

// ------------------------------------------------------------------ chrome
function chrome(s, chapterTag) {
  SLIDE_NO += 1;
  s.addText(chapterTag || "", {
    x: M, y: H - 0.52, w: 8.0, h: 0.3, fontFace: BODY, fontSize: 10,
    color: SLATE, align: "left", margin: 0,
  });
  s.addText(String(SLIDE_NO), {
    x: W - M - 0.9, y: H - 0.52, w: 0.9, h: 0.3, fontFace: BODY, fontSize: 10,
    color: MIST, align: "right", margin: 0,
  });
}

/* Standard content slide.
   opts: {num, title, objective, tag, notes}  -> returns slide            */
function contentSlide(opts) {
  const s = pres.addSlide();
  s.background = { color: "FFFFFF" };
  const hasNum = opts.num !== undefined && opts.num !== null;
  if (hasNum) {
    s.addShape(pres.ShapeType.roundRect, {
      x: M, y: 0.40, w: 0.52, h: 0.52, fill: { color: NAVY }, rectRadius: 0.09,
      line: { color: NAVY, width: 0 },
    });
    s.addText(String(opts.num), {
      x: M, y: 0.40, w: 0.52, h: 0.52, fontFace: HEAD, fontSize: 20, bold: true,
      color: "FFFFFF", align: "center", valign: "middle", margin: 0,
    });
  }
  const tx = hasNum ? M + 0.72 : M;
  s.addText(opts.title, {
    x: tx, y: 0.36, w: W - tx - M, h: 0.60, fontFace: HEAD, fontSize: 28,
    bold: true, color: NAVY, align: "left", valign: "middle", margin: 0,
  });
  if (opts.objective) {
    s.addText([
      { text: "Objective   ", options: { bold: true, color: AMBERD, fontSize: 12 } },
      { text: opts.objective, options: { color: SLATE, italic: true, fontSize: 13 } },
    ], {
      x: tx, y: 1.00, w: W - tx - M, h: 0.36, fontFace: BODY, align: "left",
      valign: "middle", margin: 0,
    });
  }
  chrome(s, opts.tag);
  if (opts.notes) s.addNotes(opts.notes);
  return s;
}

/* Full-bleed dark slide used for the title and the part dividers.          */
function darkSlide(opts) {
  const s = pres.addSlide();
  s.background = { color: NAVY };
  chrome(s, "");
  if (opts.notes) s.addNotes(opts.notes);
  return s;
}

/* A tinted rounded card with an optional heading and body text.            */
function card(s, o) {
  s.addShape(pres.ShapeType.roundRect, {
    x: o.x, y: o.y, w: o.w, h: o.h, rectRadius: 0.06,
    fill: { color: o.fill || TINT }, line: { color: o.line || "FFFFFF", width: o.lw || 0 },
  });
  let ty = o.y + 0.16;
  if (o.head) {
    s.addText(o.head, {
      x: o.x + 0.20, y: ty, w: o.w - 0.40, h: 0.30, fontFace: HEAD,
      fontSize: o.headSize || 15, bold: true, color: o.headColor || NAVY,
      align: "left", valign: "middle", margin: 0,
    });
    ty += 0.34;
  }
  if (o.body) {
    s.addText(o.body, {
      x: o.x + 0.20, y: ty, w: o.w - 0.40, h: o.y + o.h - ty - 0.12,
      fontFace: BODY, fontSize: o.size || 13.5, color: o.color || GRAPHITE,
      align: "left", valign: "top", margin: 0, lineSpacingMultiple: 1.08,
    });
  }
}

/* Bulleted list inside a card-free area.                                   */
function bullets(s, o) {
  const items = o.items.map((t, i) => ({
    text: t,
    options: { bullet: { code: "2022" }, breakLine: i !== o.items.length - 1 },
  }));
  s.addText(items, {
    x: o.x, y: o.y, w: o.w, h: o.h, fontFace: BODY, fontSize: o.size || 14,
    color: o.color || GRAPHITE, align: "left", valign: "top", margin: 0,
    paraSpaceAfter: o.gap === undefined ? 8 : o.gap,
  });
}

const EQM = JSON.parse(require("fs").readFileSync(EQ + "/manifest.json", "utf8"));

/* Place an equation at its natural size (uniform 21 pt across the whole deck),
   centred on (cx, cy). It is scaled down only if it would not fit (maxW, maxH). */
function eqAt(s, name, cx, cy, maxW, maxH) {
  const m = EQM[name];
  if (!m) throw new Error("unknown equation " + name);
  const k = Math.min(1, maxW / m.w, maxH / m.h);
  const w = m.w * k, h = m.h * k;
  if (k < 1) console.log(`  scaled ${name} to ${(k * 100).toFixed(0)}%`);
  s.addImage({ path: eq(name), x: cx - w / 2, y: cy - h / 2, w: w, h: h });
}

function pngSize(p) {
  const b = require("fs").readFileSync(p);
  return { w: b.readUInt32BE(16), h: b.readUInt32BE(20) };
}

/* Place a figure inside the box (o.x, o.y, o.w, o.h) preserving its aspect
   ratio and centring it. pptxgenjs "sizing: contain" still writes a frame of
   the requested aspect, which stretched every figure in the 2025 build. */
function image(s, file, o) {
  const n = pngSize(file);
  const k = Math.min(o.w / n.w, o.h / n.h);
  const w = n.w * k, h = n.h * k;
  s.addImage({ path: file, x: o.x + (o.w - w) / 2, y: o.y + (o.h - h) / 2, w: w, h: h });
}

function caption(s, text, o) {
  s.addText(text, {
    x: o.x, y: o.y, w: o.w, h: 0.32, fontFace: BODY, fontSize: 10.5,
    color: SLATE, italic: true, align: o.align || "center", margin: 0, valign: "top",
  });
}

/* Two small conclusion chips at the bottom of a slide: physics + engineering */
function chips(s, physics, engineering, y, h) {
  const yy = y === undefined ? 5.66 : y;
  const hh = h === undefined ? 1.18 : h;
  card(s, {
    x: M, y: yy, w: (W - 2 * M - 0.32) / 2, h: hh, fill: TINTA,
    head: "Physical meaning", headSize: 11.5, headColor: AMBERD,
    body: physics, size: 12,
  });
  card(s, {
    x: M + (W - 2 * M - 0.32) / 2 + 0.32, y: yy, w: (W - 2 * M - 0.32) / 2, h: hh,
    fill: TINT, head: "Engineering implication", headSize: 11.5, headColor: NAVY,
    body: engineering, size: 12,
  });
}

const N = (tip, mis, ask) =>
  "TEACHING TIP\n" + tip +
  "\n\nCOMMON MISCONCEPTION\n" + mis +
  "\n\nASK THE CLASS\n" + ask;

// ==========================================================================
// 1. Title
// ==========================================================================
{
  const s = darkSlide({
    notes: N(
      "Open by stating the thesis of the course out loud before showing any equation: every EOS in this module exists because its predecessor omitted physics that turned out to matter. Ask students to write that sentence down; it is the spine of the whole module and of the examination.",
      "Students arrive believing that newer equations are simply 'more accurate fits'. They are not. Each one encodes a specific physical mechanism that the previous one lacked. Correct this framing on slide one.",
      "Name an equation of state you have used in a simulator. What physics do you believe it contains? Nobody is expected to answer well yet; the question is the hook."),
  });
  s.addText("Evolution of Equations of State", {
    x: 1.0, y: 2.15, w: W - 2.0, h: 1.05, fontFace: HEAD, fontSize: 44, bold: true,
    color: "FFFFFF", align: "left", valign: "middle", margin: 0,
  });
  s.addText("A Physics-Driven Perspective", {
    x: 1.0, y: 3.20, w: W - 2.0, h: 0.6, fontFace: HEAD, fontSize: 24,
    color: "CBD9E6", align: "left", valign: "middle", margin: 0,
  });
  s.addShape(pres.ShapeType.roundRect, {
    x: 1.0, y: 4.15, w: 8.6, h: 1.02, rectRadius: 0.06,
    fill: { color: "17405F" }, line: { color: "17405F", width: 0 },
  });
  s.addText("Every new equation of state was developed because the previous model neglected important physics.", {
    x: 1.2, y: 4.15, w: 8.2, h: 1.02, fontFace: BODY, fontSize: 15, italic: true,
    color: "E8EEF4", align: "left", valign: "middle", margin: 0,
  });
  s.addText("Soorathep Kheawhom", {
    x: 1.0, y: 5.48, w: W - 2.0, h: 0.36, fontFace: HEAD, fontSize: 17, bold: true,
    color: "FFFFFF", align: "left", valign: "middle", margin: 0,
  });
  s.addText("Department of Chemical Engineering, Faculty of Engineering, Chulalongkorn University", {
    x: 1.0, y: 5.84, w: W - 2.0, h: 0.34, fontFace: BODY, fontSize: 13,
    color: "CBD9E6", align: "left", valign: "middle", margin: 0,
  });
  s.addText("Graduate lecture package  |  Chemical, Mechanical, Petroleum, Energy and Materials Engineering", {
    x: 1.0, y: 6.20, w: W - 2.0, h: 0.34, fontFace: BODY, fontSize: 12,
    color: "9DB4C8", align: "left", valign: "middle", margin: 0,
  });
}

// ==========================================================================
// 2. The argument
// ==========================================================================
{
  const s = contentSlide({
    title: "The argument of this course",
    objective: "State the organising thesis and the six questions applied to every model.",
    tag: "Introduction",
    notes: N(
      "Walk up the ladder on the right from the bottom, naming only the physics added at each rung, not the equations. Students should see that the vertical axis is physical content, not calendar time.",
      "That the ladder is a ranking of accuracy. It is not. A cubic equation outperforms SAFT for a light hydrocarbon flash in both speed and reliability. The ladder ranks physical content, and content is only worth its cost when your problem contains that physics.",
      "If your system is a dry natural gas at 60 bar, which rung do you need, and why would climbing higher waste your time?"),
  });
  bullets(s, {
    x: M, y: 1.62, w: 6.05, h: 2.4, size: 15, items: [
      "The sequence of equations of state is a single argument, not a catalogue.",
      "Each model repairs one specific physical omission of its predecessor.",
      "Each repair carries a cost: parameters, computation, or loss of robustness.",
      "Choosing a model means choosing which physics your problem contains.",
    ],
  });
  card(s, {
    x: M, y: 4.20, w: 6.05, h: 2.55, fill: TINT,
    head: "Six questions asked of every model",
    body: "1.  What problem existed?\n2.  Why did the previous equation of state fail?\n3.  What new physics was introduced?\n4.  How was the mathematics modified?\n5.  What limitations remain?\n6.  Why was another equation of state developed?",
    size: 13.5,
  });
  image(s, fig("f33_hierarchy"), { x: 7.05, y: 1.55, w: 5.66, h: 5.25 });
  caption(s, "The hierarchy of physics contained in an equation of state.", { x: 7.05, y: 6.82, w: 5.66 });
}

// ==========================================================================
// 3. Timeline
// ==========================================================================
{
  const s = contentSlide({
    title: "One hundred and fifty years in one line",
    objective: "Place every model of the course on a common historical and conceptual axis.",
    tag: "Introduction",
    notes: N(
      "Point out the two clusters. Between 1873 and 1949 almost nothing usable appeared: the physics was understood but the computation was not available. Between 1949 and 1976 three models appeared in rapid succession, driven by the petroleum industry and by the arrival of the digital computer.",
      "Students read the gap between van der Waals and Redlich-Kwong as a lack of interest. It was a lack of computing power and of accurate PVT data, not of ideas.",
      "Why do you think the cubic equations appeared in the same three decades as commercial process simulators?"),
  });
  image(s, fig("f02_timeline"), { x: M, y: 1.62, w: W - 2 * M, h: 3.45 });
  chips(s,
    "Classical models (navy) add mean-field physics. Molecular models (amber) add structure: chains, hydrogen bonds, charges. Data-driven models (teal) learn the residual free energy directly.",
    "The models in industrial use today span a century of physics. A simulator flowsheet routinely mixes a 1976 cubic for the hydrocarbons with a 2001 molecular model for the solvent.",
    5.28);
}

// ==========================================================================
// 4. Part I divider
// ==========================================================================
function divider(part, title, chapters, notes) {
  const s = darkSlide({ notes });
  s.addText(part, {
    x: 1.0, y: 2.05, w: 4.0, h: 0.6, fontFace: HEAD, fontSize: 16, bold: true,
    color: AMBER, align: "left", valign: "middle", margin: 0, charSpacing: 2,
  });
  s.addText(title, {
    x: 1.0, y: 2.60, w: W - 2.0, h: 0.95, fontFace: HEAD, fontSize: 36, bold: true,
    color: "FFFFFF", align: "left", valign: "middle", margin: 0,
  });
  s.addText(chapters, {
    x: 1.0, y: 3.75, w: W - 2.0, h: 1.6, fontFace: BODY, fontSize: 16,
    color: "BFD2E2", align: "left", valign: "top", margin: 0, lineSpacingMultiple: 1.35,
  });
  return s;
}

divider("PART I", "Foundations",
  "Chapter 1   Why do we need an equation of state?\nChapter 2   The ideal gas law and the physics it omits",
  N("Use this pause to reset attention. State what Part I will establish: that the EOS is the closure of process thermodynamics, and that the ideal gas law fails in two distinct and predictable ways.",
    "Students treat Part I as revision and disengage. Emphasise that the departure-function chain in Chapter 1 is the reason the whole course exists.",
    "Before we start: what property does a simulator actually need from an EOS in order to size a flash drum?"));

// ==========================================================================
// 5. Ch1 - role of the EOS
// ==========================================================================
{
  const s = contentSlide({
    num: 1, title: "What an equation of state is for",
    objective: "Identify the EOS as the closure relation that converts measurable P, T and composition into every other thermodynamic property.",
    tag: "Chapter 1  Why do we need an equation of state?",
    notes: N(
      "Trace the arrows outward one at a time. Stress that only P, T and composition are directly measured in a plant; everything else on the diagram is inferred through the EOS.",
      "That the EOS is 'just' a PVT relation used to get density. In practice its dominant use is the fugacity coefficient, and therefore phase equilibrium. Density is the easy part.",
      "In a flowsheet with a distillation column, a compressor and a relief valve, where does the EOS enter each calculation?"),
  });
  image(s, fig("f01_eos_role"), { x: 3.15, y: 1.48, w: 7.0, h: 4.00 });
  chips(s,
    "The EOS supplies the missing relation among P, V, T and composition. Everything else follows from classical thermodynamics without further assumption.",
    "In a process simulator the EOS is evaluated more often than any other model. Its error propagates into compressor duty, vessel volume, relief sizing and custody metering.",
    5.62);
}

// ==========================================================================
// 6. Ch1 - the departure chain
// ==========================================================================
{
  const s = contentSlide({
    num: 1, title: "From PVT data to phase equilibrium",
    objective: "Follow the chain from the compressibility factor to the equilibrium ratio, and see that every link needs Z over a pressure range.",
    tag: "Chapter 1  Why do we need an equation of state?",
    notes: N(
      "Emphasise the integral limits. The fugacity coefficient at 50 bar depends on Z at every pressure from zero to 50 bar, so an EOS that is accurate at one state point but wrong elsewhere still gives the wrong fugacity.",
      "Students believe fugacity is an empirical correction factor. It is a rigorous consequence of the second law plus the EOS; there is no additional modelling assumption in these three lines.",
      "If your EOS has a 2 percent error in Z at low pressure only, does the fugacity at high pressure remain accurate? Why not?"),
  });
  const cw = (W - 2 * M - 0.30) / 2;
  card(s, { x: M, y: 1.52, w: cw, h: 1.62, fill: TINT, head: "1.  Define the deviation" });
  eqAt(s, "e_Z", M + cw / 2, 2.44, cw - 0.50, 1.06);
  card(s, { x: M + cw + 0.30, y: 1.52, w: cw, h: 1.62, fill: TINT, head: "2.  Fugacity coefficient" });
  eqAt(s, "e_lnphi", M + cw + 0.30 + cw / 2, 2.44, cw - 0.50, 1.06);
  card(s, { x: M, y: 3.30, w: cw, h: 1.62, fill: TINT, head: "3.  Residual enthalpy" });
  eqAt(s, "e_hdep", M + cw / 2, 4.22, cw - 0.50, 1.06);
  card(s, { x: M + cw + 0.30, y: 3.30, w: cw, h: 1.62, fill: TINT, head: "4.  Equilibrium ratio" });
  eqAt(s, "e_vle", M + cw + 0.30 + cw / 2, 4.22, cw - 0.50, 1.06);
  card(s, {
    x: M, y: 5.08, w: W - 2 * M, h: 1.42, fill: TINTA,
    head: "Why this matters", headColor: AMBERD,
    body: "Each expression is exact given Z(T, P). None of them is an approximation. The entire modelling uncertainty of a process simulation therefore sits in the single function Z, which is what an equation of state supplies. Improving an EOS is not a cosmetic refinement; it is the only way to reduce that uncertainty.",
    size: 14,
  });
}

// ==========================================================================
// 7. Ch1 - engineering consequence, numbers
// ==========================================================================
{
  const s = contentSlide({
    num: 1, title: "Where the error reaches the plant",
    objective: "Quantify what a modelling error in Z costs in inventory, duty and equipment size.",
    tag: "Chapter 1  Why do we need an equation of state?",
    notes: N(
      "These numbers come from the worked examples distributed with the notes and were computed with Peng-Robinson, not read from a chart. Put the second figure in context: a 2.8 percent duty error on a 200 kW machine is small, but on a 20 MW export compressor it is a real capital and energy decision.",
      "That a 17 percent density error is 'only' 17 percent. It is a 17 percent error in the mass of hydrocarbon in a vessel, which is simultaneously a safety-case error and a custody-transfer error.",
      "Which of these three errors would you notice first in commissioning, and which would you never notice until an audit?"),
  });
  const cw = (W - 2 * M - 0.60) / 3;
  const stat = (x, big, unit, head, body, col) => {
    card(s, { x, y: 1.62, w: cw, h: 4.55, fill: TINT });
    s.addText(big, {
      x: x + 0.20, y: 1.88, w: cw - 0.40, h: 1.05, fontFace: HEAD, fontSize: 54,
      bold: true, color: col, align: "left", valign: "middle", margin: 0,
    });
    s.addText(unit, {
      x: x + 0.20, y: 2.92, w: cw - 0.40, h: 0.32, fontFace: BODY, fontSize: 12.5,
      color: SLATE, align: "left", valign: "middle", margin: 0,
    });
    s.addText(head, {
      x: x + 0.20, y: 3.34, w: cw - 0.40, h: 0.6, fontFace: HEAD, fontSize: 15,
      bold: true, color: NAVY, align: "left", valign: "top", margin: 0,
    });
    s.addText(body, {
      x: x + 0.20, y: 3.98, w: cw - 0.40, h: 2.0, fontFace: BODY, fontSize: 12.5,
      color: GRAPHITE, align: "left", valign: "top", margin: 0, lineSpacingMultiple: 1.08,
    });
  };
  stat(M, "16.6", "per cent", "Inventory error",
    "Methane at 300 K and 100 bar. Using PV = RT instead of Peng-Robinson underestimates the mass held in a 50 cubic metre vessel by 16.6 per cent. This is a safety-case quantity.", RUST);
  stat(M + cw + 0.30, "19.9", "per cent", "Volume error",
    "The same state point sized on the ideal gas law gives a molar volume of 249.4 instead of 208.0 cubic centimetres per mole, an oversizing of 19.9 per cent.", AMBERD);
  stat(M + 2 * (cw + 0.30), "2.8", "per cent", "Compressor duty error",
    "Isentropic compression of 100 kilomoles per hour of carbon dioxide from 10 to 80 bar: 202.1 kilowatts with residual properties against 208.0 kilowatts on ideal-gas heat capacities alone.", NAVY);
}

// ==========================================================================
// 8. Ch2 - assumptions
// ==========================================================================
{
  const s = contentSlide({
    num: 2, title: "The ideal gas law and its three assumptions",
    objective: "State the molecular assumptions behind PV = RT and identify exactly which one each later model repairs.",
    tag: "Chapter 2  The ideal gas law",
    notes: N(
      "Write the three assumptions on the board and leave them there for the rest of the lecture. Chapter 3 repairs assumptions one and two simultaneously. Chapters 8 to 10 refine the second. Chapter 11 repairs the third by adding directional bonding.",
      "Students say the ideal gas law assumes 'no forces'. More precisely, it assumes the molecules have no volume and that the average potential energy is zero. Elastic collisions are a separate statement about the collision dynamics.",
      "Which of these three assumptions fails first as you compress a gas at constant temperature, and how would you know from the sign of Z minus one?"),
  });
  eqAt(s, "e_ideal", 6.65, 1.97, 5.3, 0.78);
  const cw = (W - 2 * M - 0.60) / 3;
  card(s, {
    x: M, y: 2.62, w: cw, h: 2.25, fill: TINT, head: "1.  Point particles",
    body: "Molecules occupy no volume, so the entire container volume is available to every molecule. Repaired by the co-volume b in 1873.", size: 13.5,
  });
  card(s, {
    x: M + cw + 0.30, y: 2.62, w: cw, h: 2.25, fill: TINT, head: "2.  No interaction energy",
    body: "The average potential energy between molecules is zero. Repaired by the mean-field term a/V squared in 1873, then refined for fifty years.", size: 13.5,
  });
  card(s, {
    x: M + 2 * (cw + 0.30), y: 2.62, w: cw, h: 2.25, fill: TINT, head: "3.  Structureless molecules",
    body: "No shape, no orientation, no directional bonding, no charge. Not repaired until SAFT in 1990 and electrolyte models thereafter.", size: 13.5,
  });
  eqAt(s, "e_kinetic", 6.65, 5.46, 6.6, 0.72);
  caption(s, "Kinetic theory gives the same result from the momentum flux at the wall, with the same three assumptions built in.", { x: M, y: 5.95, w: W - 2 * M });
}

// ==========================================================================
// 9. Ch2 - where it works
// ==========================================================================
{
  const s = contentSlide({
    num: 2, title: "Where the ideal gas law is good enough",
    objective: "Delimit the region of the reduced state plane in which PV = RT is accurate to one and to five per cent.",
    tag: "Chapter 2  The ideal gas law",
    notes: N(
      "Have students locate three real streams on this map: ambient air, a natural gas pipeline at 70 bar, and the vapour leaving a propane refrigeration condenser. Only the first sits comfortably in the white region.",
      "That 'high pressure' is the criterion. It is not: the criterion is reduced pressure at a given reduced temperature. Ammonia at 10 bar is further from ideal than nitrogen at 60 bar.",
      "Air at ambient conditions has a reduced temperature near 2.3. Read the one per cent contour: up to what pressure may you use PV = RT for ventilation calculations?"),
  });
  image(s, fig("f04_ideal_fail_map"), { x: 3.55, y: 1.48, w: 6.25, h: 4.00 });
  chips(s,
    "Ideality is a low-density statement. The gas behaves ideally when the mean separation is large compared with the molecular diameter and the thermal energy is large compared with the well depth.",
    "For light gases above about twice the critical temperature and below a few bar, PV = RT is adequate for line sizing and vent calculations. Outside that window it is not defensible.",
    5.62);
}

// ==========================================================================
// 10. Ch2 - where it fails
// ==========================================================================
{
  const s = contentSlide({
    num: 2, title: "Two distinct failure modes",
    objective: "Distinguish failure by density from failure by proximity to saturation, and read both from the Z curve.",
    tag: "Chapter 2  The ideal gas law",
    notes: N(
      "Compare nitrogen with carbon dioxide at the same temperature. Nitrogen is far above its critical temperature and stays near Z equal to one; carbon dioxide is close to saturation at 300 K and collapses. The difference is not molecular size, it is reduced temperature.",
      "That the curves fall because the gas is 'compressed'. They fall because attraction pulls the molecules together faster than pressure alone would; the rise at high pressure is the repulsive core reasserting itself.",
      "Two of these four curves reach Z above one within the plotted range. Which two, and what do they have in common?"),
  });
  image(s, fig("f03_ideal_vs_real_Z"), { x: 3.55, y: 1.48, w: 6.25, h: 4.00 });
  chips(s,
    "The initial fall below unity is attraction. The eventual rise above unity is the finite size of the molecules. Both are absent from PV = RT by construction.",
    "Near saturation the error is not a smooth few per cent: it is a discontinuity, because a real fluid condenses and the ideal gas law does not know that phases exist.",
    5.62);
}

// ==========================================================================
// 11. Ch2 - what physics is missing
// ==========================================================================
{
  const s = contentSlide({
    num: 2, title: "What physics is missing?",
    objective: "Name the two omissions that the next model must repair, and predict the sign of each correction.",
    tag: "Chapter 2  The ideal gas law",
    notes: N(
      "Do not move on until the class has predicted the signs. Excluded volume reduces the space available, so it raises pressure. Attraction reduces the momentum delivered to the wall, so it lowers pressure. Any student who can predict these two signs can reconstruct the van der Waals equation without memorising it.",
      "Students expect both corrections to reduce the pressure because 'real gases are less ideal'. The two corrections have opposite signs, which is precisely why Z has a minimum.",
      "Write down the simplest possible functional form for each correction. What must each one do as the volume becomes very large?"),
  });
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, {
    x: M, y: 1.72, w: cw, h: 2.35, fill: TINTA, headColor: TEAL,
    head: "Omission 1   Molecules occupy volume",
    body: "The volume available for molecular motion is smaller than the container volume. Replacing V by V minus b raises the predicted pressure at fixed T and V.\n\nExpected sign:  Z increases.",
    size: 14,
  });
  card(s, {
    x: M + cw + 0.34, y: 1.72, w: cw, h: 2.35, fill: TINTA, headColor: RUST,
    head: "Omission 2   Molecules attract one another",
    body: "A molecule approaching the wall is pulled back by its neighbours, so it delivers less momentum. The correction scales as the square of density.\n\nExpected sign:  Z decreases.",
    size: 14,
  });
  card(s, {
    x: M, y: 4.32, w: W - 2 * M, h: 1.85, fill: TINT,
    head: "The consequence",
    body: "Two corrections of opposite sign, with different density dependence, produce a compressibility factor that first falls, passes through a minimum, and then rises. No single-term correction can reproduce that shape. This is the structural reason every subsequent equation of state contains a repulsive term and an attractive term.",
    size: 14,
  });
}

// ==========================================================================
// 12. Part II divider
// ==========================================================================
divider("PART II", "The first real fluid",
  "Chapter 3   The van der Waals equation of state\nChapter 4   The compressibility factor\nChapter 5   The virial equation and its statistical basis",
  N("State the ambition of Part II: one equation, two molecular mechanisms, and the first theory in history that predicts a liquid, a vapour and a critical point from a single expression.",
    "Students treat van der Waals as obsolete. It is quantitatively obsolete and conceptually indispensable: every cubic equation still in industrial use in 2026 has exactly the structure introduced in 1873.",
    "Can an equation that is wrong by 30 per cent in the critical compressibility still be a scientific breakthrough? On what grounds?"));

// ==========================================================================
// 13. Ch3 - molecular picture
// ==========================================================================
{
  const s = contentSlide({
    num: 3, title: "van der Waals 1873: the molecular picture",
    objective: "Derive the two corrections from a molecular argument rather than accept them as empirical terms.",
    tag: "Chapter 3  The van der Waals equation of state",
    notes: N(
      "The factor of two in the co-volume is worth two minutes. The excluded sphere around a molecule has radius sigma, not sigma over two, so the excluded volume per pair is four times the molecular volume; per molecule it is twice. Students who miss this always misremember b.",
      "That b is the volume of the molecules. It is half the excluded volume per pair, which is four times the hard-sphere volume per molecule. The distinction matters when b is used to estimate a molecular diameter.",
      "Andrews measured continuity between liquid and vapour in 1869. Why did that experiment make a two-term correction seem plausible rather than arbitrary?"),
  });
  image(s, fig("f05_vdw_molecular"), { x: 2.35, y: 1.55, w: 8.6, h: 3.65 });
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, {
    x: M, y: 5.30, w: cw, h: 1.55, fill: TINTA, headColor: TEAL,
    head: "Excluded volume",
    body: "Two hard spheres of diameter sigma cannot approach closer than sigma. The excluded volume per molecule is b = 2 pi N sigma cubed over 3, four times the hard-sphere volume.",
    size: 12.5,
  });
  card(s, {
    x: M + cw + 0.34, y: 5.30, w: cw, h: 1.55, fill: TINTA, headColor: RUST,
    head: "Mean-field attraction",
    body: "Each molecule feels an average attractive field proportional to the local density. The energy density therefore scales as density squared, giving a pressure reduction of a over V squared.",
    size: 12.5,
  });
}

// ==========================================================================
// 14. Ch3 - assembling the equation
// ==========================================================================
{
  const s = contentSlide({
    num: 3, title: "Assembling the equation",
    objective: "Assemble the two corrections into a single cubic in volume and interpret each term.",
    tag: "Chapter 3  The van der Waals equation of state",
    notes: N(
      "Show that multiplying out gives a cubic in V. That is the whole reason this family is called cubic: it is the lowest polynomial order that can deliver three volume roots and therefore two coexisting phases plus an unstable branch.",
      "Students think 'cubic' refers to the volume being cubed in some physical sense. It refers to the polynomial degree in V after clearing denominators, and that degree is what makes phase coexistence representable.",
      "Why is a quadratic in V insufficient to describe a fluid that can exist as a liquid and a vapour at the same pressure?"),
  });
  eqAt(s, "e_bexcl", 2.65, 2.175, 2.7, 0.85);
  eqAt(s, "e_vdw", 8.3, 2.195, 6.4, 1.15);
  s.addShape(pres.ShapeType.line, {
    x: 4.55, y: 2.18, w: 0.0, h: 0.0, line: { color: MIST, width: 1 },
  });
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, {
    x: M, y: 3.15, w: cw, h: 1.85, fill: TINT, headColor: TEAL,
    head: "Repulsive term:  RT / (V - b)",
    body: "Diverges as V approaches b, so the fluid cannot be compressed below the co-volume. This single change already produces Z greater than one at high density.",
    size: 13.5,
  });
  card(s, {
    x: M + cw + 0.34, y: 3.15, w: cw, h: 1.85, fill: TINT, headColor: RUST,
    head: "Attractive term:  minus a / V squared",
    body: "Reduces the pressure in proportion to density squared, because the number of interacting pairs per unit volume scales that way. Produces Z less than one at moderate density.",
    size: 13.5,
  });
  card(s, {
    x: M, y: 5.25, w: W - 2 * M, h: 1.35, fill: TINTA, headColor: AMBERD,
    head: "The structural point",
    body: "Clearing denominators gives a cubic polynomial in V. Three real roots below the critical temperature correspond to a saturated liquid, a mechanically unstable state, and a saturated vapour. One equation now contains both phases.",
    size: 13.5,
  });
}

// ==========================================================================
// 15. Ch3 - critical point fixes a and b
// ==========================================================================
{
  const s = contentSlide({
    num: 3, title: "The critical point fixes the parameters",
    objective: "Use the critical isotherm inflection conditions to express a and b in terms of measurable critical constants.",
    tag: "Chapter 3  The van der Waals equation of state",
    notes: N(
      "This is the decisive methodological move of the whole subject: a molecular parameter that cannot be measured is replaced by a macroscopic one that can. Every cubic equation of state since 1873 uses the same device.",
      "Students think a and b are fitted to PVT data. In the classical cubics they are not fitted at all; they are determined analytically by the critical point. Fitting only enters with Soave's alpha function in 1972.",
      "The critical point supplies exactly two independent conditions. How many parameters can it therefore determine, and what does that tell you about the maximum complexity of a classical cubic?"),
  });
  eqAt(s, "e_critcond", 6.7, 2.12, 6.3, 1);
  eqAt(s, "e_vdwab", 6.7, 3.525, 9.7, 1.05);
  card(s, {
    x: M, y: 4.45, w: W - 2 * M, h: 1.72, fill: TINTA, headColor: AMBERD,
    head: "A prediction, not a fit",
    body: "The critical compressibility is now a pure number: 3/8 for every substance, with no adjustable content. That is a genuine, falsifiable prediction of the theory. It is also, as the next slides show, the first place the theory is measurably wrong, and that failure drives the following one hundred years of development.",
    size: 14,
  });
}

// ==========================================================================
// 16. Ch3 - isotherms
// ==========================================================================
{
  const s = contentSlide({
    num: 3, title: "Isotherms, the dome and the critical point",
    objective: "Read phase behaviour directly from the shape of the predicted isotherms.",
    tag: "Chapter 3  The van der Waals equation of state",
    notes: N(
      "Trace one subcritical isotherm from right to left with a pointer: vapour, saturation, the unphysical loop, saturation again, liquid. Then trace the supercritical isotherm and show that the loop has vanished. The critical isotherm is the boundary case with a horizontal inflection.",
      "That the loop is a numerical artefact. It is a real prediction of the equation, and it is what makes the equation able to describe two phases at all; it simply must be replaced within the dome by the equal-area construction.",
      "At the critical temperature the loop degenerates to a single point. What does that say about the compressibility of a fluid at its critical point, and why does that matter for supercritical extraction?"),
  });
  image(s, fig("f06_vdw_isotherms"), { x: 3.55, y: 1.48, w: 6.25, h: 4.00 });
  chips(s,
    "One analytic expression produces a liquid branch, a vapour branch and a critical point. Before 1873 no theory did this.",
    "Cubic equations remain the only models fast and robust enough to be called millions of times inside a distillation column solver.",
    5.62);
}

// ==========================================================================
// 17. Ch3 - Maxwell construction
// ==========================================================================
{
  const s = contentSlide({
    num: 3, title: "The Maxwell equal-area construction",
    objective: "Replace the mechanically unstable loop by the equilibrium saturation pressure using equality of Gibbs energy.",
    tag: "Chapter 3  The van der Waals equation of state",
    notes: N(
      "Derive the equal-area rule from equality of molar Gibbs energy along the isotherm rather than presenting it as a geometric recipe: integrating V dP between the two saturated states must vanish, which is exactly the equal-area statement.",
      "That the metastable branches are meaningless. They are physically real and observable: superheated liquid and subcooled vapour both occur, and both matter in relief-valve and flashing-flow calculations.",
      "The branch with positive slope has negative compressibility. What would happen physically to a fluid placed on that branch?"),
  });
  image(s, fig("f07_maxwell"), { x: 0.55, y: 1.55, w: 6.6, h: 4.6 });
  eqAt(s, "e_maxwell", 9.85, 2.325, 4.4, 0.95);
  card(s, {
    x: 7.45, y: 3.10, w: 5.25, h: 1.55, fill: TINT,
    head: "What the rule enforces",
    body: "Equality of molar Gibbs energy between the saturated liquid and the saturated vapour, which is the phase-equilibrium criterion applied along one isotherm.",
    size: 13,
  });
  card(s, {
    x: 7.45, y: 4.80, w: 5.25, h: 1.40, fill: TINTA, headColor: RUST,
    head: "The unstable branch",
    body: "Where dP/dV is positive the fluid has negative compressibility and cannot exist. It is excluded by stability, not by the equation.",
    size: 13,
  });
}

// ==========================================================================
// 18. Ch3 - the verdict
// ==========================================================================
{
  const s = contentSlide({
    num: 3, title: "The verdict on van der Waals",
    objective: "Identify the specific quantitative failure that motivates every later cubic equation.",
    tag: "Chapter 3  The van der Waals equation of state",
    notes: N(
      "Make the diagnosis precise. The equation is not merely inaccurate; it is inaccurate in a structural way, because the critical compressibility is fixed by the algebra and cannot be adjusted without changing the functional form. That is why Redlich and Kwong changed the denominator rather than refitting constants.",
      "Students propose fixing this by refitting a and b. It cannot be fixed that way: with two parameters and two critical conditions, the critical compressibility is completely determined. Only a change of functional form can move it.",
      "Given that 0.375 is roughly 30 per cent too high, in which direction will van der Waals err on saturated liquid density, and by roughly how much?"),
  });
  image(s, fig("f08_vdw_reduced_Zc"), { x: 0.75, y: 1.60, w: 6.1, h: 4.4 });
  bullets(s, {
    x: 7.35, y: 1.72, w: 5.4, h: 3.0, size: 14, items: [
      "Predicted critical compressibility 0.375 against a measured range of 0.23 to 0.29.",
      "Saturated liquid volumes therefore too large by tens of per cent.",
      "The attraction parameter a has no temperature dependence, so vapour pressures are poor.",
      "No molecular shape or polarity enters anywhere in the equation.",
    ],
  });
  card(s, {
    x: 7.35, y: 4.95, w: 5.4, h: 1.35, fill: TINTA, headColor: AMBERD,
    head: "Motivates Chapter 8",
    body: "Redlich and Kwong changed the volume dependence of the attraction and made it decay with temperature.",
    size: 13,
  });
}

// ==========================================================================
// 19. Ch4 - Z as bookkeeper
// ==========================================================================
{
  const s = contentSlide({
    num: 4, title: "The compressibility factor as a diagnostic",
    objective: "Interpret the sign of Z minus one, the location of the minimum, and the crossover, in molecular terms.",
    tag: "Chapter 4  The compressibility factor",
    notes: N(
      "Insist that Z is not a model. It is a dimensionless statement of how far the fluid is from ideality, and it is the natural variable in which every equation of state should be compared, because it removes the trivial pressure and temperature dependence.",
      "That Z less than one means the gas is 'compressible' and Z greater than one means it is not. Z is a ratio of actual to ideal molar volume; both regimes are compressible, but for different molecular reasons.",
      "At the Z minimum, attraction and repulsion balance. Does that mean the intermolecular forces are zero there?"),
  });
  image(s, fig("f09_Z_meaning"), { x: 3.50, y: 1.50, w: 6.35, h: 4.45 });
  eqAt(s, "e_zsign", 7.30, 6.30, 7.9, 0.42);
  card(s, {
    x: M, y: 1.72, w: 2.70, h: 1.55, fill: TINTA, headColor: RUST,
    head: "Z < 1", body: "Attraction dominates: the fluid occupies less volume than an ideal gas at the same T and P.", size: 12.5,
  });
  card(s, {
    x: M, y: 3.45, w: 2.70, h: 1.55, fill: TINTA, headColor: TEAL,
    head: "Z > 1", body: "Repulsion dominates: the finite molecular core resists compression and the fluid is stiffer than ideal.", size: 12.5,
  });
  card(s, {
    x: M, y: 5.18, w: 2.70, h: 1.30, fill: TINT,
    head: "Z = 1", body: "Coincidence, not ideality. The two effects merely cancel.", size: 12.5,
  });
}

// ==========================================================================
// 20. Ch4 - Boyle temperature
// ==========================================================================
{
  const s = contentSlide({
    num: 4, title: "The Boyle temperature",
    objective: "Connect the initial slope of Z against P to the second virial coefficient and define the Boyle temperature.",
    tag: "Chapter 4  The compressibility factor",
    notes: N(
      "This slide is the bridge to Chapter 5. The low-pressure limiting slope of Z is not an empirical observation; it is exactly the second virial coefficient divided by RT, and the second virial coefficient is exactly a two-body integral over the pair potential. Preview that link now so Chapter 5 feels inevitable.",
      "Students interpret the Boyle temperature as the temperature at which a gas behaves ideally. It is only the temperature at which the leading correction vanishes; higher-order terms remain, so the gas is ideal to first order in density only.",
      "Hydrogen and helium have Boyle temperatures below ambient. What does that predict about the sign of their deviation from ideality at room temperature?"),
  });
  image(s, fig("f10_boyle"), { x: 3.35, y: 1.55, w: 6.65, h: 4.3 });
  eqAt(s, "e_zslope", M + 1.36, 2.60, 2.72, 0.90);
  eqAt(s, "e_boyle", (M + 0.35) + (1.85) / 2, 3.35 + 0.42 / 2, 1.85, 0.42);
  card(s, {
    x: M, y: 4.15, w: 2.72, h: 2.05, fill: TINT,
    head: "Reading the slope",
    body: "Below the Boyle temperature the initial slope is negative: attraction wins first. Above it the slope is positive: the repulsive core is felt immediately.",
    size: 12.5,
  });
  caption(s, "Lennard-Jones fluid: the second virial coefficient computed by numerical integration of the Mayer function gives a reduced Boyle temperature of 3.42.", { x: 3.35, y: 5.95, w: 6.65 });
}

// ==========================================================================
// 21. Ch4 - generalized chart and Z landscape
// ==========================================================================
{
  const s = contentSlide({
    num: 4, title: "The generalized compressibility chart",
    objective: "Read Z from reduced coordinates and recognise the chart as the engineering form of corresponding states.",
    tag: "Chapter 4  The compressibility factor",
    notes: N(
      "Explain that these charts were the working tool of the profession for fifty years and are still the fastest sanity check available. If a simulator returns Z equal to 0.45 for a stream at reduced temperature 1.8 and reduced pressure 0.5, the chart tells you immediately that something is wrong.",
      "That the chart is a correlation of data for one particular fluid. It is a statement that all fluids collapse onto one surface when plotted in reduced coordinates, which is a theoretical claim, and Chapter 6 examines when it holds.",
      "Estimate Z for a stream at reduced temperature 1.2 and reduced pressure 2.0 from the chart, then decide whether you would trust that number for ammonia."),
  });
  image(s, fig("f11_generalized_chart"), { x: 0.62, y: 1.60, w: 6.05, h: 4.35 });
  image(s, fig("f34_Z_landscape"), { x: 6.90, y: 1.60, w: 5.85, h: 4.35 });
  caption(s, "Left: the classical chart form. Right: the same information as a contour map of Z over the reduced state plane, with the saturation line and the Z = 1 contour marked.", { x: M, y: 6.05, w: W - 2 * M });
}

// ==========================================================================
// 22. Ch5 - virial expansion
// ==========================================================================
{
  const s = contentSlide({
    num: 5, title: "The virial equation: an exact expansion",
    objective: "Write the density and pressure expansions, relate their coefficients, and identify the physical content of each term.",
    tag: "Chapter 5  The virial equation of state",
    notes: N(
      "Emphasise the word exact. Every other equation in this course is a model; the virial expansion is a theorem, valid term by term for any pair potential. The engineering weakness is not the theory but the truncation.",
      "Students confuse the two expansions and use B interchangeably. The pressure-series coefficient is B divided by RT, and the higher coefficients differ more substantially. Insist on the subscripted notation.",
      "The second virial coefficient describes pairs, the third describes triplets. What does that predict about how many terms you need at liquid density?"),
  });
  eqAt(s, "e_virial", 4.5, 1.995, 4.4, 0.55);
  eqAt(s, "e_virialP", 9.75, 2.00, 5.3, 0.80);
  const cw = (W - 2 * M - 0.60) / 3;
  card(s, {
    x: M, y: 2.85, w: cw, h: 2.15, fill: TINT, head: "Second coefficient",
    body: "Two-body interactions only. Computable from the pair potential without approximation, and measurable from low-pressure PVT data.", size: 13.5,
  });
  card(s, {
    x: M + cw + 0.30, y: 2.85, w: cw, h: 2.15, fill: TINT, head: "Third coefficient",
    body: "Three-body interactions, including genuine non-additive contributions. Far harder to measure and rarely available for industrial compounds.", size: 13.5,
  });
  card(s, {
    x: M + 2 * (cw + 0.30), y: 2.85, w: cw, h: 2.15, fill: TINTA, headColor: RUST, head: "Higher coefficients",
    body: "Essentially unavailable. The series is therefore always truncated in practice, which restricts the equation to gases at moderate density.", size: 13.5,
  });
  card(s, {
    x: M, y: 5.25, w: W - 2 * M, h: 1.35, fill: TINTA, headColor: AMBERD,
    head: "The pedagogical point",
    body: "The virial equation is the only equation in this course that is exact in principle. It is useless for liquids for exactly that reason: an exact expansion in density cannot be truncated where the density is high.",
    size: 14,
  });
}

// ==========================================================================
// 23. Ch5 - B2 from the pair potential
// ==========================================================================
{
  const s = contentSlide({
    num: 5, title: "From the pair potential to the second virial coefficient",
    objective: "Connect a molecular-level potential to a macroscopic, measurable coefficient through the Mayer function.",
    tag: "Chapter 5  The virial equation of state",
    notes: N(
      "This is the first point in the course where a macroscopic thermodynamic property is computed from a molecular model without any adjustable parameter. Dwell on it: it is the intellectual ancestor of SAFT in Chapter 11.",
      "Students read the Mayer function as a probability. It is not; it is a measure of how much the pair correlation departs from the ideal case, and it is negative where the potential is repulsive and positive where it is attractive.",
      "At very high temperature the exponential approaches one everywhere except inside the core. What limiting value does the integral approach, and what does it correspond to physically?"),
  });
  eqAt(s, "e_B2stat", 6.65, 2.05, 7.1, 0.9);
  image(s, fig("f13_pair_potential"), { x: 0.62, y: 2.70, w: 6.05, h: 3.45 });
  image(s, fig("f12_virial_B"), { x: 6.90, y: 2.70, w: 5.85, h: 3.45 });
  caption(s, "Left: the Lennard-Jones potential and its Mayer function at two temperatures. Right: the resulting second virial coefficient, negative at low temperature, crossing zero at the Boyle point.", { x: M, y: 6.20, w: W - 2 * M });
}

// ==========================================================================
// 24. Ch5 - truncation
// ==========================================================================
{
  const s = contentSlide({
    num: 5, title: "Why truncation limits the virial equation",
    objective: "Quantify the density at which two-term and three-term truncations fail, and draw the practical boundary.",
    tag: "Chapter 5  The virial equation of state",
    notes: N(
      "Give the practical rule: the two-term form is reliable to roughly half the critical density, the three-term form somewhat further, and neither is usable in the liquid. Then state the consequence: for a two-phase calculation the virial equation is simply not a candidate.",
      "That adding more terms would fix this. The coefficients beyond the third are not known for industrial compounds, and the series converges slowly near the critical point in any case.",
      "You need a vapour-liquid flash at 60 per cent of the critical density. Can you use a truncated virial equation for either phase? For which one, and why not the other?"),
  });
  image(s, fig("f14_virial_range"), { x: 3.55, y: 1.48, w: 6.25, h: 4.00 });
  chips(s,
    "Truncation is a statement about how many bodies interact simultaneously. At liquid density every molecule interacts with a dozen neighbours at once, so a two-body or three-body expansion cannot converge.",
    "For compressor and pipeline calculations in the gas phase the two-term virial equation is accurate and cheap. For anything involving a liquid it is not an option, which is why the cubic family survived.",
    5.62);
}

// ==========================================================================
// 25. Part III divider
// ==========================================================================
divider("PART III", "Generalization",
  "Chapter 6   The principle of corresponding states\nChapter 7   The Pitzer acentric factor",
  N("Frame Part III as a change of question. Parts I and II asked what equation describes a fluid. Part III asks whether all fluids are the same fluid once the axes are rescaled, and if not, what single number measures the difference.",
    "Students think corresponding states is a curve-fitting convenience. It is a theoretical prediction that follows from the vdW equation and, more generally, from conformal pair potentials.",
    "If two fluids obeyed exactly the same law in reduced coordinates, what would that imply about their molecules?"));

// ==========================================================================
// 26. Ch6 - CS from vdW
// ==========================================================================
{
  const s = contentSlide({
    num: 6, title: "Corresponding states falls out of van der Waals",
    objective: "Derive the reduced form of the van der Waals equation and recognise that it contains no substance-specific constant.",
    tag: "Chapter 6  The principle of corresponding states",
    notes: N(
      "Do this substitution live on the board. Watching a and b disappear is far more convincing than being shown the result. Then state the general condition: any two-parameter equation of state implies two-parameter corresponding states, and the two statements are equivalent.",
      "Students believe corresponding states is more general than van der Waals. It is more general in its statistical-mechanical form, based on conformal pair potentials, but the two-parameter version is exactly equivalent to a two-parameter cubic.",
      "Which molecules have pair potentials that are identical after scaling by an energy and a length? Name three, and then name three that certainly do not."),
  });
  eqAt(s, "e_csvdw", 6.65, 2.145, 5.6, 1.05);
  eqAt(s, "e_cs2", 6.65, 3.16, 4.2, 0.42);
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, {
    x: M, y: 3.75, w: cw, h: 2.55, fill: TINT, headColor: TEAL,
    head: "Where it works",
    body: "Argon, krypton, xenon, methane and nitrogen: nearly spherical, non-polar molecules whose pair potentials are conformal, differing only by an energy scale and a length scale.\n\nThese are the simple fluids, and for them the collapse is close to exact.",
    size: 13.5,
  });
  card(s, {
    x: M + cw + 0.34, y: 3.75, w: cw, h: 2.55, fill: TINTA, headColor: RUST,
    head: "Where it must fail",
    body: "Elongated molecules such as n-octane, polar molecules such as ammonia, quadrupolar molecules such as carbon dioxide, and hydrogen-bonding molecules such as water.\n\nTheir potentials are not conformal, so no rescaling can superimpose them.",
    size: 13.5,
  });
}

// ==========================================================================
// 27. Ch6 - universality and its failure
// ==========================================================================
{
  const s = contentSlide({
    num: 6, title: "Universality and its limits",
    objective: "Observe the collapse for simple fluids and the systematic departure for polar and associating fluids.",
    tag: "Chapter 6  The principle of corresponding states",
    notes: N(
      "Direct attention to the ordering of the curves. The departure is not random scatter; it grows monotonically with a molecular property. Ask the class to guess what that property is before revealing the acentric factor in the next chapter.",
      "Students attribute the spread to experimental error. It is systematic and reproducible, and its regularity is exactly what makes a third parameter possible.",
      "The departure is ordered. What single molecular characteristic could you use to index it, and how would you measure that characteristic without a microscope?"),
  });
  image(s, fig("f15_corresponding_states"), { x: 3.55, y: 1.48, w: 6.25, h: 4.00 });
  chips(s,
    "Two parameters force a single universal critical compressibility. Real fluids have critical compressibilities from 0.23 to 0.29, so a two-parameter theory cannot be exact for all of them.",
    "Two-parameter charts are adequate for light hydrocarbons and permanent gases. For refrigerants, water and amines they are not, and a third parameter is mandatory.",
    5.62);
}

// ==========================================================================
// 28. Ch7 - why Tc and Pc are not enough
// ==========================================================================
{
  const s = contentSlide({
    num: 7, title: "Why the critical constants are not enough",
    objective: "Show that reduced vapour-pressure curves have different slopes, and that the slope carries the missing information.",
    tag: "Chapter 7  The Pitzer acentric factor",
    notes: N(
      "Point out that all lines pass through the same point at reduced temperature one, by definition of reduced coordinates. The only remaining freedom is the slope, so the slope must be where all the substance-specific information sits.",
      "Students expect the third parameter to be something structural like a dipole moment. Pitzer deliberately chose a macroscopic, easily measured quantity instead, precisely so that it would be available for industrial compounds.",
      "Two fluids share the same critical temperature and pressure but have vapour-pressure lines of different slope. Which one boils at a lower reduced temperature, and what does that say about its molecules?"),
  });
  image(s, fig("f16_psat_reduced"), { x: 3.55, y: 1.48, w: 6.25, h: 4.00 });
  chips(s,
    "In reduced coordinates every vapour-pressure line is pinned at the critical point. What distinguishes fluids is how steeply the line falls, which reflects the strength and directionality of the intermolecular forces.",
    "This is a practical choice as well as a physical one: vapour pressure is the most widely measured property in chemical engineering, so a parameter defined from it is available for essentially every compound.",
    5.62);
}

// ==========================================================================
// 29. Ch7 - definition of omega
// ==========================================================================
{
  const s = contentSlide({
    num: 7, title: "Pitzer's acentric factor",
    objective: "Define the acentric factor from a single point on the reduced vapour-pressure curve and interpret it physically.",
    tag: "Chapter 7  The Pitzer acentric factor",
    notes: N(
      "Justify the choice of reduced temperature 0.7: it lies near the normal boiling point of many common fluids, it is comfortably subcritical so the measurement is easy, and it is far enough from the critical point to avoid critical anomalies. The value minus one for simple fluids is an empirical calibration, not a derivation.",
      "That the acentric factor measures how non-spherical a molecule is in a geometric sense. It measures the departure of the intermolecular force field from spherical symmetry, which includes polarity and hydrogen bonding, not only shape.",
      "Argon has an acentric factor of essentially zero and water has 0.345. Which contributes more to water's value, its shape or its hydrogen bonding?"),
  });
  image(s, fig("f17_acentric_definition"), { x: 0.62, y: 1.60, w: 6.15, h: 4.5 });
  eqAt(s, "e_omega", 9.8, 2.11, 5.3, 0.62);
  card(s, {
    x: 7.05, y: 2.72, w: 5.65, h: 1.60, fill: TINT,
    head: "Why reduced temperature 0.7",
    body: "Close to the normal boiling point of many fluids, comfortably subcritical, easily measured, and far enough from the critical point to avoid critical anomalies.",
    size: 13,
  });
  card(s, {
    x: 7.05, y: 4.48, w: 5.65, h: 1.60, fill: TINTA, headColor: AMBERD,
    head: "Physical meaning",
    body: "The acentric factor measures how far the intermolecular force field departs from spherical symmetry. It increases with chain length, with polarity and with hydrogen bonding.",
    size: 13,
  });
}

// ==========================================================================
// 30. Ch7 - omega across families and three-parameter CS
// ==========================================================================
{
  const s = contentSlide({
    num: 7, title: "The acentric factor across molecular families",
    objective: "Relate the numerical value of the acentric factor to molecular architecture, and state the three-parameter correlation.",
    tag: "Chapter 7  The Pitzer acentric factor",
    notes: N(
      "Walk down the chart family by family. Note that carbon dioxide, a linear symmetric molecule, has a value comparable with n-butane because of its quadrupole. This breaks the naive shape interpretation and is worth stating explicitly.",
      "That the acentric factor is a measured molecular property. It is a correlating parameter derived from vapour pressure; it can even be negative for helium and hydrogen, which is meaningless as a shape.",
      "Methanol has a larger acentric factor than benzene despite being a much smaller molecule. Explain."),
  });
  image(s, fig("f18_omega_vs_shape"), { x: 0.62, y: 1.58, w: 6.55, h: 4.55 });
  eqAt(s, "e_pitzer", 10, 2.2, 4.9, 0.5);
  card(s, {
    x: 7.45, y: 2.75, w: 5.25, h: 1.75, fill: TINT,
    head: "Three-parameter corresponding states",
    body: "A simple-fluid reference surface plus a linear correction weighted by the acentric factor. The Lee-Kesler tables are the standard numerical implementation.",
    size: 13,
  });
  card(s, {
    x: 7.45, y: 4.65, w: 5.25, h: 1.50, fill: TINTA, headColor: RUST,
    head: "Where it still fails",
    body: "Strongly associating fluids, whose reduced vapour-pressure curves are not straight, so a single slope parameter cannot represent them.",
    size: 13,
  });
}

// ==========================================================================
// 31. Part IV divider
// ==========================================================================
divider("PART IV", "The cubic era",
  "Chapter 8    Redlich-Kwong, 1949\nChapter 9    Soave-Redlich-Kwong, 1972\nChapter 10  Peng-Robinson, 1976, and the industrial standard",
  N("Set the industrial context. These three equations were developed by and for the petroleum and gas-processing industries, and their arrival coincides with the first commercial process simulators. The design constraint was never elegance; it was that the equation had to be solvable millions of times per flowsheet.",
    "Students assume the newest equation is always the best. In light-hydrocarbon service the differences among these three are often smaller than the uncertainty in the feed composition.",
    "What would you require of an equation of state before you would allow it inside the inner loop of a distillation column solver?"));

// ==========================================================================
// 32. Ch8 - Redlich-Kwong
// ==========================================================================
{
  const s = contentSlide({
    num: 8, title: "Redlich-Kwong, 1949: two changes at once",
    objective: "Identify the two independent modifications of the van der Waals attraction term and their separate effects.",
    tag: "Chapter 8  Redlich-Kwong",
    notes: N(
      "Insist that there are two changes, not one. Most textbooks present the temperature dependence and pass over the change in volume dependence, but the second is what moves the critical compressibility from 0.375 to 0.333 and improves the vapour phase.",
      "Students remember only the inverse square root of temperature. Ask them to write down the denominator from memory; most will write V squared, which is van der Waals.",
      "Why should an effective attraction weaken as temperature rises, given that the pair potential itself is temperature independent?"),
  });
  eqAt(s, "e_rk", 6.7, 2.175, 6.3, 1.15);
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, {
    x: M, y: 3.00, w: cw, h: 1.95, fill: TINTA, headColor: AMBERD,
    head: "Change 1   Temperature dependence",
    body: "The attraction is divided by the square root of temperature. Physically, at higher kinetic energy molecules spend less time in the attractive well, so the mean-field average of the attractive energy falls.",
    size: 13.5,
  });
  card(s, {
    x: M + cw + 0.34, y: 3.00, w: cw, h: 1.95, fill: TINTA, headColor: AMBERD,
    head: "Change 2   Volume dependence",
    body: "The denominator becomes V(V + b) rather than V squared. This softens the attraction at high density and lowers the predicted critical compressibility from 0.375 to 0.333.",
    size: 13.5,
  });
  eqAt(s, "e_rkab", 6.65, 5.75, 10.2, 1);
}

// ==========================================================================
// 33. Ch8 - alpha functions
// ==========================================================================
{
  const s = contentSlide({
    num: 8, title: "The temperature dependence of the attraction",
    objective: "Compare the alpha functions of the four classical cubics and see how each encodes a different physical assumption.",
    tag: "Chapter 8  Redlich-Kwong",
    notes: N(
      "This single figure summarises Chapters 3, 8, 9 and 10. Van der Waals is a horizontal line: no temperature dependence at all. Redlich-Kwong is a fixed power law, identical for every substance. Soave and Peng-Robinson add a substance-specific slope through the acentric factor. That is the whole story of the cubic era in one plot.",
      "Students think alpha is a fudge factor. It is the effective temperature dependence of the mean-field attraction, and its value at the critical temperature is fixed at one by construction so that the critical constants are preserved.",
      "Two fluids with different acentric factors share the same alpha at the critical temperature. Why must that be so?"),
  });
  image(s, fig("f20_alpha_functions"), { x: 3.50, y: 1.50, w: 6.35, h: 4.45 });
  eqAt(s, "e_alphadef", 6.65, 6.275, 5.6, 0.45);
  bullets(s, {
    x: M, y: 1.75, w: 2.75, h: 4.2, size: 13, items: [
      "van der Waals: constant, no temperature dependence.",
      "Redlich-Kwong: a fixed power law, the same for every substance.",
      "Soave: substance-specific through the acentric factor.",
      "Peng-Robinson: the same structure with a different coefficient set.",
    ],
  });
}

// ==========================================================================
// 34. Ch8 - what RK bought
// ==========================================================================
{
  const s = contentSlide({
    num: 8, title: "What Redlich-Kwong bought, and what it did not",
    objective: "Separate the genuine improvement in the vapour phase from the persistent failures in the liquid phase.",
    tag: "Chapter 8  Redlich-Kwong",
    notes: N(
      "State the diagnosis precisely. Redlich-Kwong contains no molecular parameter beyond the critical constants, so it necessarily assigns the same reduced vapour-pressure curve to every substance. In the language of Chapter 7 it has a single fixed acentric factor built in, close to 0.06.",
      "Students conclude that Redlich-Kwong was superseded because it was inaccurate. It was superseded because it was structurally incapable of distinguishing substances, which is a different and more serious defect.",
      "If Redlich-Kwong behaves as though every fluid had an acentric factor of about 0.06, for which real substances will it perform best?"),
  });
  image(s, fig("f19_rk_vs_vdw"), { x: 3.55, y: 1.48, w: 6.25, h: 4.00 });
  chips(s,
    "The vapour-phase compressibility improves substantially: errors of several per cent under van der Waals fall to about one per cent for simple fluids.",
    "Liquid densities remain poor and vapour pressures remain wrong for anything but simple fluids, because no molecular shape or polarity parameter enters the equation.",
    5.62);
}

// ==========================================================================
// 35. Ch9 - Soave
// ==========================================================================
{
  const s = contentSlide({
    num: 9, title: "Soave 1972: fit the temperature dependence to reality",
    objective: "Replace the assumed power law by an alpha function regressed against experimental vapour pressures.",
    tag: "Chapter 9  Soave-Redlich-Kwong",
    notes: N(
      "Explain the regression procedure explicitly: for each of a set of hydrocarbons, choose alpha at each temperature so that the isofugacity condition reproduces the measured vapour pressure, then correlate the resulting slope parameter against the acentric factor. The physics enters through the choice of what to fit, not through the functional form.",
      "Students see this as pure empiricism replacing theory. It is a deliberate reallocation of the modelling effort: the volumetric behaviour is left to the cubic structure, and the fitted freedom is spent where it buys phase equilibrium.",
      "Why fit alpha to vapour pressure rather than to density? What does that choice say about the intended application?"),
  });
  eqAt(s, "e_srk", 6.7, 2.14, 5.9, 1.12);
  eqAt(s, "e_srkalpha", 6.65, 3.245, 9.1, 0.65);
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, {
    x: M, y: 3.90, w: cw, h: 2.35, fill: TINTA, headColor: AMBERD,
    head: "The new physics",
    body: "Molecular shape and polarity enter the equation of state for the first time, through the acentric factor, and they enter the attraction term where they physically belong.\n\nAlpha equals one at the critical temperature by construction, so the critical constants are preserved exactly.",
    size: 13.5,
  });
  card(s, {
    x: M + cw + 0.34, y: 3.90, w: cw, h: 2.35, fill: TINT,
    head: "Why this was decisive",
    body: "Vapour pressures became quantitative for hydrocarbons, and therefore so did equilibrium ratios. This is the point at which process simulation of hydrocarbon separations became reliable enough for design rather than for checking.",
    size: 13.5,
  });
}

// ==========================================================================
// 36. Ch9 - impact on vapour pressure
// ==========================================================================
{
  const s = contentSlide({
    num: 9, title: "The effect on predicted vapour pressure",
    objective: "Quantify the improvement Soave's alpha function delivers relative to the fixed Redlich-Kwong power law.",
    tag: "Chapter 9  Soave-Redlich-Kwong",
    notes: N(
      "State clearly that the reference curve here is the Soave result itself, not experimental data, so the figure shows the size of the model change rather than an absolute error. The Redlich-Kwong deviation exceeding thirty per cent at low reduced temperature is the quantity to remember.",
      "Students read a thirty per cent vapour-pressure error as tolerable. In a multistage separation it compounds: a thirty per cent error in the equilibrium ratio of a key component changes the required number of stages substantially.",
      "The deviation is largest at low reduced temperature and vanishes at the critical point. Why must it vanish there?"),
  });
  image(s, fig("f21_srk_psat"), { x: 3.55, y: 1.48, w: 6.25, h: 4.00 });
  chips(s,
    "The fixed power law of Redlich-Kwong is equivalent to assigning every substance the same acentric factor. Soave's regression removes that constraint.",
    "Deviations exceeding thirty per cent at low reduced temperature translate directly into equilibrium-ratio errors, and therefore into stage counts and reflux ratios.",
    5.62);
}

// ==========================================================================
// 37. Ch10 - Peng-Robinson
// ==========================================================================
{
  const s = contentSlide({
    num: 10, title: "Peng-Robinson 1976: repair the volume dependence",
    objective: "Identify the change in the denominator, its effect on the critical compressibility, and the resulting cubic in Z.",
    tag: "Chapter 10  Peng-Robinson",
    notes: N(
      "Emphasise the division of labour across three chapters. Redlich-Kwong changed the temperature dependence and the volume dependence together. Soave repaired the temperature dependence properly. Peng and Robinson then repaired the volume dependence properly, which is what liquid density depends on.",
      "That Peng-Robinson is simply Soave with different constants. The denominator is structurally different, giving the two roots one plus and one minus the square root of two, and that is what shifts the critical compressibility to 0.307.",
      "The critical compressibility moves from 0.333 to 0.307 against a real range of 0.23 to 0.29. Is that a solution or an improvement?"),
  });
  eqAt(s, "e_pr", 6.65, 2.155, 6.6, 1.15);
  eqAt(s, "e_prab", 6.65, 3.425, 10.2, 0.95);
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, {
    x: M, y: 4.05, w: cw, h: 1.62, fill: TINTA, headColor: AMBERD,
    head: "The new physics",
    body: "A softer, longer-ranged effective attraction at high density, which is what a real liquid experiences. The critical compressibility falls to 0.3074, much closer to the measured range.",
    size: 13.5,
  });
  card(s, { x: M + cw + 0.34, y: 4.05, w: cw, h: 1.62, fill: TINT, head: "Reduced to a cubic in Z, solved analytically" });
  card(s, { x: M, y: 5.82, w: W - 2 * M, h: 1.02, fill: TINT });
  eqAt(s, "e_prcubic", 4.85, 6.33, 7.6, 0.62);
  eqAt(s, "e_ab", 10.55, 6.33, 3.1, 0.78);
}

// ==========================================================================
// 38. Ch10 - liquid density and envelope
// ==========================================================================
{
  const s = contentSlide({
    num: 10, title: "Liquid density: the reason Peng-Robinson won",
    objective: "Compare saturated liquid volumes and coexistence envelopes from Soave and Peng-Robinson.",
    tag: "Chapter 10  Peng-Robinson",
    notes: N(
      "Give the number: Peng-Robinson predicts saturated liquid volumes roughly eleven to twelve per cent smaller than Soave across the subcritical range for propane. That is close to the size of the Soave error, which is why the change was adopted so quickly.",
      "Students expect the improvement to appear in the vapour phase as well. It does not, in any important way. The two equations are nearly indistinguishable for vapour, and the choice between them is decided almost entirely by the liquid.",
      "You are sizing a pump for a saturated hydrocarbon liquid. How much does an eleven per cent volume error change the required duty, and what else does it change?"),
  });
  image(s, fig("f22_pr_liquid_density"), { x: 0.62, y: 1.60, w: 6.05, h: 4.4 });
  image(s, fig("f23_pvt_envelope_compare"), { x: 6.90, y: 1.60, w: 5.85, h: 4.4 });
  caption(s, "Left: saturated liquid molar volume of propane. Right: the coexistence envelope in density-temperature coordinates. The two models agree closely on the vapour branch and differ systematically on the liquid branch.", { x: M, y: 6.10, w: W - 2 * M });
}

// ==========================================================================
// 39. Ch10 - comparison
// ==========================================================================
{
  const s = contentSlide({
    num: 10, title: "van der Waals, Redlich-Kwong, Soave and Peng-Robinson compared",
    objective: "Assess the four classical cubics on the criteria that actually decide model selection in industry.",
    tag: "Chapter 10  Peng-Robinson",
    notes: N(
      "Read the last column aloud: computational cost is excellent for all four. That is why the family survived a century. Then read the polar and associating column: none. That is why Chapter 11 exists.",
      "Students look for the single best equation. The table has no best row, only a best row for a given column. Model selection is the identification of which column your problem lives in.",
      "Your feed is a wet natural gas containing methanol as a hydrate inhibitor. Which column decides your choice, and does any row satisfy it?"),
  });
  image(s, fig("f24_model_compare"), { x: 1.85, y: 1.52, w: 9.6, h: 4.00 });
  chips(s,
    "Each row adds one piece of physics and each addition shows up in exactly one or two columns. No row adds physics that improves every column at once.",
    "The final column explains the persistence of the family: all four are solvable analytically or in a few Newton steps, which is what an inner-loop model must be.",
    5.62);
}

// ==========================================================================
// 40. Ch10 - why PR is the standard
// ==========================================================================
{
  const s = contentSlide({
    num: 10, title: "Why Peng-Robinson became the industrial standard",
    objective: "Explain the adoption of Peng-Robinson in engineering rather than purely scientific terms, and name the standard patches.",
    tag: "Chapter 10  Peng-Robinson",
    notes: N(
      "Stress the third bullet. The parameters required are only the critical temperature, the critical pressure and the acentric factor, all of which are tabulated for essentially every industrial compound. A more accurate model requiring parameters nobody has measured is not usable in a design office.",
      "That industrial adoption tracks scientific accuracy. It tracks accuracy per unit of parameter availability and computational cost. Peng-Robinson is the optimum of that ratio for hydrocarbon processing.",
      "Volume translation improves liquid density at the cost of one fitted constant per compound. Under what circumstances is that trade worth making?"),
  });
  const cw = (W - 2 * M - 0.34) / 2;
  bullets(s, {
    x: M, y: 1.68, w: cw, h: 3.1, size: 14, items: [
      "Adequate for both phases across the ranges of oil and gas processing.",
      "Analytic cubic solution, so it is fast and robust inside iterative solvers.",
      "Requires only critical temperature, critical pressure and acentric factor, which are tabulated for essentially every industrial compound.",
      "Well understood mixing rules and a long record of validated binary interaction parameters.",
    ],
  });
  card(s, {
    x: M + cw + 0.34, y: 1.68, w: cw, h: 1.55, fill: TINT,
    head: "Standard patch 1   Volume translation",
    body: "Peneloux and co-workers, 1982: a constant volume shift per compound that corrects liquid density without disturbing the predicted vapour-liquid equilibrium.",
    size: 13,
  });
  card(s, {
    x: M + cw + 0.34, y: 3.38, w: cw, h: 1.42, fill: TINT,
    head: "Standard patch 2   Mathias-Copeman alpha",
    body: "A three-constant alpha function fitted per compound, used when vapour pressures of polar species must be reproduced accurately.",
    size: 13,
  });
  card(s, {
    x: M, y: 5.05, w: W - 2 * M, h: 1.25, fill: TINTA, headColor: RUST,
    head: "The cost of every patch, and the limit of the family",
    body: "Each patch buys accuracy with an additional fitted constant per compound, so predictive power for new molecules is not improved. No amount of patching introduces chain connectivity, hydrogen bonding or electrostatics, because none of those quantities appears anywhere in a cubic equation.",
    size: 13.5,
  });
}

// ==========================================================================
// 41. Ch10 - working with PR
// ==========================================================================
{
  const s = contentSlide({
    num: 10, title: "Working with Peng-Robinson in practice",
    objective: "Assemble the three expressions needed for a flash calculation and identify the most common practical error.",
    tag: "Chapter 10  Peng-Robinson",
    notes: N(
      "Root selection is the single most common source of wrong answers in student and industrial EOS code. Below the critical temperature the cubic can return three real roots; the middle one is always discarded, and the choice between the outer two must be made by comparing the fugacity coefficient, not by assuming which phase you expect.",
      "That the largest root is always the vapour and the smallest is always the liquid, so one can be chosen by inspection. The roots exist regardless of which phase is thermodynamically stable; only the fugacity comparison identifies the stable one.",
      "Your flash returns three real roots at 350 K and 10 bar. Which do you use, and what calculation decides it?"),
  });
  eqAt(s, "e_prphi", 6.65, 2.08, 9.4, 0.95);
  eqAt(s, "e_amix", 6.65, 3.12, 9.4, 0.86);
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, {
    x: M, y: 3.72, w: cw, h: 2.55, fill: TINTA, headColor: RUST,
    head: "The most common practical error",
    body: "Selecting the wrong root of the cubic. Below the critical temperature there may be three real roots; the middle root is mechanically unstable and always discarded, and the choice between the smallest and the largest must be made by comparing the fugacity coefficient, never by assumption.\n\nA wrong root gives an answer that is not slightly wrong but wrong by the density ratio between a liquid and a vapour.",
    size: 13.5,
  });
  card(s, {
    x: M + cw + 0.34, y: 3.72, w: cw, h: 2.55, fill: TINT,
    head: "Mixtures",
    body: "The van der Waals one-fluid mixing rules reduce a mixture to a pseudo-pure component. The binary interaction parameter is fitted to binary vapour-liquid equilibrium data and is the only adjustable quantity.\n\nSetting it to zero is a defensible default for similar hydrocarbons and is not defensible for a hydrocarbon with carbon dioxide, water or an alcohol.",
    size: 13.5,
  });
}

// ==========================================================================
// 42. Part V divider
// ==========================================================================
divider("PART V", "The molecular era",
  "Chapter 11   SAFT and the statistical associating fluid theory\nChapter 12   Electrolyte equations of state\nChapter 13   Future directions",
  N("Announce the change of construction. Everything so far wrote down a pressure explicitly. From here the models write down a residual Helmholtz energy as a sum of physically separable terms and obtain the pressure by differentiation. That change is what makes it possible to add one physical effect at a time.",
    "Students expect SAFT to be a more complicated cubic. It is a different construction with a different reference fluid, and its parameters have molecular meaning that cubic parameters do not.",
    "If you could add one term to a cubic equation to describe an alcohol, what physics would you put in it?"));

// ==========================================================================
// 43. Ch11 - the construction
// ==========================================================================
{
  const s = contentSlide({
    num: 11, title: "SAFT: a different construction",
    objective: "Contrast writing down a pressure with writing down a residual Helmholtz energy as a sum of separable contributions.",
    tag: "Chapter 11  SAFT",
    notes: N(
      "Make the methodological point explicit. Because the Helmholtz energy is additive over physically distinct effects, terms can be added, removed or improved independently. That modularity is impossible in a cubic, where every effect is entangled in two parameters.",
      "Students ask which term is 'the equation of state'. All of them together are; the pressure is a derivative of the sum, so no single term is an equation of state on its own.",
      "Why is the Helmholtz energy the natural potential here rather than the Gibbs energy?"),
  });
  eqAt(s, "e_saftP", 6.65, 2.155, 6, 1.15);
  eqAt(s, "e_saft", 6.65, 3.225, 6.6, 0.55);
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, {
    x: M, y: 3.90, w: cw, h: 2.35, fill: TINT,
    head: "Wertheim 1984 to 1986",
    body: "First-order thermodynamic perturbation theory for fluids with highly directional attractive forces. This is the mathematics that makes hydrogen bonding tractable as a free-energy contribution rather than as a fitted correction.",
    size: 13.5,
  });
  card(s, {
    x: M + cw + 0.34, y: 3.90, w: cw, h: 2.35, fill: TINT,
    head: "Chapman and co-workers 1990, Gross and Sadowski 2001",
    body: "SAFT turned the theory into an engineering equation of state. PC-SAFT then perturbed about the hard-chain rather than the hard-sphere reference, which improved the description of long molecules substantially.",
    size: 13.5,
  });
}

// ==========================================================================
// 44. Ch11 - four terms
// ==========================================================================
{
  const s = contentSlide({
    num: 11, title: "Four terms, four pieces of physics",
    objective: "Attribute each Helmholtz contribution to a specific molecular mechanism and to the cubic-equation defect it repairs.",
    tag: "Chapter 11  SAFT",
    notes: N(
      "Map each panel back onto the earlier chapters. The hard-sphere term is the co-volume of Chapter 3 done correctly. The dispersion term is the attraction of Chapter 3 done correctly. The chain term replaces the acentric factor of Chapter 7 with an actual structural parameter. The association term has no counterpart anywhere in the cubic family.",
      "Students treat the association term as an optional extra. For water, alcohols, amines and acids it is the dominant contribution to the phase behaviour, not a correction.",
      "Which of the four terms would you delete first if you needed the model to run ten times faster, and what would you lose?"),
  });
  image(s, fig("f25_saft_terms"), { x: 0.70, y: 1.60, w: 11.9, h: 3.45 });
  const cw = (W - 2 * M - 0.90) / 4;
  const t = (i, head, body) => card(s, {
    x: M + i * (cw + 0.30), y: 5.20, w: cw, h: 1.55, fill: i === 3 ? TINTA : TINT,
    headColor: i === 3 ? AMBERD : NAVY, head, body, size: 11.5, headSize: 12.5,
  });
  t(0, "Hard sphere", "Excluded volume treated with the Carnahan-Starling result rather than a single constant b.");
  t(1, "Chain", "Connectivity of bonded segments. Replaces the acentric factor with a structural parameter.");
  t(2, "Dispersion", "Attraction between segments from perturbation theory rather than a mean field.");
  t(3, "Association", "Short-range directional bonding. No cubic equation contains this at all.");
}

// ==========================================================================
// 45. Ch11 - the terms in equations
// ==========================================================================
{
  const s = contentSlide({
    num: 11, title: "The terms in equations",
    objective: "Read each contribution and identify the molecular parameter it introduces.",
    tag: "Chapter 11  SAFT",
    notes: N(
      "Point at the packing fraction in the hard-sphere term and note that it depends only on segment number, segment diameter and density, with no fitted constant. Then point at the association strength and note that it contains two parameters with direct physical meaning: a bonding energy and a bonding volume.",
      "Students see five parameters and conclude SAFT is more empirical than a cubic. The opposite is closer to the truth: the parameters are transferable across homologous series, so a value regressed for one alkane predicts its neighbours.",
      "The fraction of unbonded sites is determined by a mass-action balance. What does that resemble from your chemical reaction engineering course?"),
  });
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, { x: M, y: 1.60, w: cw, h: 1.45, fill: TINT, head: "Hard-sphere reference (Carnahan-Starling)" });
  eqAt(s, "e_cs", (M + 0.35) + (2.5) / 2, 2.10 + 0.85 / 2, 2.5, 0.85);
  card(s, { x: M + cw + 0.34, y: 1.60, w: cw, h: 1.45, fill: TINT, head: "Chain formation" });
  eqAt(s, "e_chain", (M + cw + 0.70) + (3.5) / 2, 2.18 + 0.5 / 2, 3.5, 0.5);
  card(s, { x: M, y: 3.22, w: cw, h: 1.68, fill: TINTA, headColor: AMBERD, head: "Association (Wertheim TPT1)" });
  eqAt(s, "e_assoc", M + cw / 2, 4.26, cw - 0.5, 0.98);
  card(s, { x: M + cw + 0.34, y: 3.22, w: cw, h: 1.68, fill: TINTA, headColor: AMBERD, head: "Association strength" });
  eqAt(s, "e_delta", M + cw + 0.34 + cw / 2, 4.26, cw - 0.5, 0.98);
  card(s, {
    x: M, y: 5.08, w: W - 2 * M, h: 1.26, fill: TINT,
    head: "The five molecular parameters",
    body: "Segment number, segment diameter, segment energy, association energy and association volume. For an n-alkane series the segment number grows almost linearly with carbon number while the diameter and energy remain nearly constant, which is why SAFT extrapolates to polymers and cubics do not.",
    size: 13.5,
  });
}

// ==========================================================================
// 46. Ch11 - contributions and where cubics fail
// ==========================================================================
{
  const s = contentSlide({
    num: 11, title: "What the terms contribute, and what they buy",
    objective: "Judge the relative magnitude of each contribution and the class of systems on which the investment pays.",
    tag: "Chapter 11  SAFT",
    notes: N(
      "Both figures are labelled illustrative because they are not produced by a real SAFT implementation. Say so explicitly to the class; it is a useful lesson in reading figures critically, and the qualitative statements they make are nonetheless correct.",
      "Students conclude that SAFT should replace cubics everywhere. For a light hydrocarbon flash a cubic is faster, equally accurate and better parameterised. SAFT earns its cost on polymers, associating fluids and mixtures far from ideality.",
      "Name a stream in your own research or workplace for which you would pay the SAFT computational cost, and one for which you would not."),
  });
  image(s, fig("f26_saft_contributions"), { x: 0.62, y: 1.60, w: 6.05, h: 4.4 });
  image(s, fig("f27_saft_vs_cubic"), { x: 6.90, y: 1.60, w: 5.85, h: 4.4 });
  caption(s, "Both panels are schematic illustrations of the qualitative behaviour, not output from a validated SAFT implementation.", { x: M, y: 6.08, w: W - 2 * M });
}

// ==========================================================================
// 47. Ch12 - electrolytes, the physics
// ==========================================================================
{
  const s = contentSlide({
    num: 12, title: "Ions change the range of the forces",
    objective: "Recognise that Coulomb interactions are long ranged and require terms with no counterpart in a neutral-fluid model.",
    tag: "Chapter 12  Electrolyte equations of state",
    notes: N(
      "Contrast the ranges numerically. Dispersion falls off as the inverse sixth power of separation and is negligible beyond about one nanometre. The Coulomb interaction falls off as the inverse first power, so in a dilute solution an ion interacts with thousands of others simultaneously. No perturbation about a short-range reference can capture that.",
      "Students expect an electrolyte model to be a neutral model with an extra fitted parameter. The long-range term is structurally different and must be derived from the Poisson-Boltzmann equation or from the mean spherical approximation.",
      "The Debye length in a one molar aqueous solution is under one nanometre. What does that imply about the applicability of the Debye-Huckel limiting law in a battery electrolyte?"),
  });
  image(s, fig("f28_electrolyte_terms"), { x: 2.55, y: 1.50, w: 8.2, h: 3.80 });
  eqAt(s, "e_debye", 6.65, 5.95, 4.0, 1.12);
  caption(s, "The Debye screening length sets the range over which an ion feels the surrounding ionic atmosphere.", { x: M, y: 6.60, w: W - 2 * M });
}

// ==========================================================================
// 48. Ch12 - the Helmholtz sum
// ==========================================================================
{
  const s = contentSlide({
    num: 12, title: "The electrolyte Helmholtz sum",
    objective: "Add the electrostatic and solvation contributions to a molecular reference and identify what each one describes.",
    tag: "Chapter 12  Electrolyte equations of state",
    notes: N(
      "This slide is the direct payoff of the modular construction introduced in Chapter 11. Because the Helmholtz energy is additive, electrostatics can be added to an existing SAFT model without rederiving anything. That is exactly what ePC-SAFT does.",
      "That the Born term is a solvation correction of secondary importance. It is typically the largest single contribution to the free energy of an ion in solution, of the order of hundreds of kilojoules per mole.",
      "Which of these three terms would you expect to dominate at 0.001 molar, and which at 5 molar?"),
  });
  eqAt(s, "e_elec", 6.7, 1.875, 6.3, 0.55);
  const cw = (W - 2 * M - 0.60) / 3;
  card(s, {
    x: M, y: 2.45, w: cw, h: 1.90, fill: TINT, head: "Molecular reference",
    body: "Hard sphere, chain, dispersion and association terms describing the solvent and the uncharged part of the interactions, taken directly from SAFT.", size: 13,
  });
  card(s, {
    x: M + cw + 0.30, y: 2.45, w: cw, h: 1.90, fill: TINTA, headColor: AMBERD, head: "Born solvation",
    body: "The free energy of charging an ion inside a dielectric medium. Usually the largest single contribution, and strongly dependent on the ionic radius.", size: 13,
  });
  card(s, {
    x: M + 2 * (cw + 0.30), y: 2.45, w: cw, h: 1.90, fill: TINTA, headColor: AMBERD, head: "Ion-ion screening",
    body: "Debye-Huckel or the mean spherical approximation, describing the ionic atmosphere that screens each central charge.", size: 13,
  });
  eqAt(s, "e_born", 4.0, 5.14, 6.4, 1.02);
  eqAt(s, "e_dhll", 9.85, 5.14, 4.0, 0.78);
  card(s, {
    x: M, y: 5.85, w: W - 2 * M, h: 0.85, fill: TINT,
    body: "The Debye-Huckel expression is a limiting law, exact only as the ionic strength approaches zero. Battery and capture solvents operate one to three orders of magnitude above that limit, where ion pairing, hydration and the composition dependence of the dielectric constant all matter.",
    size: 13,
  });
}

// ==========================================================================
// 49. Ch12 - activity coefficients
// ==========================================================================
{
  const s = contentSlide({
    num: 12, title: "Concentrated solutions and the activity minimum",
    objective: "Explain the minimum and upturn in the mean ionic activity coefficient in terms of competing physics.",
    tag: "Chapter 12  Electrolyte equations of state",
    notes: N(
      "The upturn is the whole story of this chapter. Electrostatic screening alone predicts a monotonic decrease. The observed rise at high concentration comes from the depletion of free solvent as it is bound into hydration shells, and from short-range repulsion between hydrated ions. A purely electrostatic model cannot produce it at any level of parameterisation.",
      "Students believe more parameters in a Debye-Huckel-type expression would capture the upturn. They cannot, because the missing physics is solvation and excluded volume, not electrostatics.",
      "In a five molar aqueous salt solution, roughly what fraction of the water is in a primary hydration shell? What does that do to the activity of the solvent?"),
  });
  image(s, fig("f29_mean_activity"), { x: 3.55, y: 1.48, w: 6.25, h: 4.00 });
  chips(s,
    "Screening lowers the activity coefficient. Solvent depletion and hydrated-ion repulsion raise it. The minimum is where the two mechanisms balance.",
    "Salt solubility limits, low-temperature precipitation in battery electrolytes and amine degradation in capture solvents all depend on the region beyond the minimum.",
    5.62);
}

// ==========================================================================
// 50. Ch12 - battery electrolytes
// ==========================================================================
{
  const s = contentSlide({
    num: 12, title: "Application: battery electrolytes",
    objective: "Map electrolyte thermodynamic outputs onto the design targets of an electrochemical cell.",
    tag: "Chapter 12  Electrolyte equations of state",
    notes: N(
      "Connect this to the students' own work. Battery electrolytes routinely operate at one molar and above, and water-in-salt and localised high-concentration formulations run far beyond that, where almost every solvent molecule is coordinated to an ion. The dilute-solution intuitions taught in undergraduate physical chemistry are simply not applicable.",
      "That transport and thermodynamics are separate problems. Activity coefficients enter the driving force for transport, so a thermodynamic error propagates directly into a predicted transference number and into the interpretation of an impedance spectrum.",
      "If your model underestimates the activity coefficient of the salt by twenty per cent, which measured cell quantity would reveal the error first?"),
  });
  image(s, fig("f30_battery_electrolyte"), { x: 1.55, y: 1.52, w: 10.2, h: 3.90 });
  chips(s,
    "The solvation shell is the physical object that connects thermodynamics, transport and interfacial chemistry in a cell. An equation of state that resolves it describes all three consistently.",
    "Voltage window, solid-electrolyte-interphase chemistry, salt precipitation risk and low-temperature operating limit are all set by properties an electrolyte equation of state can compute.",
    5.62);
}

// ==========================================================================
// 51. Ch13 - future directions
// ==========================================================================
{
  const s = contentSlide({
    num: 13, title: "Where the subject is going",
    objective: "Identify the four active research directions and the specific limitation each one addresses.",
    tag: "Chapter 13  Future directions",
    notes: N(
      "Frame each direction as a response to a limitation named earlier in the course. Molecular simulation supplies reference data where experiments do not exist. Machine learning addresses functional-form rigidity. Consistency constraints address the fact that a flexible model can violate thermodynamics. Electrochemical thermodynamics addresses the coupling ignored in Chapter 12.",
      "Students assume machine learning will replace physical models. The productive architectures learn the residual Helmholtz energy subject to physical constraints, which is a physical model with a flexible functional form, not a replacement for physics.",
      "Which of these four directions is most relevant to your own thesis, and what limitation of the models you currently use would it remove?"),
  });
  image(s, fig("f31_future_map"), { x: 2.55, y: 1.50, w: 8.2, h: 3.95 });
  chips(s,
    "Each direction targets a specific gap: missing data, rigid functional form, unenforced thermodynamic consistency, or unmodelled electrochemical coupling.",
    "The practical near-term gain is parameter estimation for compounds that have never been measured, which is the binding constraint in specialty chemicals and in new battery chemistries.",
    5.62);
}

// ==========================================================================
// 52. Ch13 - physics-informed ML
// ==========================================================================
{
  const s = contentSlide({
    num: 13, title: "Physics-informed machine learning equations of state",
    objective: "Describe an architecture that learns a Helmholtz function under hard thermodynamic constraints.",
    tag: "Chapter 13  Future directions",
    notes: N(
      "The essential design choice is that the network outputs a scalar free energy and every property is obtained by differentiation. This guarantees that the predicted properties are mutually consistent, which a network that predicts pressure, enthalpy and fugacity independently cannot guarantee.",
      "Students expect the failure mode to be poor accuracy. Accuracy inside the training envelope is usually excellent. The failure mode is confident, unflagged extrapolation outside it, which is far more dangerous in a design calculation.",
      "How would you detect that such a model is extrapolating, and what should a process simulator do when it is?"),
  });
  image(s, fig("f32_ml_eos"), { x: 1.75, y: 1.52, w: 9.8, h: 3.15 });
  eqAt(s, "e_mlA", 6.65, 5.06, 8.4, 0.55);
  eqAt(s, "e_constraint", 6.65, 5.76, 6.6, 0.72);
  card(s, {
    x: M, y: 6.20, w: W - 2 * M, h: 0.86, fill: TINTA, headColor: RUST,
    body: "The honest failure mode is extrapolation. Inside the training envelope such models are accurate; outside it they remain confident and are not. Any deployment must include an explicit domain-of-validity check.",
    size: 13,
  });
}

// ==========================================================================
// 53. Closing - the hierarchy
// ==========================================================================
{
  const s = contentSlide({
    title: "Closing the argument",
    objective: "Restate the thesis of the course and convert it into a working rule for model selection.",
    tag: "Conclusion",
    notes: N(
      "Return to the first slide deliberately and read the thesis again. Then give the students the operational form: the question is never whether a model is accurate in the abstract, but whether the physics it contains is the physics of their problem.",
      "Students leave believing they should always use the most sophisticated model available. The correct rule is to use the simplest model that contains the physics of the problem, because every additional term costs parameters, computation and robustness.",
      "Take a system from your own research. Which rung of this ladder does it require, and can you defend that choice on physical grounds rather than on habit?"),
  });
  image(s, fig("f33_hierarchy"), { x: 0.85, y: 1.55, w: 5.6, h: 5.15 });
  bullets(s, {
    x: 6.85, y: 1.75, w: 5.85, h: 2.75, size: 14.5, items: [
      "Each rung adds one physical mechanism the rung below omitted.",
      "Each addition costs parameters, computation, or robustness.",
      "Height on the ladder is physical content, not accuracy for your problem.",
      "The correct model is the lowest rung that contains your physics.",
    ],
  });
  card(s, {
    x: 6.85, y: 4.70, w: 5.85, h: 2.00, fill: TINTA, headColor: AMBERD,
    head: "The rule to take away",
    body: "Do not ask whether an equation of state is accurate. Ask which physics it contains, and whether that physics is the physics of your problem. Every model in this course answers that question honestly if you know how to read it.",
    size: 14,
  });
}

// ==========================================================================
// 54. References
// ==========================================================================
{
  const s = contentSlide({
    title: "References and further reading",
    objective: "Locate the primary sources and the standard graduate texts for each part of the course.",
    tag: "Conclusion",
    notes: N(
      "Direct students to the primary papers, not only the textbooks. Soave 1972 and Peng and Robinson 1976 are each about five pages long and are entirely readable by a graduate student. Reading them is the fastest way to understand how modest and how well argued each contribution was.",
      "That the original papers are too difficult to read. The cubic-equation papers in particular are short, concrete and far clearer than most textbook accounts of them.",
      "Read Peng and Robinson 1976 before the next session and identify, in their own words, the single defect of Soave they set out to repair."),
  });
  const cw = (W - 2 * M - 0.34) / 2;
  card(s, {
    x: M, y: 1.62, w: cw, h: 4.85, fill: TINT, head: "Graduate texts",
    body: "Smith, Van Ness, Abbott and Swihart, Introduction to Chemical Engineering Thermodynamics, 9th edition, 2022.\n\nPrausnitz, Lichtenthaler and de Azevedo, Molecular Thermodynamics of Fluid-Phase Equilibria, 3rd edition, 1999.\n\nPoling, Prausnitz and O'Connell, The Properties of Gases and Liquids, 5th edition, 2001.\n\nSandler, Chemical, Biochemical, and Engineering Thermodynamics, 5th edition, 2017.\n\nKontogeorgis and Folas, Thermodynamic Models for Industrial Applications, 2010.",
    size: 12.5,
  });
  card(s, {
    x: M + cw + 0.34, y: 1.62, w: cw, h: 4.85, fill: TINT, head: "Primary literature",
    body: "van der Waals, doctoral thesis, Leiden, 1873.\n\nRedlich and Kwong, Chemical Reviews 44 (1949) 233.\n\nPitzer and co-workers, Journal of the American Chemical Society 77 (1955) 3427 and 3433.\n\nSoave, Chemical Engineering Science 27 (1972) 1197.\n\nPeng and Robinson, Industrial and Engineering Chemistry Fundamentals 15 (1976) 59.\n\nWertheim, Journal of Statistical Physics 35 (1984) 19 and 35; 42 (1986) 459 and 477.\n\nChapman, Gubbins, Jackson and Radosz, Industrial and Engineering Chemistry Research 29 (1990) 1709.\n\nGross and Sadowski, Industrial and Engineering Chemistry Research 40 (2001) 1244.",
    size: 12.5,
  });
}

pres.writeFile({ fileName: OUT }).then(() => console.log("wrote", OUT, "slides:", SLIDE_NO));
