"""DfAM Practitioner Program, Lab 8 - compliance topology optimisation in Python (starter code).

A compact Python version of the 88-line MATLAB code (Andreassen et al., 2011):
SIMP interpolation, sensitivity or density filter, optimality-criteria update.
Problem: half MBB beam (symmetry on the left edge, roller at the bottom-right corner, load at the top-left).

Run:  python T8_topopt.py                      default 60 x 20 elements, volume fraction 0.5
      python T8_topopt.py 90 30 0.4 3.0 2.0 1  nelx nely volfrac penal rmin ft   (ft: 0 sensitivity, 1 density filter)

Exercises: change rmin (1.5, 3, 6), volfrac and penal; compare the two filters; then apply the
printability check am_filter() to the result for two build directions.
"""
import sys
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import spsolve


def element_stiffness(nu=0.3):
    k = np.array([1/2 - nu/6, 1/8 + nu/8, -1/4 - nu/12, -1/8 + 3*nu/8, -1/4 + nu/12, -1/8 - nu/8, nu/6, 1/8 - 3*nu/8])
    return 1 / (1 - nu**2) * np.array([
        [k[0], k[1], k[2], k[3], k[4], k[5], k[6], k[7]], [k[1], k[0], k[7], k[6], k[5], k[4], k[3], k[2]],
        [k[2], k[7], k[0], k[5], k[6], k[3], k[4], k[1]], [k[3], k[6], k[5], k[0], k[7], k[2], k[1], k[4]],
        [k[4], k[5], k[6], k[7], k[0], k[1], k[2], k[3]], [k[5], k[4], k[3], k[2], k[1], k[0], k[7], k[6]],
        [k[6], k[3], k[4], k[1], k[2], k[7], k[0], k[5]], [k[7], k[2], k[1], k[4], k[3], k[6], k[5], k[0]]])


def optimise(nelx=60, nely=20, volfrac=0.5, penal=3.0, rmin=2.0, ft=1, max_iter=200, tol=0.01, verbose=True):
    Emin, E0 = 1e-9, 1.0
    ndof = 2 * (nelx + 1) * (nely + 1)
    KE = element_stiffness()
    edof = np.zeros((nelx * nely, 8), dtype=int)
    for ex in range(nelx):
        for ey in range(nely):
            el = ey + ex * nely
            n1 = (nely + 1) * ex + ey; n2 = (nely + 1) * (ex + 1) + ey
            edof[el] = [2*n1 + 2, 2*n1 + 3, 2*n2 + 2, 2*n2 + 3, 2*n2, 2*n2 + 1, 2*n1, 2*n1 + 1]
    iK = np.kron(edof, np.ones((8, 1), dtype=int)).flatten()
    jK = np.kron(edof, np.ones((1, 8), dtype=int)).flatten()
    # filter matrix H (linear weights within radius rmin)
    rows, cols, vals = [], [], []
    R = int(np.ceil(rmin)) - 1
    for i in range(nelx):
        for j in range(nely):
            r = i * nely + j
            for k in range(max(i - R, 0), min(i + R + 1, nelx)):
                for l in range(max(j - R, 0), min(j + R + 1, nely)):
                    w = rmin - np.hypot(i - k, j - l)
                    if w > 0:
                        rows.append(r); cols.append(k * nely + l); vals.append(w)
    H = coo_matrix((vals, (rows, cols)), shape=(nelx * nely, nelx * nely)).tocsc()
    Hs = np.asarray(H.sum(1)).flatten()
    # loads and supports: half MBB beam
    dofs = np.arange(ndof)
    fixed = np.union1d(dofs[0:2 * (nely + 1):2], np.array([ndof - 1]))
    free = np.setdiff1d(dofs, fixed)
    f = np.zeros(ndof); f[1] = -1.0
    x = volfrac * np.ones(nelx * nely); xPhys = x.copy()
    history = []
    for it in range(1, max_iter + 1):
        sK = (KE.flatten()[np.newaxis]).T * (Emin + xPhys ** penal * (E0 - Emin))
        K = coo_matrix((sK.flatten(order="F"), (iK, jK)), shape=(ndof, ndof)).tocsc()
        u = np.zeros(ndof)
        u[free] = spsolve(K[free, :][:, free], f[free])
        ce = (np.dot(u[edof], KE) * u[edof]).sum(1)
        c = ((Emin + xPhys ** penal * (E0 - Emin)) * ce).sum()
        dc = -penal * xPhys ** (penal - 1) * (E0 - Emin) * ce
        dv = np.ones(nelx * nely)
        if ft == 0:                                             # sensitivity filter
            dc = np.asarray(H @ (x * dc)).flatten() / Hs / np.maximum(1e-3, x)
        else:                                                   # density filter
            dc = np.asarray(H @ (dc / Hs)).flatten(); dv = np.asarray(H @ (dv / Hs)).flatten()
        # optimality-criteria update with bisection on the multiplier
        l1, l2, move = 0.0, 1e9, 0.2
        while (l2 - l1) / (l1 + l2) > 1e-3:
            lmid = 0.5 * (l1 + l2)
            xnew = np.maximum(0.0, np.maximum(x - move, np.minimum(1.0, np.minimum(x + move, x * np.sqrt(-dc / dv / lmid)))))
            xP = xnew if ft == 0 else np.asarray(H @ xnew).flatten() / Hs
            if xP.sum() > volfrac * nelx * nely:
                l1 = lmid
            else:
                l2 = lmid
        change = np.abs(xnew - x).max()
        x, xPhys = xnew, xP
        history.append(c)
        if verbose and (it == 1 or it % 10 == 0):
            print("it %3d   compliance %9.3f   volume %.3f   change %.3f" % (it, c, xPhys.mean(), change))
        if change < tol:
            break
    return xPhys.reshape((nelx, nely)).T, history            # rows = top to bottom, columns = left to right


