#!/usr/bin/env python3
"""
ai_vc_design.py -- zoned-wick vapour chamber with a stepped evaporator for a
2.5D GPU-class package (one SoC + four HBM stacks on a silicon interposer).

Thermal Management & Clean Energy Lab, University of Bristol
https://bristol-thermal-lab.github.io/ai-chip-vapour-chamber/

Same method as our zoned-wick vapour chamber (v0.2), extended to several heat
sources and a stepped base:

 1. 2.5D liquid model on a 0.5 mm grid of the evaporator wick.  Darcy flow
        -div( rho K t / mu  grad D ) + g D = m_evap
    where D = P_v - P_l is the capillary pressure deficit, t the local wick
    thickness, K the Blake-Kozeny permeability of the local powder, g the
    feed conductance per unit area of sintered pillars / feeding posts that
    bring condensate down from the condenser wick, and m_evap = q_w / h_fg the
    evaporation rate.  Side walls (wick-lined) are a Robin boundary.
    Liquid crossing the 0.5 mm step at the edge of the SoC pocket travels an
    extra 0.5 mm down the step wall.
 2. Capillary limit: Q_cap = Q * min_x [ 2 sigma / r_c(x) / (D(x) + dP_v) ],
    r_c = 0.21 d_s; dP_v from a 2D Darcy (Hele-Shaw) model of the vapour gap.
 3. Thermal model: 2D conduction in the 1 mm copper base, fed through the TIM
    by the dies, sinking to the saturated vapour through the wick
    (solid-continuous Maxwell k_eff for a sintered wick) -- conduction-only (conservative) or a literature boiling
    resistance 0.05 K cm2/W over the die footprints.  T_v follows from the lid
    and cold plate.
 4. Optimisation at fixed copper-powder mass (same as a uniform 50 um,
    porosity 0.5, 0.8 mm baseline):
      a. wick thickness by optimality-criteria (compliance) updates;
      b. powder zoning: the coarsest of 50/100/200 um whose capillary pressure
         still exceeds the local deficit at the capillary limit (x 1/0.8);
      c. feeding-post area fraction by OC, then error diffusion onto a
         1.25 mm grid of 1 mm posts.
    Evaporator pads (die footprint + 1 mm) are fixed at 50 um, 0.6 mm.

Engineering model: in-plane liquid supply only. Boiling incipience, vapour
venting through the pads and condenser-wick pressure drop are not modelled.

MIT licence.
"""
from __future__ import annotations
import json, math, sys
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla
import CoolProp.CoolProp as CP

# ---------------------------------------------------------------- geometry (mm)
DX = 0.5
L_VC = 80.0            # outer footprint
WALL = 4.0             # side frame
L_CAV = L_VC - 2 * WALL
N = int(round(L_CAV / DX))
xc = (np.arange(N) + 0.5) * DX - L_CAV / 2
X, Y = np.meshgrid(xc, xc, indexing="ij")

T_BASE, T_LID = 1.0, 1.0       # copper, mm
H_CAV = 3.5                    # cavity height above the floor (mm)
STEP = 0.5                     # SoC pocket depth (HBM top is 0.5 mm above SoC top)
T_CW = 0.4                     # condenser wick, mm (50 um, eps 0.5)
GAP_MIN = 1.0                  # minimum vapour gap, mm
POCKET = 13.0                  # half-width of the SoC pocket (mm)

DIES = [  # name, x0, y0, half-x, half-y, power W
    ("SoC", 0.0, 0.0, 11.5, 11.5, 700.0),
    ("HBM1", -23.75, 0.0, 2.75, 8.5, 30.0),
    ("HBM2", -17.25, 0.0, 2.75, 8.5, 30.0),
    ("HBM3", 17.25, 0.0, 2.75, 8.5, 30.0),
    ("HBM4", 23.75, 0.0, 2.75, 8.5, 30.0),
]
Q_TOT = sum(d[5] for d in DIES)

R_TIM = 0.05e-4       # m2 K / W  (0.05 K cm2/W, indium-class TIM)
R_BOIL = 0.05e-4      # m2 K / W  literature evaporator resistance
H_CP, T_COOL = 10000.0, 35.0   # cold plate on the lid
K_CU = 390.0
EPS_Z, EPS_B = 0.6, 0.5        # zoned / baseline porosity
POWDERS = (50e-6, 100e-6, 200e-6)

def rect(x0, y0, hx, hy, m=0.0):
    return (np.abs(X - x0) <= hx + m) & (np.abs(Y - y0) <= hy + m)

