"""An ideal Rankine cycle with real steam properties (CoolProp instead of steam tables), its T-s diagram, and what boiler
pressure does to efficiency and to the steam leaving the turbine."""
import numpy as np, matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from CoolProp.CoolProp import PropsSI

F = "Water"
def cycle(p_boiler, T_in=500 + 273.15, p_cond=10e3):
    # 1: saturated liquid leaving the condenser
    h1 = PropsSI("H", "P", p_cond, "Q", 0, F); s1 = PropsSI("S", "P", p_cond, "Q", 0, F); v1 = 1 / PropsSI("D", "P", p_cond, "Q", 0, F)
    # 2: after the pump (isentropic): w_pump = v dp
    w_pump = v1 * (p_boiler - p_cond); h2 = h1 + w_pump; s2 = s1
    # 3: superheated steam leaving the boiler
    h3 = PropsSI("H", "P", p_boiler, "T", T_in, F); s3 = PropsSI("S", "P", p_boiler, "T", T_in, F)
    # 4: after the turbine (isentropic) at the condenser pressure
    h4 = PropsSI("H", "P", p_cond, "S", s3, F); x4 = PropsSI("Q", "P", p_cond, "S", s3, F)
    w_turb, q_in = h3 - h4, h3 - h2
    return dict(h1=h1, h2=h2, h3=h3, h4=h4, s1=s1, s3=s3, x4=x4, eta=(w_turb - w_pump) / q_in,
                bwr=w_pump / w_turb, w_net=w_turb - w_pump, q_in=q_in)

c = cycle(8e6)
print("Boiler 8 MPa, 500 °C; condenser 10 kPa")
for k in ("h1", "h2", "h3", "h4"):
    print(f"  {k} = {c[k] / 1000:8.1f} kJ/kg")
print(f"  turbine work {(c['h3'] - c['h4']) / 1000:.1f} kJ/kg, pump work {(c['h2'] - c['h1']) / 1000:.1f} kJ/kg, heat in {c['q_in'] / 1000:.1f} kJ/kg")
print(f"  thermal efficiency {100 * c['eta']:.1f} %, back work ratio {100 * c['bwr']:.2f} %, turbine exit quality {c['x4']:.3f}")
eta_carnot = 1 - PropsSI("T", "P", 10e3, "Q", 0, F) / (500 + 273.15)
print(f"  Carnot between the same temperatures: {100 * eta_carnot:.1f} %")

print("\nBoiler pressure sweep (500 °C in, 10 kPa out):")
ps = [2e6, 4e6, 6e6, 8e6, 10e6, 12e6, 15e6]
rows = [cycle(p) for p in ps]
for p, r in zip(ps, rows):
    print(f"  {p / 1e6:5.0f} MPa   efficiency {100 * r['eta']:5.1f} %   exit quality {r['x4']:.3f}{'   too wet (< 0.88)' if r['x4'] < 0.88 else ''}")

# the fix: reheat. Expand to 2 MPa, heat back to 500 °C, expand to the condenser
def reheat(p_boiler=8e6, p_re=2e6, T_in=500 + 273.15, p_cond=10e3):
    b = cycle(p_boiler, T_in, p_cond)
    h4a = PropsSI("H", "P", p_re, "S", b["s3"], F)              # after the high-pressure turbine
    h5 = PropsSI("H", "P", p_re, "T", T_in, F); s5 = PropsSI("S", "P", p_re, "T", T_in, F)
    h6 = PropsSI("H", "P", p_cond, "S", s5, F); x6 = PropsSI("Q", "P", p_cond, "S", s5, F)
    w_turb = (b["h3"] - h4a) + (h5 - h6)
    w_pump = b["h2"] - b["h1"]
    q_in = (b["h3"] - b["h2"]) + (h5 - h4a)
    return (w_turb - w_pump) / q_in, x6
eta_r, x_r = reheat()
print()
print(f"With reheat at 2 MPa back to 500 °C: efficiency {100 * eta_r:.1f} % (was {100 * c['eta']:.1f} %), exit quality {x_r:.3f} (was {c['x4']:.3f})")

# T-s diagram with the saturation dome
fig, ax = plt.subplots(1, 2, figsize=(11, 4.6))
Tc = PropsSI("Tcrit", F)
Ts = np.linspace(273.16, Tc - 0.01, 300)
s_c = PropsSI("S", "T", Tc, "Dmass", PropsSI("rhocrit", F), F)    # the critical point closes the dome
liq = [PropsSI("S", "T", t, "Q", 0, F) / 1000 for t in Ts] + [s_c / 1000]
vap = [s_c / 1000] + [PropsSI("S", "T", t, "Q", 1, F) / 1000 for t in Ts[::-1]]
ax[0].plot(liq + vap, list(Ts - 273.15) + [Tc - 273.15, Tc - 273.15] + list(Ts[::-1] - 273.15), color="#999", lw=1)
# the cycle: 1-2 pump (vertical, tiny), 2-3 heating at constant pressure, 3-4 turbine (vertical), 4-1 condensing
p = 8e6
s23 = np.linspace(c["s1"], c["s3"], 200)
T23 = [PropsSI("T", "P", p, "S", s, F) - 273.15 for s in s23]
T1 = PropsSI("T", "P", 10e3, "Q", 0, F) - 273.15
ax[0].plot(s23 / 1000, T23, color="#6d3fc4", lw=2)
ax[0].plot([c["s3"] / 1000] * 2, [T23[-1], T1], color="#6d3fc4", lw=2)
ax[0].plot([c["s1"] / 1000, c["s3"] / 1000], [T1, T1], color="#6d3fc4", lw=2)
for lbl, s, T in (("1, 2", c["s1"], T1), ("3", c["s3"], T23[-1]), ("4", c["s3"], T1)):
    ax[0].annotate(lbl, (s / 1000, T), xytext=(5, 5), textcoords="offset points")
ax[0].set(xlabel="entropy s (kJ/kg·K)", ylabel="temperature T (°C)", title="Ideal Rankine cycle, 8 MPa / 500 °C / 10 kPa")
# the sweep
ax2 = ax[1].twinx()
ax[1].plot([p / 1e6 for p in ps], [100 * r["eta"] for r in rows], "o-", color="#6d3fc4", label="efficiency")
ax2.plot([p / 1e6 for p in ps], [r["x4"] for r in rows], "s--", color="#e0a000", label="turbine exit quality")
ax2.axhline(0.88, color="#e0a000", lw=0.8, ls=":")
ax[1].set(xlabel="boiler pressure (MPa)", ylabel="thermal efficiency (%)", title="Higher pressure: more efficient, wetter exit")
ax2.set_ylabel("exit quality x₄")
fig.tight_layout()
fig.savefig("rankine.png", dpi=150)
print("saved rankine.png")
