"""Pictures: von Mises stress on the side of the beam (deformed shape, exaggerated), and the mesh study."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.tri as mtri

def read_frd(path):
    """Nodal displacements and von Mises stresses from a CalculiX .frd result file."""
    disp, vm, block = {}, {}, None
    for line in open(path):
        if line.startswith(" -4"):
            block = line.split()[1]; continue
        if line.startswith(" -3"):
            block = None; continue
        if line.startswith(" -1") and block in ("DISP", "STRESS"):
            nid = int(line[3:13]); v = [float(line[13 + 12 * k: 25 + 12 * k]) for k in range(6 if block == "STRESS" else 3)]
            if block == "DISP":
                disp[nid] = v
            else:
                sx, sy, sz, sxy, syz, szx = v
                vm[nid] = (0.5 * ((sx - sy) ** 2 + (sy - sz) ** 2 + (sz - sx) ** 2) + 3 * (sxy ** 2 + syz ** 2 + szx ** 2)) ** 0.5
    return disp, vm

nodes = {}
mode = None
for line in open("mesh.inp"):
    if line.startswith("*"):
        mode = "node" if line.upper().startswith("*NODE") else None; continue
    if mode == "node":
        i, x, y, z = line.split(",")[:4]; nodes[int(i)] = (float(x), float(y), float(z))
disp, vm = read_frd("beam.frd")
side = [i for i, (x, y, z) in nodes.items() if abs(y) < 1e-6]          # the face y = 0
scale = 50
X = [nodes[i][0] + scale * disp[i][0] for i in side]
Z = [nodes[i][2] + scale * disp[i][2] for i in side]
fig, ax = plt.subplots(2, 1, figsize=(9, 7.5), gridspec_kw={"height_ratios": [1.15, 1]})
tri = mtri.Triangulation([nodes[i][0] for i in side], [nodes[i][2] for i in side])
tri = mtri.Triangulation(X, Z, tri.triangles)
cs = ax[0].tricontourf(tri, [vm[i] for i in side], levels=20, cmap="plasma")
ax[0].plot([0, 100, 100, 0, 0], [0, 0, 20, 20, 0], color="#999", lw=0.8, ls="--")
fig.colorbar(cs, ax=ax[0], label="von Mises stress (MPa)")
ax[0].set_aspect("equal"); ax[0].set(title=f"Cantilever, 500 N at the tip: von Mises stress, shape x{scale} (dashed: before)", xlabel="x (mm)", ylabel="z (mm)")
# the mesh study (numbers from the three runs)
nodes_n = [515, 2024, 11323, 73993]; defl = [0.1211, 0.1215, 0.1216, 0.1217]
s30 = [52.5, 52.5, 52.5, 52.5]; vmax = [75.2, 75.7, 85.8, 109.8]
ax[1].semilogx(nodes_n, s30, "o-", color="#6d3fc4", label="bending stress 30 mm from the clamp (beam theory 52.5 MPa)")
ax[1].semilogx(nodes_n, vmax, "s--", color="#e0a000", label="highest von Mises (at the clamp's corner)")
ax[1].axhline(52.5, color="#6d3fc4", lw=0.8, ls=":"); ax[1].set_ylim(40, 120)
ax[1].set(xlabel="nodes in the mesh", ylabel="stress (MPa)", title="Mesh study: one number settles, the other keeps climbing")
ax[1].legend(fontsize=8.5)
fig.tight_layout()
fig.savefig("cantilever.png", dpi=150)
print("saved cantilever.png")