flux_die = np.zeros((N, N))     # W/m2 at the die face
die_id = -np.ones((N, N), int)
for i, (n, x0, y0, hx, hy, P) in enumerate(DIES):
    r = rect(x0, y0, hx, hy)
    flux_die[r] = P / (4 * hx * hy * 1e-6)
    die_id[r] = i
PAD = np.zeros((N, N), bool)
for (n, x0, y0, hx, hy, P) in DIES:
    PAD |= rect(x0, y0, hx, hy, 1.0)
INPOCKET = rect(0, 0, POCKET, POCKET)
CELL = (DX * 1e-3) ** 2

# ---------------------------------------------------------------- properties
def water(Tc):
    T = Tc + 273.15
    q = lambda k, x: CP.PropsSI(k, "T", T, "Q", x, "Water")
    return dict(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), P=q("P", 0))

def k_maxwell(kl, eps, ks=K_CU):
    """Effective conductivity of a sintered (solid-continuous) wick, Maxwell form
    as recommended for sintered powders (Chi 1976; Peterson 1994)."""
    return ks * (2 + kl / ks - 2 * eps * (1 - kl / ks)) / (2 + kl / ks + eps * (1 - kl / ks))

perm = lambda d, e: d * d * e ** 3 / (150 * (1 - e) ** 2)
pcap = lambda d, sig: 2 * sig / (0.21 * d)

# ---------------------------------------------------------------- pillars (support)
def pillar_sites(pitch=12.0, dia=3.0):
    pts = []
    for px in np.arange(-L_CAV / 2 + pitch / 2, L_CAV / 2, pitch):
        for py in np.arange(-L_CAV / 2 + pitch / 2, L_CAV / 2, pitch):
            near = any(abs(px - x0) <= hx + 3 + dia / 2 and abs(py - y0) <= hy + 3 + dia / 2
                       for (_, x0, y0, hx, hy, _) in DIES)
            if abs(px) <= POCKET + dia and abs(py) <= POCKET + dia:
                near = True          # keep the pocket and its step wall clear
            if not near:
                pts.append((round(float(px), 3), round(float(py), 3)))
    return pts

def disc_mask(pts, dia):
    m = np.zeros((N, N))
    for (px, py) in pts:
        m += ((X - px) ** 2 + (Y - py) ** 2 <= (dia / 2) ** 2)
    return np.minimum(m, 1)

# ---------------------------------------------------------------- linear solvers
def assemble(cond, react, robin):
    """-div(cond grad u) + react u on the grid, Robin (conductance robin) on the
    outer edge.  cond, react per cell (SI). Returns sparse matrix."""
    idx = np.arange(N * N).reshape(N, N)
    rows, cols, vals = [], [], []
    diag = react.ravel() * CELL
    # x-faces
    for axis in (0, 1):
        a = cond
        if axis == 0:
            c1, c2 = a[:-1, :], a[1:, :]
            i1, i2 = idx[:-1, :], idx[1:, :]
            s1, s2 = INPOCKET[:-1, :], INPOCKET[1:, :]
        else:
            c1, c2 = a[:, :-1], a[:, 1:]
            i1, i2 = idx[:, :-1], idx[:, 1:]
            s1, s2 = INPOCKET[:, :-1], INPOCKET[:, 1:]
        L = np.full(c1.shape, DX * 1e-3)
        L = L + np.where(s1 != s2, STEP * 1e-3, 0.0) * ROBIN_STEP  # step wall
        g = 2 * c1 * c2 / (c1 + c2 + 1e-300) * (DX * 1e-3) / L     # harmonic, x face width/length
        g = g.ravel()
        rows += [i1.ravel(), i2.ravel(), i1.ravel(), i2.ravel()]
        cols += [i2.ravel(), i1.ravel(), i1.ravel(), i2.ravel()]
        vals += [-g, -g, g, g]
    A = sp.coo_matrix((np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), shape=(N * N, N * N)).tocsr()
    edge = np.zeros((N, N))
    edge[0, :] += 1; edge[-1, :] += 1; edge[:, 0] += 1; edge[:, -1] += 1
    diag = diag + (edge * robin).ravel() * (DX * 1e-3)
    return (A + sp.diags(diag)).tocsc()

ROBIN_STEP = 1.0

def solve_liquid(t, d, eps, g_feed, m_evap, p):
    """D field (Pa). t (m), d powder (m), g_feed kg/(s Pa m2), m_evap kg/(s m2)."""
    cond = p["rho_l"] * perm(d, eps) * t / p["mu_l"]          # kg/(s Pa)
    # wall: wick-lined side wall 0.4 mm, 50 um eps .5, height ~H_CAV, per unit edge length
    g_wall = p["rho_l"] * perm(50e-6, 0.5) * 0.4e-3 / p["mu_l"] / (0.5 * H_CAV * 1e-3)
    A = assemble(cond, g_feed, g_wall)
    D = spla.spsolve(A, (m_evap * CELL).ravel()).reshape(N, N)
    return D, cond

