#!/usr/bin/env python3
"""
heat_pipe_limits.py -- operating limits of a cylindrical wicked heat pipe.

Thermal Management & Clean Energy Lab, University of Bristol
https://bristol-thermal-lab.github.io/heat-pipe/

Five classical limits are evaluated over a range of operating (vapour)
temperatures for a cylindrical heat pipe with a sintered-powder wick:

  capillary    Chi (1976) / Faghri (2016) pressure balance, closed form
               (laminar vapour) or fixed-point iteration (turbulent vapour)
  boiling      Chi (1976), using the evaporator length L_e and an effective
               wick conductivity (Maxwell) -- nucleation radius r_n is a
               parameter (default 2.54e-7 m, Chi)
  sonic        Busse (1973):       q = 0.474 A_v h_fg sqrt(rho_v P_v)
  entrainment  Cotter / Chi:       q = A_v h_fg sqrt(sigma rho_v / (2 r_hw))
  viscous      Busse (1973):       q = A_v r_v^2 h_fg rho_v P_v / (16 mu_v L_eff)

Sintered-sphere wick relations (Chi 1976; Peterson 1994; Faghri 2016):
  effective pore radius   r_c = 0.21 d_s
  permeability            K   = d_s^2 eps^3 / (150 (1 - eps)^2)   (Blake-Kozeny)

Sign convention for tilt: phi > 0 means the evaporator is ABOVE the condenser
(adverse, against gravity); phi < 0 is gravity-assisted; phi = 0 horizontal.

Fluid properties from CoolProp (IAPWS-95 for water).  Install with
    pip install CoolProp numpy matplotlib

Usage
    python heat_pipe_limits.py                    # 6 mm x 200 mm, horizontal
    python heat_pipe_limits.py --od 8 --length 250 --tilt 30
    python heat_pipe_limits.py --validate         # compare with catalogue Qmax
    python heat_pipe_limits.py --csv out.csv      # dump the table

This is an engineering estimate.  Real Qmax depends on fill ratio, sintering
quality, bends, flattening and test procedure; use it for trends and
first-cut sizing, not as a guarantee.

MIT licence.
"""
from __future__ import annotations

import argparse
import csv
import math
from dataclasses import dataclass, field, replace

import numpy as np

try:
    import CoolProp.CoolProp as CP
except ImportError as exc:  # pragma: no cover
    raise SystemExit("CoolProp is required:  pip install CoolProp") from exc

G = 9.81  # m s^-2


# --------------------------------------------------------------------------
# Inputs
# --------------------------------------------------------------------------
@dataclass
class Geometry:
    od: float = 6.0e-3          # outer diameter, m
    wall: float = 0.30e-3       # wall thickness, m
    t_wick: float = 0.45e-3     # wick thickness, m
    L: float = 0.200            # total length, m
    L_e: float = 0.050          # evaporator length, m
    L_c: float = 0.050          # condenser length, m
    tilt_deg: float = 0.0       # +ve = evaporator above condenser (adverse)

    @property
    def r_o(self): return self.od / 2
    @property
    def r_i(self): return self.r_o - self.wall
    @property
    def r_v(self): return self.r_i - self.t_wick
    @property
    def L_a(self): return self.L - self.L_e - self.L_c
    @property
    def L_eff(self): return self.L_a + 0.5 * (self.L_e + self.L_c)
    @property
    def A_v(self): return math.pi * self.r_v ** 2
    @property
    def A_w(self): return math.pi * (self.r_i ** 2 - self.r_v ** 2)

    def check(self):
        if self.r_v <= 0:
            raise ValueError("wall + wick thickness leave no vapour core")
        if self.L_a < 0:
            raise ValueError("L_e + L_c exceed total length")


