"""Mesh the cantilever with Gmsh, write the CalculiX input (clamped at x = 0, 500 N down at x = 100), solve, and read the
tip deflection and the stresses. Usage: python run.py 5   (the mesh size in mm)"""
import re, subprocess, sys
size = float(sys.argv[1]) if len(sys.argv) > 1 else 5
L, B, H, P, E, NU = 100.0, 10.0, 20.0, 500.0, 210000.0, 0.3     # mm, N, MPa

subprocess.run(["gmsh", "beam.geo", "-3", "-setnumber", "size", str(size), "-format", "inp", "-o", "mesh.inp"], check=True, capture_output=True)
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))
fixed = [i for i, (x, y, z) in nodes.items() if abs(x) < 1e-6]
tip = [i for i, (x, y, z) in nodes.items() if abs(x - L) < 1e-6]
with open("beam.inp", "w") as f:
    f.write("*INCLUDE, INPUT=mesh.inp\n")
    f.write("*NSET, NSET=FIXED\n" + "\n".join(map(str, fixed)) + "\n")
    f.write("*NSET, NSET=TIP\n" + "\n".join(map(str, tip)) + "\n")
    f.write(f"*MATERIAL, NAME=STEEL\n*ELASTIC\n{E}, {NU}\n*SOLID SECTION, ELSET=BEAM, MATERIAL=STEEL\n")
    f.write("*STEP\n*STATIC\n*BOUNDARY\nFIXED, 1, 3\n*CLOAD\n")
    f.write("".join(f"{i}, 3, {-P / len(tip):.6f}\n" for i in tip))     # 500 N shared over the end face
    f.write("*NODE PRINT, NSET=TIP\nU\n*NODE FILE\nU\n*EL FILE\nS\n*END STEP\n")
elements = sum(1 for _ in re.finditer(r"^\d+,", open("mesh.inp").read().split("*ELEMENT")[-1], re.M))
r = subprocess.run(["ccx", "beam"], capture_output=True, text=True)
# tip deflection: the average vertical movement of the end face, from beam.dat
uz = [float(l.split()[3]) for l in open("beam.dat") if re.match(r"^\s+\d+\s+-?\d", l)]
tip_defl = -sum(uz) / len(uz)
# stresses: the nodal stresses in beam.frd (block "-4  STRESS"), von Mises from the six components
stress, inblock = {}, False
for line in open("beam.frd"):
    if line.startswith(" -4  STRESS"): inblock = True; continue
    if inblock and line.startswith(" -3"): break
    if inblock and line.startswith(" -1"):
        nid = int(line[3:13]); v = [float(line[13 + 12 * k: 25 + 12 * k]) for k in range(6)]
        sx, sy, sz, sxy, syz, szx = v
        stress[nid] = (sx, (0.5 * ((sx - sy) ** 2 + (sy - sz) ** 2 + (sz - sx) ** 2) + 3 * (sxy ** 2 + syz ** 2 + szx ** 2)) ** 0.5)
def top_stress_at(x0, band=10.0):
    """Bending stress (sigma_x) on the top face at x0: a straight line fitted through the top-face nodes within +/- band mm,
    read at x0. The same rule on every mesh, so the meshes can be compared."""
    pts = [(nodes[i][0], s[0]) for i, s in stress.items() if abs(nodes[i][2] - H) < 1e-6 and abs(nodes[i][0] - x0) <= band]
    n = len(pts); mx = sum(x for x, _ in pts) / n; my = sum(y for _, y in pts) / n
    slope = sum((x - mx) * (y - my) for x, y in pts) / sum((x - mx) ** 2 for x, _ in pts)
    return my + slope * (x0 - mx)
vm_max = max(s[1] for s in stress.values())
print(f"mesh {size:g} mm: {len(nodes)} nodes, {elements} elements; tip deflection {tip_defl:.4f} mm; "
      f"bending stress on top 30 mm from the clamp {top_stress_at(30.0):.1f} MPa; highest von Mises {vm_max:.1f} MPa")
