\section{Advanced tutorial: reconstructing an R134a air conditioner}
\label{sec:tutorial-r134a-air-conditioner}

This tutorial develops a complete graphical and numerical solution for a
real-fluid air conditioner. It focuses on the refrigeration process: the
working fluid, four device models, cycle construction, and energy balances.
Every diagram is generated by LuaCoolProp rather than imported as an image.

The exercise is more demanding than the R717 example in the preceding chapter.
The initial state is superheated rather than saturated, condensation ends at a
specified temperature rather than at an imposed quality, and the graphical
construction is built in stages.  We shall reproduce that reasoning while
making every thermodynamic assumption explicit and every computed value
reproducible.

\begin{LCPNote}[What the six generated pages show]
The executable file \texttt{tutorial/r134a-air-conditioner.tex} produces one
six-page PDF.  Pages 1 and 2 identify phase regions and the low-pressure
ideal-gas limit.  Pages 3, 4, and 5 construct states 1, 2, and 3 successively.
Page 6 introduces state 4, closes the cycle, projects the readings, and reports
values obtained directly from the process endpoint exports.
\end{LCPNote}

\subsection{Translate the statement into thermodynamic constraints}

The working fluid is R134a and the mass flow rate is
\(\dot m=0.1\,\mathrm{kg\,s^{-1}}\).  The four states and four device models
are:

\begin{center}
\begin{tabularx}{\textwidth}{@{}c l X@{}}
\toprule
State or path & Given data & Consequence in a PH diagram \\
\midrule
1 & $p_1=3\,\mathrm{bar}$, $T_1=5\,{}^\circ\mathrm C$ &
  Superheated-vapour state at the intersection of an isobar and an isotherm.\\
$1\to2$ & Isentropic compression, $p_2/p_1=6$ &
  $p_2=18\,\mathrm{bar}$ and $s_2=s_1$.\\
$2\to3$ & Isobaric cooling, $T_3=60\,{}^\circ\mathrm C$ &
  Horizontal path at $18\,\mathrm{bar}$ ending on the $60\,{}^\circ\mathrm C$
  isotherm.\\
$3\to4$ & Adiabatic throttle to $p_4=p_1$ &
  Steady-flow energy balance gives $h_4=h_3$, hence a vertical path.\\
$4\to1$ & Isobaric evaporation and superheating &
  Horizontal path at $3\,\mathrm{bar}$ returning to state 1.\\
\bottomrule
\end{tabularx}
\end{center}

This translation is the central modelling step.  Words such as
``isentropic'', ``isobaric'', and ``isenthalpic'' become the \key{type} values
passed to \macro{\LCPAddPHProcess}; no curve is drawn merely because it looks
similar to the expected correction.

\subsection{Use a stable plotting domain}

An initial worksheet spans a broad R134a domain.  The progressive correction
benefits from a closer view around the cycle, so all six generated pages share
the following axis:

\begin{LCPExample}{Common axis for every construction stage}
\LCPSetup{fluid=R134a}
\begin{tikzpicture}
\begin{axis}[
  lcp fluid=R134a,
  width=17cm,height=11cm,
  xmin=140,xmax=520,
  ymin=.7,ymax=55,ymode=log,
  xlabel={Specific enthalpy $h$ ($\mathrm{kJ\,kg^{-1}}$)},
  ylabel={Pressure $p$ (bar)},
  grid=both,clip mode=individual
]
  % One construction stage goes here.
\end{axis}
\end{tikzpicture}
\end{LCPExample}

The pressure range extends beyond both operating pressures and shows the top of
the saturation dome.  The enthalpy range leaves room for the compressed-vapour
state and for annotations.  Keeping identical limits across the sequence makes
movement from one construction to the next visually meaningful.

\subsection{Stage 1: identify the three phase regions}

The saturated-liquid and saturated-vapour boundaries are the two curves
generated by qualities 0 and 1.  They delimit subcooled liquid on the left,
liquid--vapour equilibrium below the dome, and superheated vapour on the right.
The two branches remain distinct at the low-pressure triple point and converge
to the single critical state at the top of the dome.  LuaCoolProp refines this
neighbourhood automatically and gives both curves the same canonical critical
endpoint, independently of the selected pure fluid.