def solve_vapour(t, q_w, p):
    """Hele-Shaw vapour gap: max pressure drop (Pa)."""
    gap = (H_CAV - T_CW) * 1e-3 - t + np.where(INPOCKET, STEP * 1e-3, 0)
    gap = np.maximum(gap, 0.3e-3)
    cond = p["rho_v"] * gap ** 3 / (12 * p["mu_v"])
    src = q_w / p["h_fg"] - (q_w.sum() / q_w.size) / p["h_fg"]   # evaporation - uniform condensation
    A = assemble(cond, np.full((N, N), 1e-12), 0.0)
    Pv = spla.spsolve(A, (src * CELL).ravel()).reshape(N, N)
    return Pv.max() - Pv.min()

def solve_thermal(t, eps, boiling, p, T_v):
    keff = k_maxwell(p["k_l"], eps)
    R_w = t / keff
    if boiling:
        R_w = np.where(die_id >= 0, R_BOIL, R_w)
    h_w = 1.0 / R_w
    cond = np.full((N, N), K_CU * T_BASE * 1e-3)                 # W/K
    # step wall: base continues down the step; small extra path
    A = assemble(cond, h_w, 0.0)
    rhs = flux_die * CELL + h_w * T_v * CELL
    Tb = spla.spsolve(A, rhs.ravel()).reshape(N, N)
    q_w = h_w * (Tb - T_v)
    T_die = Tb + flux_die * R_TIM
    return T_die, q_w

def lid_Tv(p_guess_T):
    cw = k_maxwell(water(p_guess_T)["k_l"], 0.5)
    A = (L_VC * 1e-3) ** 2
    R = (T_CW * 1e-3 / cw + T_LID * 1e-3 / K_CU) / ((L_CAV * 1e-3) ** 2) + 1 / (H_CP * A)
    return T_COOL + Q_TOT * R

# ---------------------------------------------------------------- one evaluation
def evaluate(design, boiling=False, verbose=False):
    T_v = 60.0
    for _ in range(3):
        T_v = lid_Tv(T_v)
    p = water(T_v)
    t, d, eps, g = design["t"], design["d"], design["eps"], design["g"]
    T_die, q_w = solve_thermal(t, eps, boiling, p, T_v)
    m_evap = np.maximum(q_w, 0) / p["h_fg"]
    D, _ = solve_liquid(t, d, eps, g, m_evap, p)
    dPv = solve_vapour(t, q_w, p)
    ratio = pcap(d, p["sigma"]) / (np.maximum(D, 0) + dPv)
    q_cap = Q_TOT * ratio.min()
    res = dict(T_v=T_v, q_cap=q_cap, margin=q_cap / Q_TOT, dPv=dPv, Dmax=D.max(),
               T_soc=float(T_die[die_id == 0].max()), T_hbm=float(T_die[die_id > 0].max()))
    if verbose:
        print({k: round(v, 2) for k, v in res.items()})
    return res, D, q_w, p

# ---------------------------------------------------------------- design pieces
def baseline(pillars):
    pm = disc_mask(pillars, 3.0)
    return dict(t=np.full((N, N), 0.8e-3), d=np.full((N, N), 50e-6), eps=EPS_B,
                g=pillar_feed(pm, water(60)), posts=[], pillars=pillars)

def pillar_feed(mask, p, dia=3.0, h=2.0e-3):
    # per unit plan area of a sintered column (50 um, eps .5) of height h
    return mask * p["rho_l"] * perm(50e-6, 0.5) / (p["mu_l"] * h)

def tmax_field():
    return ((H_CAV - T_CW - GAP_MIN) + np.where(INPOCKET, STEP, 0)) * 1e-3

def mass(t, eps):  # solid copper volume per plan area summed (m3)
    return ((1 - eps) * t).sum() * CELL

