Repository navigation
Expand file tree
/
Copy pathcalc.py
More file actions
637 lines (537 loc) · 30.6 KB
/
Copy pathcalc.py
File metadata and controls
637 lines (537 loc) · 30.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
import FreeCAD
import FreeCADGui as Gui
import Part, os, math
from PySide import QtWidgets
import numpy as np
from eds_config import module_path
from edsFEM.systems import System
from edsFEM.points import Point
ICONPATH = os.path.join(module_path, "resources")
def _show_error(msg):
b = QtWidgets.QMessageBox()
b.setIcon(QtWidgets.QMessageBox.Critical)
b.setWindowTitle("Error")
b.setText(msg)
b.setStandardButtons(QtWidgets.QMessageBox.Ok)
b.exec_()
def _beam_local_axes(p1, p2):
"""edsFEM local coordinate axes — mirrors coord_sys() in elements.py."""
dx = p2.x - p1.x; dy = p2.y - p1.y; dz = p2.z - p1.z
norm = math.sqrt(dx*dx + dy*dy + dz*dz)
xa = np.array([dx, dy, dz]) / norm
if abs(xa[2]) < 1e-8:
za = np.array([0.0, 0.0, 1.0])
elif abs(xa[0]) < 1e-8 and abs(xa[1]) < 1e-8:
za = np.array([-1.0, 0.0, 0.0])
else:
zd = (xa[0]**2 + xa[1]**2) / xa[2]
za = np.array([-xa[0], -xa[1], zd])
za /= np.linalg.norm(za)
ya = -np.cross(xa, za)
return xa, ya, za
# ── edsFEM adapter (shim layer) ───────────────────────────────────────────────
class EdsFEMAdapter:
"""Thin wrapper around edsFEM System to keep Calc.execute() clean."""
def __init__(self):
self.model = System()
self.node_pts = [] # list[Point] — input geometry nodes (mm)
self.beam_ids = [] # list[Beam] — edsFEM beam objects
# ── nodes ─────────────────────────────────────────────────────────────────
def add_node(self, x_mm, y_mm, z_mm):
pt = Point(float(x_mm), float(y_mm), float(z_mm))
self.node_pts.append(pt)
return len(self.node_pts) - 1
def get_or_add_node(self, x_mm, y_mm, z_mm, tol=0.5):
for i, pt in enumerate(self.node_pts):
if abs(pt.x - x_mm) < tol and abs(pt.y - y_mm) < tol and abs(pt.z - z_mm) < tol:
return i
return self.add_node(x_mm, y_mm, z_mm)
# ── elements ──────────────────────────────────────────────────────────────
def add_element(self, n1_idx, n2_idx, profile):
"""Add beam. profile must expose .E .G .A .I_y .I_z .I_t in N/mm² and mm."""
beam = self.model.add_beam(
self.node_pts[n1_idx], self.node_pts[n2_idx], profile=profile)
self.beam_ids.append(beam)
return len(self.beam_ids) - 1
# ── boundary conditions ───────────────────────────────────────────────────
def find_beam_node(self, x_mm, y_mm, z_mm):
"""Return (beam_node, distance_mm) of the node closest to the given point."""
best, best_d = None, float('inf')
for beam in self.beam_ids:
for node in beam.nodes:
p = node.point
d = math.sqrt((p.x - x_mm)**2 + (p.y - y_mm)**2 + (p.z - z_mm)**2)
if d < best_d:
best_d = d
best = node
return best, best_d
def add_support(self, beam_node, t_x, t_y, t_z, r_x, r_y, r_z):
self.model.add_support(beam_node,
t_x=t_x, t_y=t_y, t_z=t_z,
r_x=r_x, r_y=r_y, r_z=r_z)
# ── loads ─────────────────────────────────────────────────────────────────
def add_point_load(self, beam_node, Fx_N, Fy_N, Fz_N):
self.model.add_p_load(beam_node, Fx=Fx_N, Fy=Fy_N, Fz=Fz_N, Tx=0, Ty=0, Tz=0)
def add_distributed_load(self, elem_idx, w_start_Npmm, w_end_Npmm, direction):
"""
direction: signed unit vector e.g. [0,0,-1] for gravity.
w_start / w_end: positive magnitudes in N/mm.
"""
beam = self.beam_ids[elem_idx]
end_val = w_end_Npmm if abs(w_end_Npmm - w_start_Npmm) > 1e-9 else None
self.model.add_q_load(
start_val=w_start_Npmm,
start_point=beam.point_1,
end_point=beam.point_2,
end_val=end_val,
direction=direction,
beam=beam)
# ── solve ─────────────────────────────────────────────────────────────────
def solve(self):
self.model.assemble(selfweight=None)
self.model.solve()
self.model.postprocess()
# ── results ───────────────────────────────────────────────────────────────
def _resample(self, arr2d, num_pts):
if arr2d is None or len(arr2d) == 0:
return np.zeros(num_pts)
vals = arr2d[:, 3] if arr2d.ndim > 1 else np.asarray(arr2d, dtype=float)
if len(vals) == num_pts:
return vals.copy()
return np.interp(np.linspace(0, 1, num_pts),
np.linspace(0, 1, len(vals)), vals)
def get_forces(self, elem_idx, num_pts):
"""Return dict with My/Mz/Vy/Vz/N/T arrays (raw edsFEM units: N·mm and N)."""
beam = self.beam_ids[elem_idx]
beam.moments(s=2)
beam.shear_forces(s=2)
beam.normal_forces(s=2)
return {
'My': self._resample(beam.My, num_pts),
'Mz': self._resample(beam.Mz, num_pts),
'Vy': self._resample(beam.Vy, num_pts),
'Vz': self._resample(beam.Vz, num_pts),
'N': self._resample(beam.N, num_pts),
'T': self._resample(beam.Mx, num_pts),
}
def get_displacements(self, elem_idx, num_pts):
"""Return dict with dx/dy/dz arrays in mm (global coordinates)."""
beam = self.beam_ids[elem_idx]
try:
beam.displacements()
n_d = len(beam.dz) if beam.dz is not None else 0
if n_d < 2:
raise ValueError("no displacement data")
x_o = np.linspace(0, 1, n_d)
x_n = np.linspace(0, 1, num_pts)
dz = beam.dz
dx = beam.dx if beam.dx is not None else np.zeros(n_d)
dy = beam.dy if beam.dy is not None else np.zeros(n_d)
return {
'dz': np.interp(x_n, x_o, dz),
'dx': np.interp(x_n, x_o, dx),
'dy': np.interp(x_n, x_o, dy),
}
except Exception:
return {'dz': np.zeros(num_pts),
'dx': np.zeros(num_pts),
'dy': np.zeros(num_pts)}
# ── Calc ──────────────────────────────────────────────────────────────────────
class Calc:
def __init__(self, obj, elements):
obj.Proxy = self
obj.addProperty("App::PropertyLinkList", "ListElements", "Calc",
"elements for analysis").ListElements = elements
obj.addProperty("App::PropertyString", "LengthUnit", "Calc",
"length unit").LengthUnit = 'm'
obj.addProperty("App::PropertyString", "ForceUnit", "Calc",
"force unit").ForceUnit = 'kN'
obj.addProperty("App::PropertyStringList", "NameMembers", "Calc", "member names")
obj.addProperty("App::PropertyVectorList", "Nodes", "Calc", "node positions (mm)")
# force diagram results
obj.addProperty("App::PropertyStringList", "MomentY", "ResultMoment", "My per member (kN·m)")
obj.addProperty("App::PropertyStringList", "MomentZ", "ResultMoment", "Mz per member (kN·m)")
obj.addProperty("App::PropertyFloatList", "MinMomentY", "ResultMoment", "")
obj.addProperty("App::PropertyFloatList", "MaxMomentY", "ResultMoment", "")
obj.addProperty("App::PropertyFloatList", "MinMomentZ", "ResultMoment", "")
obj.addProperty("App::PropertyFloatList", "MaxMomentZ", "ResultMoment", "")
obj.addProperty("App::PropertyInteger", "NumPointsMoment", "NumPoints", "").NumPointsMoment = 6
obj.addProperty("App::PropertyStringList", "ShearY", "ResultShear", "Vy per member (kN)")
obj.addProperty("App::PropertyStringList", "ShearZ", "ResultShear", "Vz per member (kN)")
obj.addProperty("App::PropertyFloatList", "MinShearY", "ResultShear", "")
obj.addProperty("App::PropertyFloatList", "MaxShearY", "ResultShear", "")
obj.addProperty("App::PropertyFloatList", "MinShearZ", "ResultShear", "")
obj.addProperty("App::PropertyFloatList", "MaxShearZ", "ResultShear", "")
obj.addProperty("App::PropertyInteger", "NumPointsShear", "NumPoints", "").NumPointsShear = 4
obj.addProperty("App::PropertyStringList", "AxialForce", "ResultAxial", "N per member (kN)")
obj.addProperty("App::PropertyInteger", "NumPointsAxial", "NumPoints", "").NumPointsAxial = 3
obj.addProperty("App::PropertyStringList", "Torque", "ResultTorque", "Mx per member (kN·m)")
obj.addProperty("App::PropertyFloatList", "MinTorque","ResultTorque", "")
obj.addProperty("App::PropertyFloatList", "MaxTorque","ResultTorque", "")
obj.addProperty("App::PropertyInteger", "NumPointsTorque", "NumPoints", "").NumPointsTorque = 3
# displacement results (global X/Y/Z in mm)
obj.addProperty("App::PropertyStringList", "DeflectionX", "ResultDeflection", "dx global X (mm)")
obj.addProperty("App::PropertyStringList", "DeflectionY", "ResultDeflection", "dy global Y (mm)")
obj.addProperty("App::PropertyStringList", "DeflectionZ", "ResultDeflection", "dz global Z (mm)")
obj.addProperty("App::PropertyFloatList", "MinDeflectionY", "ResultDeflection", "")
obj.addProperty("App::PropertyFloatList", "MaxDeflectionY", "ResultDeflection", "")
obj.addProperty("App::PropertyFloatList", "MinDeflectionZ", "ResultDeflection", "")
obj.addProperty("App::PropertyFloatList", "MaxDeflectionZ", "ResultDeflection", "")
obj.addProperty("App::PropertyInteger", "NumPointsDeflection", "NumPoints", "").NumPointsDeflection = 6
# reaction results
obj.addProperty("App::PropertyStringList", "ReactionForces",
"ResultReactions", "Fx,Fy,Fz per support (kN)")
obj.addProperty("App::PropertyStringList", "ReactionMoments",
"ResultReactions", "Tx,Ty,Tz per support (kN·m)")
obj.addProperty("App::PropertyVectorList", "ReactionPositions",
"ResultReactions", "support positions (mm)")
obj.addProperty("App::PropertyStringList", "ReactionLabels",
"ResultReactions", "support labels")
# ── profile builder ───────────────────────────────────────────────────────
def _make_profile(self, section_obj, mat_obj):
"""
Build a minimal profile object for edsFEM from FreeCAD section + material.
All values output in N/mm² (MPa) and mm.
"""
def _qty(prop, unit):
"""Safely read a FreeCAD Quantity property."""
if prop is None:
return 0.0
if isinstance(prop, (int, float)):
return float(prop)
if hasattr(prop, 'getValueAs'):
return float(prop.getValueAs(unit))
try:
return float(prop)
except Exception:
return 0.0
def _parse_str(s, default):
try:
return float(str(s).split()[0]) if isinstance(s, str) else float(s)
except Exception:
return default
class Profile:
pass
p = Profile()
p.A = _qty(getattr(section_obj, 'AreaSection', None), 'mm^2')
p.I_y = _qty(getattr(section_obj, 'MomentInertiaY', None), 'mm^4')
p.I_z = _qty(getattr(section_obj, 'MomentInertiaZ', None), 'mm^4')
p.I_t = _qty(getattr(section_obj, 'MomentInertiaPolar', None), 'mm^4')
# aliases used by some edsFEM versions
p.Iy = p.I_y; p.Iz = p.I_z; p.J = p.I_t
p.Wy_el = p.Wz_el = p.Wy_pl = p.Wz_pl = 0.0
p.g = p.g_stiff = 0
p.designation = getattr(section_obj, 'Label', 'Custom')
# Young's / shear modulus — try Material dict first (FreeCAD card format)
E = 210000.0 # default steel (N/mm²)
G = E / 2.6 # ν ≈ 0.3
mat_dict = None
raw_md = getattr(mat_obj, 'Material', None)
if raw_md is not None and hasattr(raw_md, 'keys'):
mat_dict = raw_md
if mat_dict is not None:
E = _parse_str(mat_dict.get('YoungsModulus',
mat_dict.get('YoungModulus', E)), E)
g_str = mat_dict.get('ShearModulus', '')
if g_str:
G = _parse_str(g_str, E / 2.6)
else:
nu = _parse_str(mat_dict.get('PoissonRatio', '0.3'), 0.3)
G = E / (2 * (1 + nu))
else:
# fall back to direct properties
for attr in ('ModulusElasticity', 'YoungsModulus', 'YoungModulus', 'E'):
val = getattr(mat_obj, attr, None)
if val is not None:
E = _qty(val, 'MPa')
break
for attr in ('ShearModulus', 'G'):
val = getattr(mat_obj, attr, None)
if val is not None:
G = _qty(val, 'MPa')
break
else:
nu = _qty(getattr(mat_obj, 'PoissonRatio', 0.3), '')
G = E / (2 * (1 + (nu if nu > 0 else 0.3)))
p.E = E
p.G = G
return p
# ── execute ───────────────────────────────────────────────────────────────
def execute(self, obj):
lines = [e for e in obj.ListElements
if ('Line' in e.Name or 'Wire' in e.Name)
and hasattr(e, 'SectionMember') and hasattr(e, 'MaterialMember')]
loads = [e for e in obj.ListElements if 'Load' in e.Name]
supports = [e for e in obj.ListElements if 'Suport' in e.Name]
if not lines:
_show_error("No structural members with section/material found in selection.")
return
try:
print("\n" + "=" * 60)
print("STARTING FEA — edsFEM (via EdsFEMAdapter)")
print("=" * 60)
fea = EdsFEMAdapter()
element_names = []
# ── build beams ──────────────────────────────────────────────────
print("\nADDING BEAMS...")
for line_obj in lines:
profile = self._make_profile(line_obj.SectionMember,
line_obj.MaterialMember)
print(f" Profile {profile.designation}: E={profile.E:.0f} MPa "
f"A={profile.A:.0f} mm² Iy={profile.I_y:.0f} mm⁴")
for edge_idx, edge in enumerate(line_obj.Shape.Edges):
v1 = edge.Vertexes[0].Point
v2 = edge.Vertexes[1].Point
n1 = fea.get_or_add_node(v1.x, v1.y, v1.z)
n2 = fea.get_or_add_node(v2.x, v2.y, v2.z)
fea.add_element(n1, n2, profile)
name = f"{line_obj.Name}_{edge_idx}"
element_names.append(name)
p1 = fea.node_pts[n1]; p2 = fea.node_pts[n2]
L = math.sqrt((p2.x-p1.x)**2+(p2.y-p1.y)**2+(p2.z-p1.z)**2)
print(f" {name} L={L:.1f} mm")
print(f"\n✓ {len(fea.beam_ids)} beams, {len(fea.node_pts)} geometry nodes")
# ── supports ─────────────────────────────────────────────────────
print("\nADDING SUPPORTS...")
support_count = 0
for support_obj in supports:
try:
pos = support_obj.Placement.Base # mm (FreeCAD geometry)
node, dist = fea.find_beam_node(pos.x, pos.y, pos.z)
if node is None or dist > 10.0:
print(f" ✗ No beam node for {support_obj.Label} (dist={dist:.1f} mm)")
continue
def bc(flag): return 0 if flag else None
t_x = bc(getattr(support_obj, 'FixTranslationX', True))
t_y = bc(getattr(support_obj, 'FixTranslationY', True))
t_z = bc(getattr(support_obj, 'FixTranslationZ', True))
r_x = bc(getattr(support_obj, 'FixRotationX', False))
r_y = bc(getattr(support_obj, 'FixRotationY', False))
r_z = bc(getattr(support_obj, 'FixRotationZ', False))
fea.add_support(node, t_x, t_y, t_z, r_x, r_y, r_z)
trans = sum(1 for v in (t_x,t_y,t_z) if v==0)
rot = sum(1 for v in (r_x,r_y,r_z) if v==0)
kind = "FIXED" if (trans==3 and rot==3) else \
"PINNED" if (trans==3 and rot==0) else \
"ROLLER" if (trans==1 and rot==0) else f"T{trans}R{rot}"
print(f" ✓ {support_obj.Label} {kind} dist={dist:.2f} mm")
support_count += 1
except Exception as e:
print(f" ✗ {support_obj.Label}: {e}")
# ── loads ─────────────────────────────────────────────────────────
print("\nADDING LOADS...")
_dir_map = {'-Z':[0,0,-1],'+Z':[0,0,1],
'-Y':[0,-1,0],'+Y':[0,1,0],
'-X':[-1,0,0],'+X':[1,0,0]}
loads_added = 0
for load_obj in loads:
try:
dir_str = getattr(load_obj, 'GlobalDirection', '-Z')
direction = _dir_map.get(dir_str, [0, 0, -1])
obj_base = getattr(load_obj, 'ObjectBase', None)
if not obj_base or not obj_base[0][1]:
print(f" ✗ {load_obj.Label}: no ObjectBase, skipping")
continue
base_obj = obj_base[0][0]
sub = obj_base[0][1][0]
if 'Edge' in sub:
# ── distributed load ──────────────────────────────────
edge_num = int(sub.replace('Edge', '')) - 1
tgt_name = f"{base_obj.Name}_{edge_num}"
if tgt_name not in element_names:
print(f" ✗ Beam '{tgt_name}' not found"); continue
elem_idx = element_names.index(tgt_name)
def _Npmm(prop_name):
prop = getattr(load_obj, prop_name, None)
if prop is None: return 0.0
# cascade: N/m → N/mm; kN/m → N/mm (1:1); kN → interpret as kN/m
try: return float(prop.getValueAs('N/m')) / 1000.0
except: pass
try: return float(prop.getValueAs('kN/m'))
except: pass
try: return float(prop.getValueAs('kN')) # UI stores kN as kN/m
except: return 0.0
w_s = _Npmm('InitialLoading')
w_e = _Npmm('FinalLoading') or w_s
if w_s == 0.0:
print(f" ✗ {load_obj.Label}: zero intensity, skipping"); continue
fea.add_distributed_load(elem_idx, abs(w_s), abs(w_e), direction)
print(f" ✓ Dist load on {tgt_name}: "
f"{w_s:.5f} N/mm dir={direction}")
loads_added += 1
elif 'Vertex' in sub:
# ── nodal (point) load ────────────────────────────────
vidx = int(sub.replace('Vertex', '')) - 1
vpt = base_obj.Shape.Vertexes[vidx].Point
node, dist = fea.find_beam_node(vpt.x, vpt.y, vpt.z)
if node is None or dist > 1.0:
print(f" ✗ No node within 1 mm of vertex "
f"({vpt.x:.0f},{vpt.y:.0f},{vpt.z:.0f})"); continue
try: F_N = float(load_obj.NodalLoading.getValueAs('N'))
except:
try: F_N = float(load_obj.NodalLoading.getValueAs('kN')) * 1000
except: F_N = 0.0
fea.add_point_load(node,
F_N * direction[0],
F_N * direction[1],
F_N * direction[2])
print(f" ✓ Point load {F_N:.1f} N dir={direction}")
loads_added += 1
else:
print(f" ✗ {load_obj.Label}: unknown sub-element '{sub}'")
except Exception as e:
import traceback
print(f" ✗ Load {load_obj.Label}: {e}")
print(traceback.format_exc())
print(f"\n✓ Supports: {support_count} Loads: {loads_added}")
# ── solve ─────────────────────────────────────────────────────────
print("\nSOLVING...")
fea.solve()
print("✓ Solution converged!")
# ── extract forces + displacements ────────────────────────────────
print("\nEXTRACTING RESULTS...")
momentY=[]; momentZ=[]; shearY=[]; shearZ=[]; axialForce=[]; torque=[]
deflX=[]; deflY=[]; deflZ=[]
minMY=[]; maxMY=[]; minMZ=[]; maxMZ=[]
minVY=[]; maxVY=[]; minVZ=[]; maxVZ=[]
minT=[]; maxT=[]
minDY=[]; maxDY=[]; minDZ=[]; maxDZ=[]
n_f = obj.NumPointsMoment
n_d = getattr(obj, 'NumPointsDeflection', 6)
for i in range(len(fea.beam_ids)):
# forces (raw edsFEM: N·mm for moments, N for shear/axial)
f = fea.get_forces(i, n_f)
my = f['My'] / 1e6 # N·mm → kN·m
mz = f['Mz'] / 1e6
vy = f['Vy'] / 1e3 # N → kN
vz = f['Vz'] / 1e3
n = f['N'] / 1e3
t = f['T'] / 1e6 # N·mm → kN·m
momentY.append(",".join(f"{v:.4f}" for v in my))
momentZ.append(",".join(f"{v:.4f}" for v in mz))
shearY.append( ",".join(f"{v:.4f}" for v in vy))
shearZ.append( ",".join(f"{v:.4f}" for v in vz))
axialForce.append(",".join(f"{v:.4f}" for v in n))
torque.append( ",".join(f"{v:.4f}" for v in t))
minMY.append(float(np.min(my))); maxMY.append(float(np.max(my)))
minMZ.append(float(np.min(mz))); maxMZ.append(float(np.max(mz)))
minVY.append(float(np.min(vy))); maxVY.append(float(np.max(vy)))
minVZ.append(float(np.min(vz))); maxVZ.append(float(np.max(vz)))
minT.append( float(np.min(t))); maxT.append( float(np.max(t)))
# displacements (already mm, global X/Y/Z)
d = fea.get_displacements(i, n_d)
deflX.append(",".join(f"{v:.6f}" for v in d['dx']))
deflY.append(",".join(f"{v:.6f}" for v in d['dy']))
deflZ.append(",".join(f"{v:.6f}" for v in d['dz']))
minDY.append(float(np.min(d['dy']))); maxDY.append(float(np.max(d['dy'])))
minDZ.append(float(np.min(d['dz']))); maxDZ.append(float(np.max(d['dz'])))
nm = element_names[i] if i < len(element_names) else f"elem{i}"
print(f" {nm}: "
f"My=[{float(np.min(my)):.2f}, {float(np.max(my)):.2f}] kN·m "
f"Vz=[{float(np.min(vz)):.2f}, {float(np.max(vz)):.2f}] kN "
f"dz=[{float(np.min(d['dz'])):.3f}, {float(np.max(d['dz'])):.3f}] mm")
# ── reactions via node equilibrium ────────────────────────────────
# For each support: sum local→global member-end forces.
# n1 end: R += T.T @ [N0, Vy0, Vz0] n2 end: R -= T.T @ [Nn, Vyn, Vzn]
print("\nREACTIONS (node equilibrium):")
r_forces=[]; r_moments=[]; r_positions=[]; r_labels=[]
for support_obj in supports:
loc = support_obj.Placement.Base # mm
RF = np.zeros(3)
RM = np.zeros(3)
for bi, beam in enumerate(fea.beam_ids):
if not beam.elements or bi >= len(axialForce):
continue
p1 = beam.elements[0].node_1.point
p2 = beam.elements[-1].node_2.point
d1 = math.sqrt((p1.x-loc.x)**2+(p1.y-loc.y)**2+(p1.z-loc.z)**2)
d2 = math.sqrt((p2.x-loc.x)**2+(p2.y-loc.y)**2+(p2.z-loc.z)**2)
if d1 > 5.0 and d2 > 5.0:
continue
xa, ya, za = _beam_local_axes(p1, p2)
T = np.array([xa, ya, za]) # T.T @ f_local = f_global
try:
N = [float(v) for v in axialForce[bi].split(',')]
Vy = [float(v) for v in shearY[bi].split(',')]
Vz = [float(v) for v in shearZ[bi].split(',')]
Mx = [float(v) for v in torque[bi].split(',')]
My = [float(v) for v in momentY[bi].split(',')]
Mz = [float(v) for v in momentZ[bi].split(',')]
except Exception:
continue
if d1 < 5.0:
RF += T.T @ np.array([N[0], Vy[0], Vz[0]])
RM += T.T @ np.array([Mx[0], My[0], Mz[0]])
if d2 < 5.0:
RF -= T.T @ np.array([N[-1], Vy[-1], Vz[-1]])
RM -= T.T @ np.array([Mx[-1],My[-1], Mz[-1]])
Fx,Fy,Fz = float(RF[0]),float(RF[1]),float(RF[2])
Tx,Ty,Tz = float(RM[0]),float(RM[1]),float(RM[2])
print(f" {support_obj.Label} at ({loc.x:.0f},{loc.y:.0f},{loc.z:.0f}) mm: "
f"Fx={Fx:.3f} Fy={Fy:.3f} Fz={Fz:.3f} kN")
r_forces.append(f"{Fx:.4f},{Fy:.4f},{Fz:.4f}")
r_moments.append(f"{Tx:.4f},{Ty:.4f},{Tz:.4f}")
r_positions.append(FreeCAD.Vector(loc.x, loc.y, loc.z))
r_labels.append(support_obj.Label)
# ── store all results ─────────────────────────────────────────────
obj.MomentY = momentY; obj.MomentZ = momentZ
obj.ShearY = shearY; obj.ShearZ = shearZ
obj.AxialForce = axialForce; obj.Torque = torque
obj.DeflectionX = deflX
obj.DeflectionY = deflY
obj.DeflectionZ = deflZ
obj.ReactionForces = r_forces
obj.ReactionMoments = r_moments
obj.ReactionPositions = r_positions
obj.ReactionLabels = r_labels
obj.MinMomentY = minMY; obj.MaxMomentY = maxMY
obj.MinMomentZ = minMZ; obj.MaxMomentZ = maxMZ
obj.MinShearY = minVY; obj.MaxShearY = maxVY
obj.MinShearZ = minVZ; obj.MaxShearZ = maxVZ
obj.MinTorque = minT; obj.MaxTorque = maxT
obj.MinDeflectionY = minDY; obj.MaxDeflectionY = maxDY
obj.MinDeflectionZ = minDZ; obj.MaxDeflectionZ = maxDZ
obj.Nodes = [FreeCAD.Vector(p.x, p.y, p.z) for p in fea.node_pts]
obj.NameMembers = element_names
print(f"\n{'='*60}")
print(f"✓ ANALYSIS COMPLETE — {len(element_names)} members "
f"{len(fea.node_pts)} nodes")
print("=" * 60 + "\n")
except Exception as e:
import traceback
msg = f"Analysis failed:\n{e}\n\n{traceback.format_exc()}"
print(msg)
_show_error(msg)
def onChanged(self, obj, prop):
pass
# ── view provider + command ───────────────────────────────────────────────────
class ViewProviderCalc:
def __init__(self, obj):
obj.Proxy = self
def getIcon(self):
icon = os.path.join(ICONPATH, "icons/calcv.svg")
return icon if os.path.exists(icon) else os.path.join(ICONPATH, "calcv.svg")
class CalcCmd:
def GetResources(self):
icon = os.path.join(ICONPATH, "icons/calcv.svg")
if not os.path.exists(icon):
icon = os.path.join(ICONPATH, "calc.svg")
return {
"Pixmap": icon,
"Accel": "",
"MenuText": "Calc Structure",
"ToolTip": "Run structural analysis using edsFEM",
}
def Activated(self):
selection = Gui.Selection.getSelection()
if not selection:
_show_error("Please select structural elements, loads, and supports.")
return
doc = FreeCAD.ActiveDocument
obj = doc.addObject("Part::FeaturePython", "CalcFEM")
Calc(obj, selection)
ViewProviderCalc(obj.ViewObject)
FreeCAD.ActiveDocument.recompute()
def IsActive(self):
return FreeCAD.ActiveDocument is not None
Gui.addCommand("Calc_1", CalcCmd())