"""
heath frame: shell finite-element check of the beam model.

Every tube is meshed as a thin shell at its true diameter and wall, with the tubes cut and joined where they meet
(gmsh), and solved as a linear static problem in CalculiX. Unlike the beam model this sees the joints: how a strut
dents the wall of the tube it lands on, and the stress that gathers round each weld line.

Units mm, N, MPa. Run:  python3 shell_fea.py [mesh_small mesh_big]
"""
import sys, json, subprocess, numpy as np, gmsh

src = open('frame_analysis.py').read().split("if __name__ == '__main__':")[0]
ns = {'__name__': 'x'}; _argv = sys.argv; sys.argv = ['x', 'geometry.json']; exec(compile(src, 'fa', 'exec'), ns); sys.argv = _argv
N, SECTIONS, MATERIAL, LANDS = ns['N'], dict(ns['SECTIONS']), ns['MATERIAL'], ns['STRUT_LANDS']
SECTIONS['bb shell'] = (40.0, 2.5)
RIDER, REAR, BUMP, G = ns['RIDER_KG'], ns['REAR_KG'], ns['BUMP'], 9.81
h_small, h_big = (float(sys.argv[1]), float(sys.argv[2])) if len(sys.argv) > 2 else (4.0, 6.0)

# tubes as centre-line runs: (name, section, [points]); earlier in PRIORITY = runs through, later ones are cut to fit it
P = lambda n: N[n]
tubes = [('head tube', 'head tube', [P('HT_BOT'), P('HT_TOP')]),
         ('long bar', 'long bar', [P('BAR_REAR'), P('BAR_FRONT')]),      # drawn straight: its 1 degree kink only makes slivers in the mesh
         ('bb shell', 'bb shell', [np.array([0, -34.0, 0]), np.array([0, 34.0, 0])]),
         ('seat tube', 'seat tube', [P('BB'), P('ST_TOP')]), ('down tube', 'down tube', [P('BB'), P('DT_END')]),
         ('front strut', 'front strut', [P('DT_END'), P('BAR_FSTRUT')])]
for s, sgn in (('L', 1), ('R', -1)):
    drop = P(f'DROP_{s}'); ss_bot = drop + [0, 0, 8]; back = lambda a, b, d: b + (a - b) / np.linalg.norm(a - b) * d   # stop short of the dropout plate
    tubes += [(f'chain stay {s} a', 'chain stay', [P(f'CS_BB_{s}'), P(f'CS_BEND_{s}')]), (f'chain stay {s} b', 'chain stay', [P(f'CS_BEND_{s}'), back(P(f'CS_BEND_{s}'), drop, 26)]),
              (f'seat stay {s}', 'seat stay', [P(f'SS_TOP_{s}'), back(P(f'SS_TOP_{s}'), ss_bot, 26)]),
              (f'rear strut {s}', 'rear strut', [P('BAR_RSTRUT') + [0, sgn * 14, -6], P(f'SS_MID_{s}')])]
PRIORITY = ['head tube', 'long bar', 'bb shell', 'seat tube', 'down tube', 'chain stay', 'seat stay', 'rear strut', 'front strut']

gmsh.initialize(); gmsh.option.setNumber('General.Terminal', 0); occ = gmsh.model.occ
surf = []                                                      # (tag, tube index)
for i, (name, sec, pts) in enumerate(tubes):
    D, t = SECTIONS[sec]; r = (D - t) / 2; a, b = pts
    for half in (0, 1):                                         # two half-shells: a closed cylinder face cannot be meshed after cutting
        vol = occ.addCylinder(*a, *(b - a), r, angle=np.pi)
        if half: occ.rotate([(3, vol)], *a, *(b - a), np.pi)
        occ.synchronize(); faces = gmsh.model.getBoundary([(3, vol)], oriented=False)
        lateral = max(faces, key=lambda f: occ.getMass(2, f[1]))[1]
        occ.remove([(3, vol)]); occ.remove([f for f in faces if f[1] != lateral], recursive=True); surf.append((lateral, i))
occ.synchronize()
out, omap = occ.fragment([(2, s) for s, _ in surf], []); occ.synchronize()
piece = {}                                                     # surface piece -> tube index (first owner wins; shared pieces are identical)
for (s, i), kids in zip(surf, omap):
    for d, k in kids: piece.setdefault(k, i)
def axis_dist(c, a, b):
    d = (b - a) / np.linalg.norm(b - a); u = c - a; s = u @ d; return np.linalg.norm(u - s * d), s, np.linalg.norm(b - a)