@dataclass
class Wick:
    d_s: float = 100e-6         # powder (sphere) diameter, m
    eps: float = 0.50           # porosity
    k_solid: float = 390.0      # copper, W m^-1 K^-1
    r_n: float = 2.54e-7        # nucleation-site radius for boiling limit, m

    @property
    def r_c(self): return 0.21 * self.d_s
    @property
    def K(self): return self.d_s ** 2 * self.eps ** 3 / (150.0 * (1 - self.eps) ** 2)
    @property
    def r_hw(self):
        # hydraulic radius of the wick surface pores (used in entrainment);
        # taken as the effective pore radius, as is usual for sintered wicks
        return self.r_c

    def k_eff(self, k_l):
        """Maxwell (1891) effective conductivity, liquid-continuous."""
        ks, e = self.k_solid, self.eps
        return k_l * (2 * k_l + ks - 2 * (1 - e) * (k_l - ks)) / \
                     (2 * k_l + ks + (1 - e) * (k_l - ks))


@dataclass
class Props:
    T: float; P: float; rho_l: float; rho_v: float
    mu_l: float; mu_v: float; k_l: float; sigma: float; h_fg: float


def props(fluid: str, T: float) -> Props:
    q = lambda k, x: CP.PropsSI(k, "T", T, "Q", x, fluid)
    return Props(T=T, P=q("P", 0), rho_l=q("D", 0), rho_v=q("D", 1),
                 mu_l=q("V", 0), mu_v=q("V", 1), k_l=q("L", 0),
                 sigma=q("I", 0), h_fg=q("H", 1) - q("H", 0))


# --------------------------------------------------------------------------
# Limits
# --------------------------------------------------------------------------
def capillary_limit(g: Geometry, w: Wick, p: Props):
    """Returns (q_max [W], Re_v at q_max, Mach at q_max, available dP [Pa])."""
    dP_cap = 2 * p.sigma / w.r_c
    dP_g = p.rho_l * G * g.L * math.sin(math.radians(g.tilt_deg))
    dP_avail = dP_cap - dP_g
    if dP_avail <= 0:
        return 0.0, 0.0, 0.0, dP_avail
    F_l = p.mu_l / (w.K * g.A_w * p.rho_l * p.h_fg)                 # Pa/(W m)
    F_v_lam = 8 * p.mu_v / (math.pi * g.r_v ** 4 * p.rho_v * p.h_fg)

    def Re(q):  # vapour Reynolds number, D = 2 r_v
        return 2 * q / (math.pi * g.r_v * p.mu_v * p.h_fg)

    q = dP_avail / ((F_l + F_v_lam) * g.L_eff)
    if Re(q) > 2300:
        # turbulent vapour, Blasius:  f = 0.079 Re^-0.25 ;  dP_v/dz = f rho u^2 * 2/r_v ...
        # written as F_v = F_v_lam * (f Re / 16)
        for _ in range(200):
            fRe = 0.079 * Re(q) ** 0.75
            F_v = F_v_lam * max(1.0, fRe / 16.0)
            q_new = dP_avail / ((F_l + F_v) * g.L_eff)
            if abs(q_new - q) < 1e-6 * q:
                break
            q = 0.5 * (q + q_new)
    u_v = q / (p.rho_v * g.A_v * p.h_fg)
    c = math.sqrt(1.33 * p.P / p.rho_v)  # ideal-gas sound speed, gamma ~ 1.33
    return q, Re(q), u_v / c, dP_avail


def boiling_limit(g: Geometry, w: Wick, p: Props):
    ke = w.k_eff(p.k_l)
    dP = 2 * p.sigma / w.r_n - 2 * p.sigma / w.r_c
    return 2 * math.pi * g.L_e * ke * p.T / (p.h_fg * p.rho_v * math.log(g.r_i / g.r_v)) * dP


def sonic_limit(g: Geometry, p: Props):
    return 0.474 * g.A_v * p.h_fg * math.sqrt(p.rho_v * p.P)


def entrainment_limit(g: Geometry, w: Wick, p: Props):
    return g.A_v * p.h_fg * math.sqrt(p.sigma * p.rho_v / (2 * w.r_hw))