\begin{LCPExample}{Saturation boundaries used as a phase map}
\LCPAddPHQuality[
  pressure min=70000,pressure max=5500000,
  quality values={0,1},
  quality boundary color=black,
  boundary style={line width=1pt},labels=false
]
\node at (axis cs:190,20) {subcooled liquid};
\node at (axis cs:310,5) {liquid--vapour equilibrium};
\node at (axis cs:455,12) {superheated vapour};
\end{LCPExample}

\IfFileExists{tutorial/r134a-air-conditioner.pdf}{%
  \begin{center}
    \includegraphics[page=1,width=.92\textwidth]
      {tutorial/r134a-air-conditioner.pdf}
  \end{center}
}{\begin{LCPWarning}[Advanced tutorial PDF not built]
Run \texttt{scripts/build-examples.sh} before compiling the manual.
\end{LCPWarning}}

Only phase labels are placed manually.  If isoline labels are enabled in an
adapted version, their automatic placement remains the exclusive responsibility
of \pkg{pgfplots-autonode}.

\subsection{Stage 2: recognize the ideal-gas region}

For an ideal gas, specific enthalpy depends only on temperature.  Isotherms and
isenthalps therefore coincide, and isotherms become nearly vertical in a PH
diagram.  Plotting a temperature family shows that this behaviour is approached
for sufficiently low-pressure superheated vapour, far to the right of the dome.

\begin{LCPExample}{Isotherms used as a diagnostic rather than decoration}
\LCPAddPHIsotherms[
  pressure min=70000,pressure max=5500000,
  temperature values={-40,-20,0,20,40,60,80,100,120,140,160},
  isotherm color=blue,
  isotherm style={line width=.45pt},labels=false
]
\end{LCPExample}

\begin{center}
  \includegraphics[page=2,width=.92\textwidth]
    {tutorial/r134a-air-conditioner.pdf}
\end{center}

This is a qualitative conclusion, not a sharp phase boundary.  The dashed box
on the generated page indicates where the isotherms are already close to
vertical over the displayed pressure interval.

\subsection{Stage 3: locate state 1 from two measured properties}

State 1 is defined by two independent properties. We name a $3\,\mathrm{bar}$ isobar and a
$5\,{}^\circ\mathrm C$ isotherm, then ask TikZ to find their intersection.
The neighbouring $0$ and $10\,{}^\circ\mathrm C$ isotherms provide a
graphical interpolation exercise.

\begin{LCPExample}{State 1 as an intersection of named thermodynamic paths}
\LCPAddPHProcess[
  type=isobar,pressure=3bar,
  from={temperature=-10C},to={temperature=20C},
  name=r134a-low-isobar]
\LCPAddPHProcess[
  type=isotherm,temperature=5C,
  from={pressure=2bar},to={pressure=5bar},
  name=r134a-state-one-isotherm,style={draw=none}]
\path[name intersections={of=r134a-low-isobar and
  r134a-state-one-isotherm,by=RAirOne}];
\fill (RAirOne) circle[radius=2pt];
\node[above right] at (RAirOne) {1};
\end{LCPExample}

\begin{center}
  \includegraphics[page=3,width=.92\textwidth]
    {tutorial/r134a-air-conditioner.pdf}
\end{center}

CoolProp gives $h_1=402.876\,\mathrm{kJ\,kg^{-1}}$ and
$s_1=1.74078\,\mathrm{kJ\,kg^{-1}\,K^{-1}}$.  A chart reading near
$403\,\mathrm{kJ\,kg^{-1}}$ is consistent with the resolution of the grid.

\subsection{Stage 4: construct the compressor outlet}

The compression ratio gives
\[
  p_2=6p_1=18\,\mathrm{bar}.
\]
The compressor is adiabatic and reversible in the model, so the path is an
isentrope.  The process command can compute its conserved entropy directly from
state 1:

\begin{LCPExample}{Isentropic compression from state 1 to state 2}
\LCPAddPHProcess[
  type=isentrope,
  from={pressure=3bar,temperature=5C},
  to={pressure=18bar},
  name=r134a-one-two,
  export coordinates=RAirOneTwo,
  color=red,
  style={line width=1.4pt,-{Latex[length=2.2mm]}}
]
\end{LCPExample}

As in the correction, two neighbouring isentropes at 1.70 and
$1.75\,\mathrm{kJ\,kg^{-1}\,K^{-1}}$ explain the graphical construction.
State 2 is the intersection of the named compression path and a named
$18\,\mathrm{bar}$ guide; it is not placed with an explicit coordinate.

\begin{center}
  \includegraphics[page=4,width=.92\textwidth]
    {tutorial/r134a-air-conditioner.pdf}
\end{center}

The exported macros give
\(h_2=441.019\,\mathrm{kJ\,kg^{-1}}\) and
\(T_2=346.205\,\mathrm K=73.05\,{}^\circ\mathrm C\). A hand reading of the
same chart at moderate resolution would give roughly
$440\,\mathrm{kJ\,kg^{-1}}$ and $73\,{}^\circ\mathrm C$.

\subsection{Stage 5: cool at constant pressure to state 3}

State 3 is fixed by $p_3=p_2=18\,\mathrm{bar}$ and
$T_3=60\,{}^\circ\mathrm C$.  The complete $2\to3$ path crosses the saturation
dome: it includes desuperheating, condensation, and a small subcooling region.
Using one isobaric process is physically clearer than splitting that continuous
heat-exchanger path merely to match the visual phases.

\begin{LCPExample}{The high-pressure heat-exchanger path}
\LCPAddPHProcess[
  type=isobar,pressure=18bar,
  from={entropy=1740.778583426JkgK},
  to={temperature=60C},
  name=r134a-two-three,
  export coordinates=RAirTwoThree,
  color=red,
  style={line width=1.4pt,-{Latex[length=2.2mm]}}
]
\end{LCPExample}

The explicit entropy in the initial-state specification is the full-precision
value calculated for state 1.  It makes the independently generated $1\to2$
and $2\to3$ paths meet exactly.  The TikZ intersection remains the sole source
of the displayed point position.

\begin{center}
  \includegraphics[page=5,width=.92\textwidth]
    {tutorial/r134a-air-conditioner.pdf}
\end{center}

The endpoint export gives
$h_3=287.411\,\mathrm{kJ\,kg^{-1}}$.  A graphical estimate near
$285\,\mathrm{kJ\,kg^{-1}}$ is consistent with the limited precision of a
printed chart.

\subsection{Stage 6: throttle, close the cycle, and locate state 4}

For a steady, adiabatic throttle with no useful shaft work and negligible
changes in kinetic and potential energy, the open-system first law gives
\(h_4=h_3\).  In PH coordinates the path is therefore vertical.

\begin{LCPExample}{Expansion and low-pressure return}
\LCPAddPHProcess[
  type=isenthalp,
  from={pressure=18bar,temperature=60C},
  to={pressure=3bar},
  name=r134a-three-four,
  export coordinates=RAirThreeFour,
  color=red,style={line width=1.4pt,-Latex}]
\LCPAddPHProcess[
  type=isobar,pressure=3bar,
  from={enthalpy=287.4107701858kJkg},
  to={temperature=5C},
  name=r134a-four-one,
  export coordinates=RAirFourOne,
  color=red,style={line width=1.4pt,-Latex}]
\end{LCPExample}

The four state positions are now obtained from adjacent named paths:

\begin{LCPExample}{Closing the topology with four intersections}
\path[name intersections={of=r134a-four-one and r134a-one-two,
  by=RAirOne}];
\path[name intersections={of=r134a-one-two and r134a-two-three,
  by=RAirTwo}];
\path[name intersections={of=r134a-two-three and r134a-three-four,
  by=RAirThree}];
\path[name intersections={of=r134a-three-four and r134a-four-one,
  by=RAirFour}];
\end{LCPExample}

Quality lines at 0.4 and 0.5 bracket state 4.  CoolProp resolves the process
endpoint as $T_4=273.822\,\mathrm K=0.672\,{}^\circ\mathrm C$ and
$Q_4=0.4367$, compared with the correction's graphical estimates of
$1\,{}^\circ\mathrm C$ and 0.43.

