"""Jacket-side coefficient, overall coefficient and cooling capacity of a jacketed reactor
(Chmltech Online Journal, Vol. 106, Issue 26, Appendix). Python 3, standard library only.

The jacket-side coefficient is the Gnielinski correlation on the hydraulic diameter of the jacket channel. By default it
is used alone. The ratios of the paper's CFD to that correlation (CFD_OVER_GNIELINSKI) can be applied by calling
jacket(..., cfd_correction=True), but they hold only for the paper's geometries and Reynolds numbers: the plain jacket
(50 mm gap, 259 mm baffle pitch, Re about 31,000) and the half-pipe (3 in. Sch 10S, Re about 91,000). The dimple ratio is
kept at 1.0 unless you opt in with DIMPLE_OPT_IN = True: the paper's dimple cell (15 mm cylindrical posts on a 60 mm
triangular pitch, uniform 8 mm gap, Re about 18,000) is idealized and not validated against any dimple measurement. The overall coefficient adds the batch-side film, the wall and the
fouling in series, and the effective area counts the strips of wall the coolant does not touch (weld gaps, baffles, weld
posts) as fins fed from the batch side. Capacity is the heat removed at the batch temperature with the water warming
along the jacket, Q = m cp (1 - exp(-UA / m cp)) (T_batch - T_in), as in the Insights jacket post.

Replace the inputs in the __main__ block with your own vessel and jacket; the defaults are reactor R-101 of the paper.
"""
import math

# CFD result over the Gnielinski correlation, finest mesh of the paper (filled by make_zip.py from results.json).
# Used only with cfd_correction=True; the dimple value only with DIMPLE_OPT_IN = True as well (see the docstring).
DIMPLE_OPT_IN = False
CFD_OVER_GNIELINSKI = {"plain": 1.028, "dimple": 1.246, "halfpipe": 0.969}


def water(t_c):
    """Water near 1 to 3 bar between 10 and 80 C: density kg/m3, viscosity Pa.s, conductivity W/m.K, cp J/kg.K.
    Simple fits to IAPWS-95 values (within about 1%)."""
    rho = 1000.6 - 0.0128 * t_c ** 1.76
    mu = 2.414e-5 * 10 ** (247.8 / (t_c + 273.15 - 140))
    k = 0.5650 + 0.00198 * t_c - 8.0e-6 * t_c ** 2
    cp = 4217 - 3.0 * t_c + 0.068 * t_c ** 2 - 0.00035 * t_c ** 3
    return rho, mu, k, cp


def gnielinski(re, pr):
    f = (0.790 * math.log(re) - 1.64) ** -2
    return (f / 8) * (re - 1000) * pr / (1 + 12.7 * math.sqrt(f / 8) * (pr ** (2 / 3) - 1)), f


def channel(kind, flow_m3s, d):
    """Flow area (m2), hydraulic diameter (m), heated width per unit length (m) and covered share of the wall."""
    if kind == "plain":            # spiral baffle: rectangular channel gap x pitch, heated on the vessel side
        a = d["gap"] * d["pitch"]
        return a, 4 * a / (2 * (d["gap"] + d["pitch"])), d["pitch"] / (d["pitch"] + d["baffle"])
    if kind == "halfpipe":         # half circle of inside diameter ID on the vessel
        a = math.pi * d["id"] ** 2 / 8
        return a, 4 * a / (math.pi * d["id"] / 2 + d["id"]), d["id"] / (d["id"] + d["weld_gap"] + 2 * d["wall"])
    if kind == "dimple":           # gap between vessel and sheet; posts on a triangular pitch
        a = flow_m3s / d["velocity"]
        cover = 1 - (math.pi * d["post"] ** 2 / 4) / (d["pitch"] ** 2 * math.sqrt(3) / 2)
        return a, 2 * d["gap"], cover
    raise ValueError(kind)


def jacket(kind, flow_m3s, d, t_water, cfd_correction=False):
    rho, mu, k, cp = water(t_water)
    a, dh, cover = channel(kind, flow_m3s, d)
    v = flow_m3s / a
    re = rho * v * dh / mu
    pr = cp * mu / k
    nu, f = gnielinski(re, pr)
    ratio = CFD_OVER_GNIELINSKI[kind] if cfd_correction and (kind != "dimple" or DIMPLE_OPT_IN) else 1.0
    h = nu * k / dh * ratio
    dp_per_m = f / dh * rho * v ** 2 / 2          # straight-channel friction only (no bends, nozzles or posts)
    return dict(v=v, Re=re, Pr=pr, Dh=dh, h=h, covered=cover, dp_per_m=dp_per_m if kind != "dimple" else None)


def overall(h_jacket, h_batch, wall_t, wall_k, r_foul, covered, strip_half_width):
    """Overall U on the whole wetted area: U of the covered wall times the effective share of the wall."""
    u = 1 / (1 / h_batch + wall_t / wall_k + r_foul + 1 / h_jacket)
    u_strip = 1 / (1 / h_batch + r_foul / 2)
    m = math.sqrt(u_strip / (wall_k * wall_t))
    eta = math.tanh(m * strip_half_width) / (m * strip_half_width) if strip_half_width > 0 else 1.0
    return u * (covered + eta * (1 - covered)), eta


def capacity(u, area, flow_m3s, t_batch, t_in, t_water=30.0):
    rho, mu, k, cp = water(t_water)
    mcp = flow_m3s * rho * cp / 1000                   # kW/K
    return mcp * (1 - math.exp(-u * area / 1000 / mcp)) * (t_batch - t_in)


if __name__ == "__main__":
    flow = 13.976 / 3600                               # m3/s of cooling water (R-101)
    area, t_batch, t_in, t_out = 17.13, 60.0, 25.0, 34.5
    h_batch, wall_t, wall_k, r_foul = 800.0, 0.012, 16.0, 0.000333
    designs = {
        "plain": (dict(gap=0.050, pitch=0.259, baffle=0.006), 0.003),
        "halfpipe": (dict(id=0.0828, wall=0.00305, weld_gap=0.010), 0.00805),
        "dimple": (dict(gap=0.008, pitch=0.060, post=0.015, velocity=0.9), 0.0075),
    }
    for kind, (d, half) in designs.items():
        j = jacket(kind, flow, d, (t_in + t_out) / 2)
        u, eta = overall(j["h"], h_batch, wall_t, wall_k, r_foul, j["covered"], half)
        q = capacity(u, area, flow, t_batch, t_in)
        print(f"{kind:9s} v {j['v']:.2f} m/s  Re {j['Re']:,.0f}  h {j['h']:,.0f} W/m2K  U {u:.0f} W/m2K  Q {q:.0f} kW"
              + (f"  dp {j['dp_per_m']:.0f} Pa/m" if j['dp_per_m'] else ""))