drop_pieces = []
for k, i in piece.items():                                      # cut each tube back to the wall of any higher-priority tube it runs into
    c = np.array(occ.getCenterOfMass(2, k)); pi = PRIORITY.index(tubes[i][1])
    for j, (nm, sec, (a, b)) in enumerate(tubes):
        if j == i or PRIORITY.index(sec) > pi or (PRIORITY.index(sec) == pi and j >= i): continue
        dist, s, L = axis_dist(c, a, b); D, t = SECTIONS[sec]
        if dist < (D - t) / 2 - 0.3 and -1 < s < L + 1: drop_pieces.append(k); break
occ.remove([(2, k) for k in set(drop_pieces)], recursive=True); occ.synchronize()
keep = {k: i for k, i in piece.items() if k not in set(drop_pieces)}
for k, i in keep.items():
    D, _ = SECTIONS[tubes[i][1]]; gmsh.model.mesh.setSize(gmsh.model.getBoundary([(2, k)], recursive=True), h_small if D < 25 else h_big)
gmsh.option.setNumber('Mesh.MeshSizeMax', h_big); gmsh.option.setNumber('Mesh.MeshSizeMin', h_small * 0.6); gmsh.option.setNumber('Mesh.MeshSizeFromCurvature', 12)
gmsh.option.setNumber('Mesh.ElementOrder', 2); gmsh.option.setNumber('Mesh.SecondOrderLinear', 1); gmsh.option.setNumber('Mesh.Algorithm', 6)
gmsh.model.mesh.generate(2); gmsh.model.mesh.removeDuplicateNodes()
tags, xyz, _ = gmsh.model.mesh.getNodes(); xyz = xyz.reshape(-1, 3); nid = {int(t): i for i, t in enumerate(tags)}
elems = []                                                      # (element id, 6 nodes, tube index)
eid = 0
for k, i in keep.items():
    types, etags, enodes = gmsh.model.mesh.getElements(2, k)
    for ty, en in zip(types, enodes):
        if ty != 9: continue
        for row in np.asarray(en, int).reshape(-1, 6):
            p = [xyz[nid[int(n)]] for n in row[:3]]; area = 0.5 * np.linalg.norm(np.cross(p[1] - p[0], p[2] - p[0]))
            if area < 0.05 or len(set(int(n) for n in row)) < 6: continue          # slivers left by the cutting
            eid += 1; elems.append((eid, row, i))
gmsh.finalize()
# close up the hair-thin edges left where three surfaces meet: merge the two ends of any edge under 0.6 mm
merge = {}
def root(n):
    while n in merge: n = merge[n]
    return n
for _, row, _ in elems:
    c = [int(n) for n in row[:3]]
    for u, v in ((c[0], c[1]), (c[1], c[2]), (c[2], c[0])):
        ru, rv = root(u), root(v)
        if ru != rv and np.linalg.norm(xyz[nid[u]] - xyz[nid[v]]) < 1.1: merge[max(ru, rv)] = min(ru, rv)
fixed_elems = []
for e, row, i in elems:
    r2 = np.array([root(int(n)) for n in row])
    if len(set(r2[:3])) == 3: fixed_elems.append((e, r2, i))
elems = fixed_elems
used = sorted({int(n) for _, row, _ in elems for n in row}); X = {n: xyz[nid[n]].copy() for n in used}
for _, row, _ in elems:                                          # mid-side nodes back onto the middle of their (possibly moved) edges
    for m, (u, v) in zip(row[3:], ((row[0], row[1]), (row[1], row[2]), (row[2], row[0]))): X[int(m)] = (X[int(u)] + X[int(v)]) / 2
print(f'mesh: {len(elems)} six-node shell elements, {len(used)} nodes (sizes {h_small:g} / {h_big:g} mm)')

def near(p, r, tube_filter=None):
    ok = set()
    for e, row, i in elems:
        if tube_filter and not tube_filter(tubes[i][0]): continue
        for n in row:
            if np.linalg.norm(X[int(n)] - p) < r: ok.add(int(n))
    return sorted(ok)
ref = max(used) + 1
sets, rigid, bcs = {}, [], []
def rigid_body(name, nodes, at, fix):
    global ref
    sets[name] = nodes; r1, r2 = ref, ref + 1; ref += 2; X[r1] = np.asarray(at, float); X[r2] = np.asarray(at, float); rigid.append((name, r1, r2))
    for d in fix: bcs.append((r1 if d <= 3 else r2, d if d <= 3 else d - 3))