\begin{center}
  \includegraphics[page=6,width=.96\textwidth]
    {tutorial/r134a-air-conditioner.pdf}
\end{center}

The final page deliberately keeps both the construction curves and the cycle.
The student can see why every state exists, while the compact result box uses
the numbers exported by exactly the same process calls that draw the red paths.

\subsection{Obtain every numerical value from process exports}

The option \key{export coordinates=RAirOneTwo} exports plotted coordinates
and SI state properties. The macros \macro{\RAirOneTwoFromX} and
\macro{\RAirOneTwoToX} contain $h_1$ and $h_2$ in the displayed unit.

The compressor outlet temperature is available as
\macro{\RAirOneTwoToTemperatureK}. The throttle similarly defines
\macro{\RAirThreeFourToQuality}. No separate property table is embedded in
the diagram source.

\begin{LCPExample}{Powers and coefficient of performance from exported values}
\pgfmathsetmacro{\CompressorPower}{
  .1*(\RAirOneTwoToX-\RAirOneTwoFromX)}
\pgfmathsetmacro{\EvaporatorPower}{
  .1*(\RAirFourOneToX-\RAirFourOneFromX)}
\pgfmathsetmacro{\AirConditionerCOP}{
  \EvaporatorPower/\CompressorPower}

\typeout{State 2 temperature (K):
  \RAirOneTwoToTemperatureK}
\typeout{State 4 quality:
  \RAirThreeFourToQuality}
\end{LCPExample}

Because enthalpy coordinates are in $\mathrm{kJ\,kg^{-1}}$ and mass flow is in
$\mathrm{kg\,s^{-1}}$, their product is directly in kilowatts:
\[
  \dot W_c
  =\dot m(h_2-h_1)
  =0.1(441.019-402.876)
  =3.81\,\mathrm{kW},
\]
\[
  \dot Q_e
  =\dot m(h_1-h_4)
  =0.1(402.876-287.411)
  =11.55\,\mathrm{kW},
\]
and
\[
  \mathrm{COP}
  =\frac{\dot Q_e}{\dot W_c}
  =3.03.
\]
The positive evaporator power means that the refrigerant receives heat from
the passenger compartment, thereby cooling it.

For comparison, using the temperatures requested by the statement gives
\[
  \mathrm{COP}_{\mathrm{Carnot}}
  =\frac{T_1}{T_3-T_1}
  =\frac{278.15}{333.15-278.15}
  =5.06.
\]
The modelled cycle is therefore less effective than the reversible benchmark,
as expected.

\begin{LCPWarning}[Keep graphical and computed precision distinct]
A printed chart yields approximate readings, while the generated process
exports evaluate the selected CoolProp state model directly. The resulting
cycle gives a COP of 3.03. In teaching material, state explicitly whether a
number is a graphical estimate or an equation-of-state evaluation; do not
silently mix the two levels of precision in one energy balance.
\end{LCPWarning}

\subsection{Files, rebuild, and adaptation checklist}

The driver and its six-stage implementation are, respectively,
\begin{center}
\small
\path{tutorial/r134a-air-conditioner.tex}\\
\path{tutorial/source/r134a-air-conditioner-diagrams.tex}.
\end{center}
Rebuild every tutorial, example, log, index, and the manual with:

\begin{LCPExample}{Reproducible repository build}
export LUACOOLPROP_LIB=/path/to/libCoolProp.dylib
./scripts/build-examples.sh
\end{LCPExample}

When adapting this example to a different air conditioner:
\begin{enumerate}
  \item replace the fluid and the two operating pressures;
  \item express every state with two independent properties;
  \item let each \macro{\LCPAddPHProcess} compute its own path;
  \item give all cycle paths stable \key{name} values;
  \item obtain state coordinates only through named-path intersections;
  \item export numerical endpoints instead of maintaining a second table;
  \item compare graphical and equation-of-state precision explicitly; and
  \item verify the signs and units of every steady-flow energy balance.
\end{enumerate}