def am_filter(x, build="up"):
    """Layer-wise printability check (non-smooth form of Langelaar's AM filter, 45 degree limit).

    x: density array with row 0 at the top. build = 'up' (base plate below) or 'down' (base plate above).
    Returns the printable density: each element is limited by the best-supported of the three elements
    in the layer beneath it. The differentiable version needed inside the optimisation loop is given in
    Langelaar (2017), Struct. Multidiscip. Optim. 55.
    """
    y = x[::-1].copy() if build == "up" else x.copy()          # y[0] = first layer on the base plate
    out = y.copy()
    for i in range(1, y.shape[0]):
        below = out[i - 1]
        pad = np.r_[below[0], below, below[-1]]
        support = np.maximum(np.maximum(pad[:-2], pad[1:-1]), pad[2:])
        out[i] = np.minimum(y[i], support)
    return out[::-1] if build == "up" else out


if __name__ == "__main__":
    a = sys.argv[1:]
    nelx, nely = (int(a[0]), int(a[1])) if len(a) >= 2 else (60, 20)
    volfrac = float(a[2]) if len(a) >= 3 else 0.5
    penal = float(a[3]) if len(a) >= 4 else 3.0
    rmin = float(a[4]) if len(a) >= 5 else 2.0
    ft = int(a[5]) if len(a) >= 6 else 1
    xP, hist = optimise(nelx, nely, volfrac, penal, rmin, ft)
    print("final compliance %.3f after %d iterations" % (hist[-1], len(hist)))
    solid = xP > 0.5
    for b in ("up", "down"):
        printable = am_filter(solid.astype(float), b) > 0.5
        lost = (solid & ~printable).sum() / solid.sum() * 100
        print("build direction %-4s : %.1f %% of the solid elements are unsupported at 45 degrees" % (b, lost))
    try:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        plt.figure(figsize=(8, 3)); plt.imshow(-xP, cmap="gray", interpolation="none"); plt.axis("off")
        plt.savefig("T8_result.png", dpi=150, bbox_inches="tight"); print("layout saved to T8_result.png")
    except Exception as e:
        print("plot skipped:", e)