rigid_body('DROPL', near(P('DROP_L') + [0, 0, 4], 38, lambda n: n.endswith('L b') or n == 'seat stay L'), P('DROP_L'), [1, 2, 3])   # the dropout plate: rigid, pinned at the axle
rigid_body('DROPR', near(P('DROP_R') + [0, 0, 4], 38, lambda n: n.endswith('R b') or n == 'seat stay R'), P('DROP_R'), [1, 3])
ends = near(P('HT_BOT'), 22, lambda n: n == 'head tube') + near(P('HT_TOP'), 22, lambda n: n == 'head tube')
rigid_body('FORK', sorted(set(ends)), ns['F_AX'], [2, 3, 4])           # a rigid fork and steerer through both headset bearings, front axle on a roller
loads = {'rider': [], 'rear': []}
def spread(case, nodes, newtons):
    for n in nodes: loads[case].append((n, 3, -newtons / len(nodes)))
spread('rider', near(P('ST_TOP'), 16, lambda n: n == 'seat tube'), RIDER * 0.7 * G * BUMP)
spread('rider', near(np.array([0, 34.0, 0]), 21.5, lambda n: n == 'bb shell') + near(np.array([0, -34.0, 0]), 21.5, lambda n: n == 'bb shell'), RIDER * 0.3 * G * BUMP)
for x in ns['REAR_RACK_X']:
    p = ns['bar_at'](x); top = [n for n in near(p, 26, lambda n: n.startswith('long bar')) if X[n][2] > p[2] + 6 and abs(X[n][0] - x) < 12]
    spread('rear', top, 1.0 * G * BUMP / 3)                              # per kg on the rails

with open('fea/frame.inp', 'w') as f:
    f.write('*NODE, NSET=NALL\n' + ''.join(f'{n},{X[n][0]:.5f},{X[n][1]:.5f},{X[n][2]:.5f}\n' for n in sorted(X)))
    for i, (name, sec, _) in enumerate(tubes):
        rows = [(e, row) for e, row, k in elems if k == i]
        if not rows: continue
        f.write(f'*ELEMENT, TYPE=S6, ELSET=T{i}\n' + ''.join(f'{e},' + ','.join(str(int(n)) for n in row) + '\n' for e, row in rows))
        f.write(f'*SHELL SECTION, ELSET=T{i}, MATERIAL=STEEL\n{SECTIONS[sec][1]}\n')
    f.write('*ELSET, ELSET=EALL\n' + ''.join(f'T{i},\n' for i in range(len(tubes)) if any(k == i for _, _, k in elems)))
    f.write('*NSET, NSET=REFS\n' + ''.join(f'{r1},\n' for _, r1, _ in rigid))
    f.write(f'*MATERIAL, NAME=STEEL\n*ELASTIC\n{MATERIAL["E"]},0.29\n')
    for name, nodes in sets.items(): f.write(f'*NSET, NSET={name}\n' + ''.join(f'{n},\n' for n in nodes))
    for name, r1, r2 in rigid: f.write(f'*RIGID BODY, NSET={name}, REF NODE={r1}, ROT NODE={r2}\n')
    f.write('*BOUNDARY\n' + ''.join(f'{n},{d},{d}\n' for n, d in bcs))
    for case in ('rider', 'rear'):
        f.write('*STEP\n*STATIC\n*CLOAD, OP=NEW\n' + ''.join(f'{n},{d},{v:.6f}\n' for n, d, v in loads[case]))
        f.write('*EL PRINT, ELSET=EALL\nS\n*NODE PRINT, NSET=REFS\nRF\n*END STEP\n')
json.dump({'tubes': [(t[0], t[1]) for t in tubes], 'elem_tube': {str(e): i for e, _, i in elems},
           'centroid': {str(e): np.mean([X[int(n)] for n in row[:3]], axis=0).tolist() for e, row, _ in elems},
           'exclude_pts': [P('DROP_L').tolist(), P('DROP_R').tolist(), P('HT_BOT').tolist(), P('HT_TOP').tolist(), P('ST_TOP').tolist(), [0, 34, 0], [0, -34, 0]] + [ns['bar_at'](x).tolist() for x in ns['REAR_RACK_X']]}, open('fea/meta.json', 'w'))
print('wrote fea/frame.inp')