def viscous_limit(g: Geometry, p: Props):
    return g.A_v * g.r_v ** 2 * p.h_fg * p.rho_v * p.P / (16 * p.mu_v * g.L_eff)


LIMITS = ("capillary", "boiling", "sonic", "entrainment", "viscous")


def evaluate(g: Geometry, w: Wick, fluid="Water", T_C=np.arange(30, 151, 5)):
    g.check()
    rows = []
    for tc in T_C:
        p = props(fluid, tc + 273.15)
        qc, Re, Ma, dPa = capillary_limit(g, w, p)
        r = dict(T_C=float(tc), capillary=qc, boiling=boiling_limit(g, w, p),
                 sonic=sonic_limit(g, p), entrainment=entrainment_limit(g, w, p),
                 viscous=viscous_limit(g, p), Re_v=Re, Mach=Ma, dP_avail=dPa)
        r["q_max"] = min(r[k] for k in LIMITS)
        r["governing"] = min(LIMITS, key=lambda k: r[k])
        rows.append(r)
    return rows


# --------------------------------------------------------------------------
# Validation against manufacturer catalogue Qmax (sintered Cu-water)
# --------------------------------------------------------------------------
# Boyd copper-water heat pipe catalogue (typical Qmax, gravity-aided,
# "common operating temperatures", typical evaporator/condenser lengths)
# Wakefield-Vette heat-pipe selection guide (sintered, straight round;
# test conditions not stated).  The two vendors differ by up to ~2x for
# nominally similar pipes, which is the realistic spread of "Qmax".
CATALOGUE = [
    # source, OD mm, L mm, Qmax W
    ("Boyd HP-CWS-R06-100", 6, 100, 137), ("Boyd HP-CWS-R06-150", 6, 150, 91),
    ("Boyd HP-CWS-R06-200", 6, 200, 69),  ("Boyd HP-CWS-R06-250", 6, 250, 55),
    ("Boyd HP-CWS-R06-310", 6, 310, 47),  ("Boyd HP-CWS-R06-350", 6, 350, 40),
    ("Boyd HP-CWS-R08-100", 8, 100, 199), ("Boyd HP-CWS-R08-155", 8, 155, 135),
    ("Boyd HP-CWS-R08-200", 8, 200, 99),  ("Boyd HP-CWS-R08-250", 8, 250, 80),
    ("Boyd HP-CWS-R05-150", 5, 150, 72),  ("Boyd HP-CWS-R05-200", 5, 200, 52),
    ("Boyd HP-CWS-R05-300", 5, 300, 35),
    ("Wakefield-Vette 5x100", 5, 100, 32), ("Wakefield-Vette 5x150", 5, 150, 35),
    ("Wakefield-Vette 5x200", 5, 200, 30), ("Wakefield 110583 8x200", 8, 200, 50),
]


def catalogue_geometry(od_mm, L_mm, tilt=0.0):
    # Evaporator / condenser lengths that scale with pipe length the way
    # vendors usually test them (about 1/4 L each, capped).
    Le = min(0.25 * L_mm, 60) / 1000
    return Geometry(od=od_mm / 1000, wall=0.30e-3 if od_mm <= 6 else 0.35e-3,
                    t_wick=0.45e-3 if od_mm <= 6 else 0.55e-3,
                    L=L_mm / 1000, L_e=Le, L_c=Le, tilt_deg=tilt)