def optimise(pillars, n_outer=6, verbose=True):
    p = water(60.0)
    base = baseline(pillars)
    budget = mass(base["t"], EPS_B)
    pm = disc_mask(pillars, 3.0)
    gp = pillar_feed(pm, p)
    tmax = tmax_field()
    d = np.where(PAD, 50e-6, 100e-6)
    tmin = lambda d: np.maximum(0.2e-3, 4 * d)
    t = np.full((N, N), 1.0e-3)
    t[PAD] = 0.6e-3
    # feeding-post area fraction
    allow_post = (~PAD) & (pm == 0) & ~ring(PAD, 1.5)
    POST_AREA = 120 * math.pi * 0.25e-6     # at most ~120 posts of 1 mm
    phi = np.where(allow_post, 0.05, 0.0)
    POST_H = 2.0e-3
    g_post_full = p["rho_l"] * perm(50e-6, 0.5) / (p["mu_l"] * POST_H)
    post_vol = lambda phi: (phi * CELL * POST_H * 0.5).sum()
    for outer in range(n_outer):
        for it in range(25):
            g = gp + phi * g_post_full
            res, D, q_w, pp = evaluate(dict(t=t, d=d, eps=EPS_Z, g=g))
            gx, gy = np.gradient(D, DX * 1e-3)
            grad2 = gx ** 2 + gy ** 2
            sens_t = pp["rho_l"] * perm(d, EPS_Z) / pp["mu_l"] * grad2 * CELL      # -dC/dt
            sens_phi = g_post_full * D ** 2 * CELL                                # -dC/dphi
            free = ~PAD
            # posts: own area budget (vapour must still vent from the pads)
            lo, hi = 1e-40, 1e40
            for _ in range(100):
                lam = math.sqrt(lo * hi)
                fn = np.clip(phi * np.sqrt(sens_phi / (lam * CELL) + 1e-30), np.maximum(phi * 0.5, 0), np.minimum(phi * 1.6 + 1e-3, 0.4))
                fn = np.where(allow_post, fn, 0.0)
                if fn.sum() * CELL > POST_AREA:
                    lo = lam
                else:
                    hi = lam
            # wick thickness: remaining copper budget
            wick_budget = budget - post_vol(fn)
            lo, hi = 1e-40, 1e40
            for _ in range(100):
                lam = math.sqrt(lo * hi)
                tn = np.clip(t * np.sqrt(sens_t / (lam * (1 - EPS_Z) * CELL)), np.maximum(t * 0.6, tmin(d)), np.minimum(t * 1.6, tmax))
                tn = np.where(free, tn, 0.6e-3)
                if mass(tn, EPS_Z) > wick_budget:
                    lo = lam
                else:
                    hi = lam
            t, phi = tn, fn
        # powder zoning at the capillary limit
        res, D, q_w, pp = evaluate(dict(t=t, d=d, eps=EPS_Z, g=gp + phi * g_post_full))
        Dlim = (D + res["dPv"]) * res["margin"]            # deficit at Q_cap
        newd = np.full((N, N), 50e-6)
        for dd in POWDERS:
            ok = (Dlim <= 0.8 * pcap(dd, pp["sigma"])) & (tmax >= 4 * dd)
            newd = np.where(ok, dd, newd)
        newd[PAD] = 50e-6
        d = smooth_zones(newd)
        d = np.where(d == 100e-6, 50e-6, d) if (d == 100e-6).mean() < 0.01 else d   # drop a sliver zone: finer is always safe
        t = np.clip(t, tmin(d), tmax)
        if verbose:
            print(f"outer {outer}: q_cap {res['q_cap']:.0f} W, margin {res['margin']:.2f}, "
                  f"zones 50/100/200 = {[(d == x).mean().round(3) for x in POWDERS]}, posts area {phi.sum() * CELL * 1e6:.0f} mm2")
    return dict(t=t, d=d, eps=EPS_Z, g=gp, phi=phi, gpost=g_post_full, pillars=pillars, budget=budget)

def ring(mask, w):
    k = int(round(w / DX))
    m = mask.copy()
    for _ in range(k):
        m = m | np.roll(m, 1, 0) | np.roll(m, -1, 0) | np.roll(m, 1, 1) | np.roll(m, -1, 1)
    return m & ~mask

def smooth_zones(d):
    # majority filter (3x3) to remove isolated cells; manufacturable zones
    out = d.copy()
    for _ in range(2):
        votes = {dd: sum(np.roll(np.roll(out == dd, i, 0), j, 1) for i in (-1, 0, 1) for j in (-1, 0, 1)) for dd in POWDERS}
        best = max(POWDERS, key=lambda dd: 0)
        stack = np.stack([votes[dd] for dd in POWDERS])
        out = np.array(POWDERS)[stack.argmax(0)]
    out[PAD] = 50e-6
    return out

