{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Thermodynamic processes\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/thermodynamic-processes). This notebook includes the lesson text and its Python examples in reading order. Run the setup cell, then run the remaining cells from top to bottom. In Colab, use File → Save a copy in Drive to keep your edits. You can run and edit this view without changing the course source. Examples use illustrative data unless stated otherwise."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-001",
      "metadata": {},
      "source": [
        "import importlib.metadata\n",
        "import subprocess\n",
        "import sys\n",
        "\n",
        "requirements = {\"numpy\": (2, 0), \"sympy\": (1, 13), \"matplotlib\": (3, 8)}\n",
        "to_install = []\n",
        "for package, minimum in requirements.items():\n",
        "    try:\n",
        "        installed = importlib.metadata.version(package)\n",
        "        version = tuple(int(part) for part in installed.split(\".\")[:2])\n",
        "    except importlib.metadata.PackageNotFoundError:\n",
        "        version = (0, 0)\n",
        "    if version < minimum:\n",
        "        to_install.append(f\"{package}>={minimum[0]}.{minimum[1]}\")\n",
        "if to_install:\n",
        "    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", *to_install])\n",
        "\n",
        "import numpy as np\n",
        "import sympy as sp\n",
        "import matplotlib\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "print(\"Python\", sys.version.split()[0])\n",
        "print(\"NumPy\", np.__version__)\n",
        "print(\"SymPy\", sp.__version__)\n",
        "print(\"Matplotlib\", matplotlib.__version__)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-002",
      "metadata": {},
      "source": [
        "A thermodynamic state is described by macroscopic variables such as pressure, volume,\n",
        "temperature, composition, and internal energy. A process is a path through those states.\n",
        "Names such as isothermal, isobaric, isochoric, and adiabatic state which quantity or\n",
        "transfer is constrained; they do not fully specify every real process.\n",
        "\n",
        "## State variables are constrained\n",
        "\n",
        "For $n$ moles of an ideal\n",
        "gas,\n",
        "\n",
        "\n",
        "$$\n",
        "pV=nRT\n",
        "$$\n",
        "\n",
        "\n",
        "where $p$,\n",
        "$V$,\n",
        "$T$, and\n",
        "$R$ describe an equilibrium state.\n",
        "Once $n$ is fixed, only two of\n",
        "$p$,\n",
        "$V$, and\n",
        "$T$ can be chosen independently.\n",
        "\n",
        "The ideal-gas law is a model for dilute gases. It is not a process equation and does not\n",
        "say how much heat or work occurred. Two paths can connect the same endpoint states while\n",
        "having different heat and work.\n",
        "\n",
        "This lesson uses heat into the gas as positive and work done by the gas as positive:\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta U=Q-W\n",
        "$$\n",
        "\n",
        "\n",
        "For an ideal gas, internal energy depends only on temperature. If molar heat capacity at\n",
        "constant volume $C_V$\n",
        "is constant over the range,\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta U=nC_V(T_f-T_i)\n",
        "$$\n",
        "\n",
        "\n",
        "## Isochoric: constant volume\n",
        "\n",
        "An isochoric process keeps\n",
        "$V$ fixed. There is no\n",
        "pressure–volume boundary work:\n",
        "\n",
        "\n",
        "$$\n",
        "W=\\int p_{\\mathrm{ext}}\\,dV=0\n",
        "$$\n",
        "\n",
        "\n",
        "Therefore $Q=\\Delta U$\n",
        "under the chosen convention when no other work mode is present. For an ideal gas at fixed\n",
        "amount and volume, pressure is proportional to absolute temperature:\n",
        "\n",
        "\n",
        "$$\n",
        "\\frac{p_f}{p_i}=\\frac{T_f}{T_i}\n",
        "$$\n",
        "\n",
        "\n",
        "The formula requires kelvin. Celsius ratios do not preserve the ideal-gas proportionality.\n",
        "\n",
        "## Isobaric: constant pressure\n",
        "\n",
        "An isobaric quasistatic process keeps pressure\n",
        "$p$ fixed. Its pressure–volume work\n",
        "is\n",
        "\n",
        "\n",
        "$$\n",
        "W=p(V_f-V_i)\n",
        "$$\n",
        "\n",
        "\n",
        "At fixed amount of ideal gas,\n",
        "$V/T$ is constant. Heating\n",
        "usually raises both internal energy and volume, so\n",
        "\n",
        "\n",
        "$$\n",
        "Q=\\Delta U+W=nC_P(T_f-T_i)\n",
        "$$\n",
        "\n",
        "\n",
        "when $C_P$ is\n",
        "constant and pressure–volume work is the only work. For an ideal gas,\n",
        "$C_P-C_V=R$.\n",
        "\n",
        "## Isothermal: constant temperature\n",
        "\n",
        "An isothermal process keeps\n",
        "$T$ fixed. For an ideal gas,\n",
        "$\\Delta U=0$.\n",
        "Along a reversible or quasistatic path,\n",
        "\n",
        "\n",
        "$$\n",
        "p(V)=\\frac{nRT}{V}\n",
        "$$\n",
        "\n",
        "\n",
        "and the work done by the gas is\n",
        "\n",
        "\n",
        "$$\n",
        "W=nRT\\ln\\left(\\frac{V_f}{V_i}\\right)\n",
        "$$\n",
        "\n",
        "\n",
        "The first law then gives $Q=W$.\n",
        "During expansion, the gas absorbs heat to replace the work it performs. This conclusion is\n",
        "specific to ideal-gas internal energy and constant temperature. A real gas can have\n",
        "interaction energy that changes during an isothermal volume change.\n",
        "\n",
        "## Adiabatic: no heat transfer\n",
        "\n",
        "An adiabatic process has $Q=0$. It does\n",
        "not necessarily have constant temperature. The first law becomes\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta U=-W\n",
        "$$\n",
        "\n",
        "\n",
        "A quasistatic reversible ideal-gas process with constant heat capacities obeys\n",
        "\n",
        "\n",
        "$$\n",
        "pV^\\gamma=\\mathrm{constant},\\qquad TV^{\\gamma-1}=\\mathrm{constant},\\qquad \\gamma=\\frac{C_P}{C_V}\n",
        "$$\n",
        "\n",
        "\n",
        "Expansion cools the gas and compression heats it under these assumptions. The work can be\n",
        "written\n",
        "\n",
        "\n",
        "$$\n",
        "W=\\frac{p_iV_i-p_fV_f}{\\gamma-1}=nC_V(T_i-T_f)\n",
        "$$\n",
        "\n",
        "\n",
        "These formulas are not consequences of\n",
        "$Q=0$ alone. Free expansion into a\n",
        "vacuum can be adiabatic with zero external pressure and therefore zero work. For an ideal\n",
        "gas, the first law then gives no temperature change, even though the process is\n",
        "irreversible and does not follow $pV^\\gamma=\\mathrm{constant}$.\n",
        "\n",
        "## Quasistatic and reversible are not synonyms\n",
        "\n",
        "A quasistatic process proceeds slowly enough that the system passes through states close\n",
        "to equilibrium, allowing a path to be drawn in equilibrium state space. Reversible is\n",
        "stronger: the process must be restorable by an infinitesimal change without net entropy\n",
        "production in system plus surroundings.\n",
        "\n",
        "Friction, viscosity, finite temperature differences, unrestrained expansion, electrical\n",
        "resistance, and mixing make processes irreversible. Moving slowly can reduce some\n",
        "departures from equilibrium, but it does not remove dry friction or diffusion.\n",
        "\n",
        "When work is evaluated from a quasistatic gas path, gas pressure approximates external\n",
        "pressure. For a rapid irreversible process, work still depends on external force or\n",
        "pressure, but one uniform gas pressure may not exist.\n",
        "\n",
        "## Reading a pressure–volume diagram\n",
        "\n",
        "A point on a pressure–volume diagram represents an equilibrium state only when the system\n",
        "is describable by one pressure and volume. An oriented curve represents a process. The\n",
        "signed work done by the gas is the area under the path:\n",
        "\n",
        "\n",
        "$$\n",
        "W=\\int_{V_i}^{V_f}p_{\\mathrm{ext}}\\,dV\n",
        "$$\n",
        "\n",
        "\n",
        "Vertical paths have zero pressure–volume work. A clockwise closed loop has positive net\n",
        "work by the gas under the usual axes; a counterclockwise loop has negative net work.\n",
        "Area is energy because\n",
        "$\\mathrm{Pa\\,m^3}=\\mathrm J$.\n",
        "\n",
        "## Building a process path"
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "amount, gas_constant, temperature = 1.0, 8.314462618, 300.0\n",
        "volumes = np.linspace(0.01, 0.02, 1001)\n",
        "pressures = amount * gas_constant * temperature / volumes\n",
        "assert np.allclose(pressures * volumes, amount * gas_constant * temperature)\n",
        "work_by = np.trapezoid(pressures, volumes)\n",
        "internal_energy_change = 0.0  # Isothermal ideal gas.\n",
        "heat_in = internal_energy_change + work_by\n",
        "exact = amount * gas_constant * temperature * np.log(volumes[-1] / volumes[0])\n",
        "print(f\"Work and heat: {work_by:.3f} J; exact work: {exact:.3f} J\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "The last line is the first law rearranged under the chosen convention. It does not identify\n",
        "the microscopic heat-transfer mechanism; it infers net heat only after the other energy\n",
        "terms are valid.\n",
        "\n",
        "## Comparing paths with the same endpoints\n",
        "\n",
        "Take an ideal gas from one equilibrium state to another. One route might first heat at\n",
        "constant volume and then expand at constant pressure. Another might follow a curved\n",
        "isothermal or polytropic path. If the endpoint temperatures match, both routes have the\n",
        "same $\\Delta U$.\n",
        "Their work and heat generally differ.\n",
        "\n",
        "This makes a strong code test. Generate two valid ordered paths with identical endpoints,\n",
        "integrate work on each, and compute heat from the first law. Require internal-energy change\n",
        "to agree while allowing transfer terms to differ.\n",
        "\n",
        "## Numerical and physical checks\n",
        "\n",
        "At every point, verify the equation of state and positivity of absolute pressure, volume,\n",
        "and temperature. For an isochoric fixture, require zero pressure–volume work. For an\n",
        "isothermal ideal-gas expansion, check that pressure falls inversely with volume, work is\n",
        "positive, and $Q=W$. For a\n",
        "reversible adiabatic fixture, check both invariant forms and compare work with the internal\n",
        "energy change.\n",
        "\n",
        "Refine path sampling. A trapezoidal work estimate should converge for a smooth path. Do\n",
        "not sort samples by volume: a real process can reverse direction, and sorting destroys its\n",
        "orientation and loop area. Report residuals and uncertainty rather than forcing endpoint\n",
        "data to fit an assumed path.\n",
        "\n",
        "Real processes can include phase transitions, reactions, leaks, changing composition,\n",
        "spatial gradients, turbulence, radiation, surface tension, and nonideal equations of\n",
        "state. A named textbook process is a controlled model, not a complete description of a\n",
        "machine.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "Trace an isothermal process for one mole of ideal gas at 300 kelvin. The question for this calculation is precise: how does **isothermal pressure**\n",
        "change when we change **volume**, while keeping the other choices fixed?\n",
        "The earlier sections explain the physical relationship. Here we turn one part of that\n",
        "relationship into a calculation that you can run, inspect, and change in Google Colab.\n",
        "\n",
        "An adiabatic process follows a different pressure-volume relation. Keep that sentence beside the results. A formula can return a number outside\n",
        "its useful range, and a plotting library will usually draw that number without asking\n",
        "whether the physical assumptions still hold. The selected interval is from\n",
        "0.005 to 0.03 m^3. It gives us a specific domain to discuss\n",
        "instead of leaving the graph's range to a software default.\n",
        "\n",
        "Use the notebook link above the lesson, run the setup cell, and then run the cells in\n",
        "order. The code below is also included there. NumPy handles the arrays of numerical\n",
        "values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these\n",
        "libraries or notebook cells are unfamiliar, start with\n",
        "[Your first physics notebook](https://tirta.co/a-byte-of-physics/your-first-physics-notebook).\n",
        "\n",
        "### State the relationship before choosing a graph\n",
        "\n",
        "In this small example, `q` stands for volume, expressed in m^3. The output is\n",
        "isothermal pressure, expressed in Pa. The equation below uses the numerical values in those\n",
        "units. Any fixed coefficients therefore carry the units needed to make the relation\n",
        "consistent. A value supplied in another unit must be converted before it enters this\n",
        "expression.\n",
        "\n",
        "\n",
        "$$\n",
        "f(q) = \\frac{2494.3387854}{q}\n",
        "$$\n",
        "\n",
        "\n",
        "This is a function of one changing input. It is not a statement that the physical\n",
        "system has only one variable. We deliberately hold the other inputs fixed so that one\n",
        "cause of variation is visible. Changing several inputs at once would make it harder\n",
        "to tell which change produced the output difference. Write down the held-fixed choices\n",
        "before trying a different experiment.\n",
        "\n",
        "At 0.01 m^3, the expression gives 249434 Pa. This is our\n",
        "reference calculation. It is a prediction of the stated example, not a new measurement.\n",
        "Its displayed digits help us compare implementations. They should not be read as a\n",
        "claim that physical inputs are known to six significant figures."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "import sympy as sp\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "q = sp.Symbol(\"q\", real=True)\n",
        "expression = sp.sympify(\"8.314462618*300/q\", locals={\"q\": q})\n",
        "reference_input = 0.01\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"m^3\")\n",
        "print(\"Predicted isothermal pressure:\", reference_output, \"Pa\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "`sp.Symbol` declares a mathematical symbol. It does not assign a numerical measurement\n",
        "to that symbol. `subs` then replaces the symbol with our chosen input, and `float`\n",
        "converts the resulting symbolic number into a standard Python numerical value.\n",
        "Keeping these steps separate lets us inspect the equation before numerical substitution.\n",
        "It also prevents a later plot from becoming the only surviving record of the model.\n",
        "\n",
        "### Compare a few cases you can explain\n",
        "\n",
        "Before drawing hundreds of points, calculate three. The lower endpoint gives\n",
        "498868 Pa. The midpoint, at 0.0175 m^3, gives\n",
        "142534 Pa. The upper endpoint gives 83144.6 Pa.\n",
        "Read these together with the assumptions: they describe different choices of volume\n",
        "within the same example, with the other inputs held fixed.\n",
        "\n",
        "These three values are a useful first check, but they do not establish the shape between\n",
        "them. Two endpoints can be equal even when the curve bends or oscillates in between.\n",
        "Likewise, a large change between endpoints does not tell us whether the relationship is\n",
        "linear. We need the equation and intermediate samples to answer those questions."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-007",
      "metadata": {},
      "source": [
        "evaluate = sp.lambdify(q, expression, modules=\"numpy\")\n",
        "inputs = np.array([0.005, 0.017499999999999998, 0.03])\n",
        "outputs = np.asarray(evaluate(inputs), dtype=float)\n",
        "outputs = np.broadcast_to(outputs, inputs.shape)\n",
        "for input_value, output_value in zip(inputs, outputs):\n",
        "    print(f\"{input_value:.6g} m^3 -> {output_value:.6g} Pa\")\n",
        "assert np.all(np.isfinite(outputs))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "metadata": {},
      "source": [
        "`lambdify` turns the symbolic expression into a numerical function. We explicitly select\n",
        "NumPy as its numerical backend so it can accept an array. The same expression now has\n",
        "two useful forms: one for algebra and one for calculating many cases. The assertion\n",
        "checks that the chosen inputs produce finite outputs. It would catch an infinity or an\n",
        "undefined numerical result, but a finite value can still be physically inappropriate.\n",
        "\n",
        "### Make a graph that answers the question\n",
        "\n",
        "The horizontal axis shows volume; the vertical axis shows isothermal pressure. Every plotted\n",
        "point is a prediction of the same expression. We mark the reference case separately\n",
        "so that a reader can connect the earlier printed value to its place on the curve.\n",
        "The axis labels include units because a shape without a scale cannot tell us the size\n",
        "of a physical effect."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-009",
      "metadata": {},
      "source": [
        "input_grid = np.linspace(0.005, 0.03, 301)\n",
        "output_grid = np.asarray(evaluate(input_grid), dtype=float)\n",
        "output_grid = np.broadcast_to(output_grid, input_grid.shape)\n",
        "fig, ax = plt.subplots(figsize=(7, 4))\n",
        "ax.plot(input_grid, output_grid, label=\"Stated model\")\n",
        "ax.scatter([reference_input], [reference_output], label=\"Reference case\", zorder=3)\n",
        "ax.set_xlabel(\"Volume (m^3)\")\n",
        "ax.set_ylabel(\"Isothermal pressure (Pa)\")\n",
        "ax.legend()\n",
        "ax.grid(alpha=0.25)\n",
        "fig.tight_layout()\n",
        "plt.show()\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-010",
      "metadata": {},
      "source": [
        "Look for a sign change, a turning point, or a region where the curve becomes steep.\n",
        "Connect each feature to the expression rather than to the colour of the line. If the\n",
        "curve has a minimum or maximum, changing the input in opposite directions may have\n",
        "similar effects on the output near that point. If it is nearly straight over a short\n",
        "interval, a local linear approximation may be useful even when the complete expression\n",
        "is nonlinear.\n",
        "\n",
        "Increasing the number of samples makes the line smoother and may reveal features that\n",
        "a coarse grid missed. It does not improve the physical inputs or enlarge the model's\n",
        "validity range. For quantities that can take only discrete values, use the line as a\n",
        "guide to the relationship and interpret only the allowed input values. A plotting\n",
        "function does not enforce such restrictions for you.\n",
        "\n",
        "### Measure the local sensitivity\n",
        "\n",
        "A derivative asks a more specific question than the whole graph: how quickly does\n",
        "isothermal pressure change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 0.01 m^3 is\n",
        "-2.49434e+07 in those ratio units. Locally, the output decreases as the\n",
        "input increases. This statement is local; the sign or size of the slope can be different\n",
        "elsewhere on the curve.\n",
        "\n",
        "\n",
        "$$\n",
        "f'(q) = - \\frac{2494.3387854}{q^{2}}\n",
        "$$\n",
        "\n",
        "\n",
        "For a small input change, multiply the derivative by that change to estimate the output\n",
        "change. Then compare that estimate with a fresh evaluation of the full expression.\n",
        "The distinction between these two calculations matters: the derivative gives a tangent\n",
        "approximation, while substitution evaluates the chosen expression at the new point."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-011",
      "metadata": {},
      "source": [
        "slope_expression = sp.diff(expression, q)\n",
        "slope_at_reference = float(slope_expression.subs(q, reference_input))\n",
        "changed_input = 0.010125\n",
        "linear_prediction = reference_output + slope_at_reference * (\n",
        "    changed_input - reference_input\n",
        ")\n",
        "full_prediction = float(evaluate(changed_input))\n",
        "print(\"Symbolic derivative:\", slope_expression)\n",
        "print(\"Tangent prediction:\", linear_prediction, \"Pa\")\n",
        "print(\"Full expression:\", full_prediction, \"Pa\")\n",
        "print(\"Approximation difference:\", full_prediction - linear_prediction, \"Pa\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-012",
      "metadata": {},
      "source": [
        "Here the changed input is 0.010125 m^3. The tangent estimate is\n",
        "246316 Pa, while the full expression gives\n",
        "246354 Pa. If the two values are close, it means the chosen\n",
        "input change is small enough for this local approximation at this point. It does not\n",
        "mean the entire model is linear. If the slope is zero, a quadratic or higher-order term\n",
        "may supply the leading change instead.\n",
        "\n",
        "This is also the beginning of uncertainty propagation. If the input has a small stated\n",
        "standard uncertainty, the magnitude of the slope times that uncertainty estimates one\n",
        "contribution to output uncertainty. Do not automatically use the same rule for a wide\n",
        "interval, a discontinuity, a turning point with zero first derivative, or several\n",
        "correlated uncertain inputs. Those situations need more of the model than one slope.\n",
        "\n",
        "### Check the derivative with numerical differences\n",
        "\n",
        "We can estimate the same slope from values on either side of the reference point.\n",
        "Subtract the lower output from the upper output and divide by twice the input step.\n",
        "Parentheses are essential: the entire output difference must be divided by the entire\n",
        "input interval. Without them, Python can execute a different mathematical expression\n",
        "while still producing a plausible number.\n",
        "\n",
        "The calculation below uses three decreasing step sizes. Each estimate is compared with\n",
        "the symbolic derivative, so the reference is independent of the numerical difference\n",
        "formula. Near an endpoint, it is acceptable here to evaluate a small extension only\n",
        "because the displayed mathematical expression is smooth there; such a check does not\n",
        "assert that extrapolated values describe additional physical cases."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-013",
      "metadata": {},
      "source": [
        "input_span = 0.024999999999999998\n",
        "for fraction in [1e-2, 1e-3, 1e-4]:\n",
        "    step = input_span * fraction\n",
        "    upper = float(evaluate(reference_input + step))\n",
        "    lower = float(evaluate(reference_input - step))\n",
        "    numerical_slope = (upper - lower) / (2 * step)\n",
        "    difference = numerical_slope - slope_at_reference\n",
        "    print(f\"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-014",
      "metadata": {},
      "source": [
        "For a smooth function, reducing the step often reduces the approximation error at first.\n",
        "Very small steps can eventually make subtraction of nearly equal floating-point values\n",
        "less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare\n",
        "the observed behaviour over a useful range of steps instead of choosing the smallest\n",
        "number the computer can represent.\n",
        "\n",
        "An absolute slope difference is useful when the expected slope is near zero. A relative\n",
        "difference would divide by a very small reference and could look enormous even when the\n",
        "absolute discrepancy is tiny. Away from zero, a relative difference can help compare\n",
        "quantities with very different scales. The tolerance should reflect the question and\n",
        "the numerical method, rather than a universal decimal threshold copied into every test.\n",
        "\n",
        "### Change the example and preserve the reasoning\n",
        "\n",
        "Make one copy of the reference calculation before editing it. Choose a second value of\n",
        "volume inside the stated interval, predict whether isothermal pressure will rise or fall,\n",
        "and then evaluate the expression. Place the prediction and the result in a text cell.\n",
        "If they disagree, identify whether the mistake was in the sign, the unit conversion,\n",
        "the algebra, or the assumption about how the curve behaves.\n",
        "\n",
        "Next choose a shorter plotting interval around the reference point. Compare the local\n",
        "curve with its tangent approximation. Then widen the interval again. The difference\n",
        "shows why a useful local estimate need not describe the whole range. Keep the axis\n",
        "labels and numerical scale visible when comparing the plots; automatic axis limits can\n",
        "make two different effects appear equally large.\n",
        "\n",
        "Finally, return to the physical limit stated at the start: An adiabatic process follows a different pressure-volume relation. Describe one change\n",
        "to the setup that would violate that limit. State what new input, equation, or observation\n",
        "would be needed before trusting an answer in the changed situation. This last step\n",
        "connects the Python experiment to the physics instead of treating successful execution\n",
        "as the only criterion for a useful result.\n",
        "\n",
        "Before saving, restart the runtime and run all cells in order. A result that depends on\n",
        "an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep\n",
        "unrounded values for later calculations, round only the reported output, and label any\n",
        "new data as measured, assumed, or generated. The graph and printed values should remain\n",
        "traceable to the same expression and the same choices of inputs.\n",
        "\n",
        "### Recover the output change by integrating the slope\n",
        "\n",
        "There is another way to check that the expression and its derivative describe the same\n",
        "relationship. Add up the small output changes predicted by the slope across the chosen\n",
        "input interval. In the continuous limit, this integral equals the output at the upper\n",
        "endpoint minus the output at the lower endpoint. The result has units of Pa:\n",
        "the input unit in the integration cancels the input unit in the denominator of the slope.\n",
        "\n",
        "This statement is about the mathematics of this particular relationship. It does not\n",
        "assign a new physical meaning to an arbitrary area under a graph. For example, an area\n",
        "under force versus distance represents work, while an area under a different pair of\n",
        "quantities may represent something else or have no standard name. Always carry the\n",
        "axis units through the calculation before naming an integral."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-015",
      "metadata": {},
      "source": [
        "slope_function = sp.lambdify(q, slope_expression, modules=\"numpy\")\n",
        "endpoint_change = float(evaluate(0.03) - evaluate(0.005))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(0.005, 0.03, points)\n",
        "    slopes = np.asarray(slope_function(grid), dtype=float)\n",
        "    slopes = np.broadcast_to(slopes, grid.shape)\n",
        "    integrated_change = np.trapezoid(slopes, grid)\n",
        "    print(\n",
        "        points,\n",
        "        \"integrated change:\",\n",
        "        integrated_change,\n",
        "        \"endpoint change:\",\n",
        "        endpoint_change,\n",
        "    )\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-016",
      "metadata": {},
      "source": [
        "The trapezoidal rule joins neighbouring slope samples with straight segments and adds\n",
        "their signed areas. A negative contribution remains negative; replacing every slope\n",
        "by its magnitude would calculate a different quantity. Increasing the sample count\n",
        "provides a practical refinement check. If the values do not settle toward the endpoint\n",
        "difference, first inspect the interval, singularities, and array ordering.\n",
        "\n",
        "Do not conclude that two agreeing calculations prove the model is physically complete.\n",
        "Both use the same selected relationship, so an omitted effect would be omitted from\n",
        "both. Their agreement is evidence that the numerical tools implement that relationship\n",
        "consistently. Comparing with an independent experiment or a more appropriate physical\n",
        "model is a separate test.\n",
        "\n",
        "Keep this comparison in the notebook when you change the expression. It is particularly\n",
        "useful after adding a coefficient, changing a sign convention, or converting an input\n",
        "unit. A code cell that produces a smooth graph can conceal these mistakes; a second\n",
        "calculation of the same output change gives you another place to notice them.\n",
        "\n",
        "## Sources\n",
        "\n",
        "- [OpenStax, *University Physics Volume 2*, Section 3.4, “Thermodynamic Processes”](https://openstax.org/books/university-physics-volume-2/pages/3-4-thermodynamic-processes).\n",
        "- [OpenStax, *University Physics Volume 2*, Section 3.6, “Adiabatic Processes for an Ideal Gas”](https://openstax.org/books/university-physics-volume-2/pages/3-6-adiabatic-processes-for-an-ideal-gas).\n",
        "- [MIT OpenCourseWare 8.01SC, Chapter 29, ideal-gas and thermodynamic-state discussion](https://ocw.mit.edu/courses/8-01sc-classical-mechanics-fall-2016/resources/mit8_01scs22_chapter29/).\n",
        "- [Benjamin Crowell, *Light and Matter*, pressure, volume, temperature, heat, and work](https://open.umn.edu/opentextbooks/textbooks/light-and-matter).\n",
        "- [The Physics Hypertextbook, “Pressure–Volume Diagrams”](https://physics.info/pressure-volume/)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "thermodynamic-processes.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/thermodynamic-processes",
      "source_sha256": "700bec30a41e3dfb602710ed51e359fe5d33e494dc138843171f9c856ba1cd51"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