def validate(w: Wick, T_C=70.0):
    print(f"\nValidation at T_v = {T_C:.0f} C, horizontal, wick d_s = {w.d_s*1e6:.0f} um, eps = {w.eps:.2f}")
    print(f"{'source':24s} {'OD':>3s} {'L':>4s} {'Qcat':>5s} {'Qmodel':>7s} {'ratio':>6s}  governing")
    out = []
    for src, od, L, qcat in CATALOGUE:
        r = evaluate(catalogue_geometry(od, L), w, T_C=[T_C])[0]
        out.append((src, od, L, qcat, r["q_max"], r["governing"]))
        print(f"{src:24s} {od:3d} {L:4d} {qcat:5.0f} {r['q_max']:7.1f} {r['q_max']/qcat:6.2f}  {r['governing']}")
    for vendor in ("Boyd", "Wakefield"):
        err = np.array([o[4] / o[3] for o in out if o[0].startswith(vendor)])
        print(f"{vendor}: model/catalogue mean {err.mean():.2f}, range {err.min():.2f}-{err.max():.2f}")
    return out


# --------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------
def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--fluid", default="Water")
    ap.add_argument("--od", type=float, default=6.0, help="outer diameter, mm")
    ap.add_argument("--wall", type=float, default=0.30, help="wall thickness, mm")
    ap.add_argument("--wick", type=float, default=0.45, help="wick thickness, mm")
    ap.add_argument("--length", type=float, default=200, help="total length, mm")
    ap.add_argument("--le", type=float, default=50, help="evaporator length, mm")
    ap.add_argument("--lc", type=float, default=50, help="condenser length, mm")
    ap.add_argument("--tilt", type=float, default=0.0, help="deg, +ve = evaporator above")
    ap.add_argument("--ds", type=float, default=100, help="powder diameter, um")
    ap.add_argument("--eps", type=float, default=0.50, help="wick porosity")
    ap.add_argument("--rn", type=float, default=2.54e-7, help="nucleation radius, m")
    ap.add_argument("--tmin", type=float, default=30); ap.add_argument("--tmax", type=float, default=150)
    ap.add_argument("--csv"); ap.add_argument("--plot")
    ap.add_argument("--validate", action="store_true")
    a = ap.parse_args()

    w = Wick(d_s=a.ds * 1e-6, eps=a.eps, r_n=a.rn)
    if a.validate:
        validate(w)
        return
    g = Geometry(od=a.od / 1e3, wall=a.wall / 1e3, t_wick=a.wick / 1e3, L=a.length / 1e3,
                 L_e=a.le / 1e3, L_c=a.lc / 1e3, tilt_deg=a.tilt)
    rows = evaluate(g, w, a.fluid, np.arange(a.tmin, a.tmax + 1e-9, 5))
    print(f"{a.fluid}: OD {a.od} mm, r_v {g.r_v*1e3:.2f} mm, L {a.length} mm, "
          f"L_eff {g.L_eff*1e3:.0f} mm, tilt {a.tilt} deg; r_c {w.r_c*1e6:.1f} um, K {w.K:.2e} m2")
    print(f"{'T C':>5s}" + "".join(f"{k:>12s}" for k in LIMITS) + f"{'Qmax':>9s}{'Re_v':>7s}{'Ma':>6s}  governing")
    for r in rows:
        print(f"{r['T_C']:5.0f}" + "".join(f"{r[k]:12.1f}" for k in LIMITS)
              + f"{r['q_max']:9.1f}{r['Re_v']:7.0f}{r['Mach']:6.3f}  {r['governing']}")
    if a.csv:
        with open(a.csv, "w", newline="") as f:
            wr = csv.DictWriter(f, fieldnames=list(rows[0].keys())); wr.writeheader(); wr.writerows(rows)
    if a.plot:
        import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
        T = [r["T_C"] for r in rows]
        fig, ax = plt.subplots(figsize=(7, 4.5))
        for k in LIMITS:
            ax.plot(T, [r[k] for r in rows], label=k)
        ax.plot(T, [r["q_max"] for r in rows], "k", lw=2.5, label="Q_max envelope")
        ax.set_yscale("log"); ax.set_xlabel("vapour temperature (°C)"); ax.set_ylabel("heat transport (W)")
        ax.legend(); ax.grid(alpha=.3); fig.tight_layout(); fig.savefig(a.plot, dpi=150)


if __name__ == "__main__":
    main()