def discretise_posts(phi, pillars, pitch=1.25, dia=1.0):
    """Error diffusion of the area fraction onto a pitch grid of dia posts."""
    site_area = math.pi * (dia / 2) ** 2
    n = int(L_CAV / pitch)
    sx = (np.arange(n) + 0.5) * pitch - L_CAV / 2
    # mean area fraction per site
    F = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            m = (np.abs(X - sx[i]) < pitch / 2) & (np.abs(Y - sx[j]) < pitch / 2)
            F[i, j] = phi[m].mean() * pitch ** 2 / site_area if m.any() else 0
    E = F.copy(); pts = []
    for j in range(n):
        rng = range(n) if j % 2 == 0 else range(n - 1, -1, -1)
        for i in rng:
            v = 1.0 if E[i, j] >= 0.5 else 0.0
            err = E[i, j] - v
            if v:
                pts.append((round(float(sx[i]), 3), round(float(sx[j]), 3)))
            s = 1 if j % 2 == 0 else -1
            for di, dj, w in ((s, 0, 7 / 16), (-s, 1, 3 / 16), (0, 1, 5 / 16), (s, 1, 1 / 16)):
                ii, jj = i + di, j + dj
                if 0 <= ii < n and 0 <= jj < n:
                    E[ii, jj] += err * w
    return pts

def posts_feed(pts, gpost, dia=1.0):
    return disc_mask(pts, dia) * gpost

# ---------------------------------------------------------------- run
def main(out_json=None):
    pillars = pillar_sites()
    print(f"grid {N}x{N}, Q = {Q_TOT:.0f} W, pillars {len(pillars)}")
    B = baseline(pillars)
    rb_c, *_ = evaluate(B, False)
    rb_b, *_ = evaluate(B, True)
    print("baseline", rb_c, rb_b)
    O = optimise(pillars)
    pts = discretise_posts(O["phi"], pillars)
    # ring = posts within 4 mm of a pad edge
    near = ring(PAD, 3.5)
    ring_pts = [q for q in pts if near[int((q[0] + L_CAV / 2) / DX), int((q[1] + L_CAV / 2) / DX)]]
    results = {}
    for name, P in (("all", pts), ("ring", ring_pts)):
        des = dict(t=O["t"], d=O["d"], eps=EPS_Z, g=O["g"] + posts_feed(P, O["gpost"]))
        rc, Dc, qw, pp = evaluate(des, False)
        rbo, *_ = evaluate(des, True)
        results[name] = dict(n=len(P), q_cap=rc["q_cap"], margin=rc["margin"], T_soc_c=rc["T_soc"],
                             T_hbm_c=rc["T_hbm"], T_soc_b=rbo["T_soc"], T_hbm_b=rbo["T_hbm"], T_v=rc["T_v"], dPv=rc["dPv"])
        print(name, results[name])
    m_used = mass(O["t"], EPS_Z) + len(pts) * math.pi * 0.25e-6 * 2.0e-3 * 0.5
    print(f"mass check: baseline {O['budget']*1e9:.0f} mm3, zoned+posts {m_used*1e9:.0f} mm3")
    t, d = O["t"], O["d"]
    zone_stats = {}
    for dd in POWDERS:
        m = d == dd
        if not m.any():
            continue
        zone_stats[int(dd * 1e6)] = dict(area_cm2=float(m.sum() * CELL * 1e4), t_min=float(t[m].min() * 1e3),
                                       t_max=float(t[m].max() * 1e3), t_mean=float(t[m].mean() * 1e3))
    print(zone_stats)
    if out_json:
        # quantised fields for the web page (0..255 on t, zone code)
        tq = np.clip(np.round((t * 1e3) / 3.0 * 255), 0, 255).astype(np.uint8)
        dq = np.select([d == 50e-6, d == 100e-6], [0, 1], 2).astype(np.uint8)
        import base64
        data = dict(n=N, dx=DX, L_cav=L_CAV, L_vc=L_VC, wall=WALL, t_base=T_BASE, t_lid=T_LID, h_cav=H_CAV,
                    step=STEP, pocket=POCKET, t_cw=T_CW, tscale=3.0 / 255,
                    t=base64.b64encode(tq.T.tobytes()).decode(), d=base64.b64encode(dq.T.tobytes()).decode(),
                    pillars=pillars, posts_all=pts, posts_ring=ring_pts,
                    dies=[dict(name=n, x=x0, y=y0, hx=hx, hy=hy, P=P) for (n, x0, y0, hx, hy, P) in DIES],
                    baseline=dict(q_cap=rb_c["q_cap"], margin=rb_c["margin"], T_soc_c=rb_c["T_soc"], T_hbm_c=rb_c["T_hbm"],
                                  T_soc_b=rb_b["T_soc"], T_hbm_b=rb_b["T_hbm"], T_v=rb_c["T_v"], dPv=rb_c["dPv"]),
                    perf=results, zones=zone_stats)
        json.dump(data, open(out_json, "w"), separators=(",", ":"))

if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else None)
