-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathfe_plate_fields_gui_ready.py
More file actions
3508 lines (3069 loc) · 134 KB
/
Copy pathfe_plate_fields_gui_ready.py
File metadata and controls
3508 lines (3069 loc) · 134 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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Infer flat and cylindrical stiffened fields from CalculiX/PrePoMax shells.
Flat structures are interpreted from connected coplanar patches. Cylindrical
structures use a separate best-fit axis/radius pipeline, preserve periodic
circumferential topology, and infer longitudinal stiffeners plus ring
stiffeners/frames from local shell orientation. FRD stresses can be projected
to either flat panel axes or local axial/circumferential cylinder axes.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import re
from collections import defaultdict
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Iterable, Sequence
Point3D = tuple[float, float, float]
Vector3D = tuple[float, float, float]
@dataclass(frozen=True)
class ShellElement:
"""One shell element from a CalculiX input deck."""
element_id: int
node_ids: tuple[int, ...]
element_type: str = ""
elset: str | None = None
@property
def corner_node_ids(self) -> tuple[int, ...]:
element_type = self.element_type.upper()
if element_type.startswith("S8") and len(self.node_ids) >= 4:
return self.node_ids[:4]
if element_type.startswith("S6") and len(self.node_ids) >= 3:
return self.node_ids[:3]
return self.node_ids[:4]
@dataclass(frozen=True)
class ShellSection:
"""Shell-section metadata from ``*Shell section`` cards."""
elset: str | None
material: str | None
thickness_m: float | None
offset: str | None = None
@dataclass(frozen=True)
class FeShellModel:
"""Parsed shell model used by the plate-field interpreter."""
nodes: dict[int, Point3D]
shell_elements: dict[int, ShellElement]
elsets: dict[str, tuple[int, ...]] = field(default_factory=dict)
shell_sections: tuple[ShellSection, ...] = ()
source_path: str | None = None
@dataclass(frozen=True)
class FrdStressResult:
"""Expanded CalculiX FRD shell result data needed for stress reduction."""
path: str
nodes: dict[int, Point3D]
element_nodes: dict[int, tuple[int, ...]]
components: tuple[str, ...]
nodal_stress: dict[int, tuple[float, ...]]
units: str = "Pa"
@dataclass(frozen=True)
class SurfacePatch:
"""A connected coplanar shell-element component."""
patch_id: str
element_ids: tuple[int, ...]
normal: Vector3D
offset: float
bbox: tuple[tuple[float, float], tuple[float, float], tuple[float, float]]
area: float
centroid: Point3D
@dataclass(frozen=True)
class InferredMember:
"""A shell-plate web and optional flange interpreted as one member."""
member_id: str
role: str
section_type: str
web_patch_id: str
flange_patch_id: str | None
direction: Vector3D
station: float
web_height_m: float
flange_width_m: float | None
web_thickness_m: float | None = None
flange_thickness_m: float | None = None
thickness_source: str | None = None
confidence: float = 1.0
diagnostics: tuple[str, ...] = ()
@dataclass(frozen=True)
class PlateField:
"""One inferred plate bay between adjacent stiffener/girder web lines."""
field_id: str
base_patch_id: str
element_ids: tuple[int, ...]
bbox: tuple[tuple[float, float], tuple[float, float], tuple[float, float]]
span_m: float
spacing_m: float
transverse_bounds: tuple[float, float]
attached_member_ids: tuple[str, ...]
members: tuple[InferredMember, ...] = ()
shell_section_thickness_m: float | None = None
confidence: float = 1.0
diagnostics: tuple[str, ...] = ()
@dataclass(frozen=True)
class PanelStress:
"""PULS/ANYstructure stress input reduced from FE nodal stresses."""
field_id: str
sigma_x1_mpa: float
sigma_x2_mpa: float
sigma_y1_mpa: float
sigma_y2_mpa: float
tau_xy_mpa: float
sample_count: int
reduction: str
source_units: str = "Pa"
diagnostics: tuple[str, ...] = ()
@dataclass(frozen=True)
class FeaBucklingPanel:
"""One GUI/API selectable buckling panel discovered from FE results."""
field_id: str
field: PlateField
stress: PanelStress | None
anystructure_input: dict[str, Any]
plot_bounds: tuple[float, float, float, float]
buckling_result: dict[str, Any] | None = None
usage_factor: float | None = None
@dataclass(frozen=True)
class FeaBucklingSession:
"""Complete FE-result buckling import used by both API and GUI workflows."""
inp_path: str
frd_path: str | None
model: FeShellModel
fields: tuple[PlateField, ...]
panels: tuple[FeaBucklingPanel, ...]
frd_summary: dict[str, Any] | None = None
diagnostics: tuple[str, ...] = ()
@property
def field_count(self) -> int:
return len(self.fields)
@property
def panel_count(self) -> int:
return len(self.panels)
def panel(self, field_id: str) -> FeaBucklingPanel:
for panel in self.panels:
if panel.field_id == field_id:
return panel
raise KeyError(field_id)
def usage_factors(self) -> dict[str, float]:
return {
panel.field_id: panel.usage_factor
for panel in self.panels
if panel.usage_factor is not None
}
def summary(self) -> dict[str, Any]:
payload = _summary_payload(self.model, self.fields, self.frd_summary)
payload["inp_path"] = self.inp_path
payload["frd_path"] = self.frd_path
surface_records = {record["field_id"]: record for record in panel_3d_records(self.model, self.fields)}
payload["panels"] = [
{
"field_id": panel.field_id,
"plot_bounds": list(panel.plot_bounds),
"surface_3d": surface_records.get(panel.field_id),
"usage_factor": panel.usage_factor,
"anystructure_input": panel.anystructure_input,
"stress": None if panel.stress is None else summarize_panel_stresses([panel.stress])[0],
"buckling_result": panel.buckling_result,
}
for panel in self.panels
]
payload["diagnostics"] = list(self.diagnostics)
return payload
@dataclass(frozen=True)
class _PatchInference:
base_patch: SurfacePatch
members: tuple[InferredMember, ...]
stiffeners: tuple[InferredMember, ...]
girders: tuple[InferredMember, ...]
base_normal: Vector3D
member_direction: Vector3D
transverse_direction: Vector3D
def read_calculix_inp(path: str | os.PathLike[str]) -> FeShellModel:
"""Read shell nodes/elements, elsets, and shell-section metadata from ``.inp``."""
path = str(path)
nodes: dict[int, Point3D] = {}
shell_elements: dict[int, ShellElement] = {}
elsets: dict[str, list[int]] = {}
shell_sections: list[ShellSection] = []
mode: str | None = None
attrs: dict[str, str | bool] = {}
pending_shell_section: dict[str, str | None] | None = None
with open(path, "r", encoding="utf-8", errors="ignore") as inp_file:
for raw_line in inp_file:
line = raw_line.strip()
if not line or line.startswith("**"):
continue
if line.startswith("*"):
mode = None
attrs = _parse_keyword_attributes(line)
keyword = _keyword_name(line)
pending_shell_section = None
if keyword == "node":
mode = "node"
elif keyword == "element":
mode = "element"
elif keyword == "elset":
mode = "elset"
name = str(attrs.get("elset", "")).strip()
if name:
elsets.setdefault(name, [])
elif keyword == "shell section":
mode = "shell_section"
pending_shell_section = {
"elset": _optional_attr(attrs, "elset"),
"material": _optional_attr(attrs, "material"),
"offset": _optional_attr(attrs, "offset"),
}
continue
if mode == "node":
parts = _csv_parts(line)
if len(parts) >= 4:
nodes[int(parts[0])] = (float(parts[1]), float(parts[2]), float(parts[3]))
elif mode == "element":
parts = _csv_parts(line)
if len(parts) >= 4:
element_id = int(parts[0])
element_type = str(attrs.get("type", ""))
elset = _optional_attr(attrs, "elset")
shell_elements[element_id] = ShellElement(
element_id=element_id,
node_ids=tuple(int(item) for item in parts[1:]),
element_type=element_type,
elset=elset,
)
if elset:
elsets.setdefault(elset, []).append(element_id)
elif mode == "elset":
name = str(attrs.get("elset", "")).strip()
if not name:
continue
values = [int(float(part)) for part in _csv_parts(line)]
if "generate" in attrs and len(values) >= 2:
step = values[2] if len(values) >= 3 else 1
elsets.setdefault(name, []).extend(range(values[0], values[1] + 1, step))
else:
elsets.setdefault(name, []).extend(values)
elif mode == "shell_section" and pending_shell_section is not None:
parts = _csv_parts(line)
thickness = _safe_float(parts[0]) if parts else None
shell_sections.append(
ShellSection(
elset=pending_shell_section.get("elset"),
material=pending_shell_section.get("material"),
offset=pending_shell_section.get("offset"),
thickness_m=thickness,
)
)
pending_shell_section = None
mode = None
return FeShellModel(
nodes=nodes,
shell_elements=shell_elements,
elsets={name: tuple(values) for name, values in elsets.items()},
shell_sections=tuple(shell_sections),
source_path=path,
)
def read_calculix_frd_summary(path: str | os.PathLike[str]) -> dict[str, Any]:
"""Return lightweight metadata and result-block discovery for a CalculiX ``.frd`` file."""
path = str(path)
result_blocks: list[dict[str, Any]] = []
current_block: dict[str, Any] | None = None
current_step: int | None = None
node_count: int | None = None
material_names: list[str] = []
with open(path, "r", encoding="utf-8", errors="ignore") as frd_file:
for line_number, raw_line in enumerate(frd_file, start=1):
line = raw_line.rstrip("\n")
stripped = line.strip()
if stripped.startswith("1PSTEP"):
numbers = [int(value) for value in re.findall(r"[-+]?\d+", stripped)]
current_step = numbers[0] if numbers else None
elif stripped.startswith("2C") and node_count is None:
numbers = [int(value) for value in re.findall(r"[-+]?\d+", stripped[2:])]
if numbers:
node_count = numbers[0]
elif stripped.startswith("1UMAT"):
name = stripped[5:].strip()
if name:
material_names.append(name)
elif stripped.startswith("-4"):
parts = stripped.split()
if len(parts) >= 2:
current_block = {
"name": parts[1],
"step": current_step,
"line_number": line_number,
"components": [],
}
result_blocks.append(current_block)
elif stripped.startswith("-5") and current_block is not None:
parts = stripped.split()
if len(parts) >= 2:
current_block["components"].append(parts[1])
return {
"path": path,
"file_size": os.path.getsize(path),
"node_count": node_count,
"materials": material_names,
"result_blocks": result_blocks,
}
def read_calculix_frd_stress(path: str | os.PathLike[str]) -> FrdStressResult:
"""Read expanded FRD nodes/connectivity and the first ``STRESS`` result block."""
path = str(path)
nodes: dict[int, Point3D] = {}
element_nodes: dict[int, tuple[int, ...]] = {}
components: list[str] = []
nodal_stress: dict[int, tuple[float, ...]] = {}
mode: str | None = None
current_element_id: int | None = None
current_element_nodes: list[int] = []
def finish_element() -> None:
nonlocal current_element_id, current_element_nodes
if current_element_id is not None:
element_nodes[current_element_id] = tuple(current_element_nodes)
current_element_id = None
current_element_nodes = []
with open(path, "r", encoding="utf-8", errors="ignore") as frd_file:
for raw_line in frd_file:
stripped = raw_line.strip()
if not stripped:
continue
if stripped.startswith("2C"):
finish_element()
mode = "nodes"
continue
if stripped.startswith("3C"):
finish_element()
mode = "elements"
continue
if stripped.startswith("-4"):
finish_element()
parts = stripped.split()
mode = "stress_header" if len(parts) >= 2 and parts[1].upper() == "STRESS" else None
if mode == "stress_header":
components = []
continue
if stripped.startswith("-3"):
finish_element()
mode = None
continue
if mode == "nodes" and stripped.startswith("-1"):
values = _frd_numbers_after_marker(raw_line)
if len(values) >= 4:
nodes[int(values[0])] = (float(values[1]), float(values[2]), float(values[3]))
elif mode == "elements" and stripped.startswith("-1"):
finish_element()
values = _frd_numbers_after_marker(raw_line)
if values:
current_element_id = int(values[0])
elif mode == "elements" and stripped.startswith("-2"):
values = _frd_numbers_after_marker(raw_line)
current_element_nodes.extend(int(value) for value in values)
elif mode == "stress_header" and stripped.startswith("-5"):
parts = stripped.split()
if len(parts) >= 2:
components.append(parts[1].upper())
elif mode in {"stress_header", "stress_data"} and stripped.startswith("-1"):
mode = "stress_data"
values = _frd_numbers_after_marker(raw_line)
if len(values) >= 1 + len(components):
node_id = int(values[0])
nodal_stress[node_id] = tuple(float(value) for value in values[1 : 1 + len(components)])
return FrdStressResult(
path=path,
nodes=nodes,
element_nodes=element_nodes,
components=tuple(components),
nodal_stress=nodal_stress,
)
def reduce_field_stresses(
model: FeShellModel,
fields: Sequence[PlateField],
frd_stress: FrdStressResult,
*,
transverse_edge_fraction: float = 0.2,
) -> list[PanelStress]:
"""Reduce FRD shell stresses to one ANYstructure/PULS stress set per field.
The reduction follows the PULS S3/U3 nominal-load shape: axial stress and
shear are uniform nominal values, while transverse stress may vary linearly
between the two transverse sides. CalculiX stresses are interpreted as
tension-positive Pa; returned normal stresses are compression-positive MPa.
"""
patches = detect_surface_patches(model)
if not patches:
return []
inference = _infer_members_from_patches(model, patches)
base_normal = inference.base_normal
base_offset = inference.base_patch.offset
member_direction = inference.member_direction
transverse_direction = inference.transverse_direction
panel_stresses: list[PanelStress] = []
for field_item in fields:
samples = _field_stress_samples(
field_item,
frd_stress,
base_normal,
base_offset,
member_direction,
transverse_direction,
)
if not samples:
panel_stresses.append(
PanelStress(
field_id=field_item.field_id,
sigma_x1_mpa=0.0,
sigma_x2_mpa=0.0,
sigma_y1_mpa=0.0,
sigma_y2_mpa=0.0,
tau_xy_mpa=0.0,
sample_count=0,
reduction="no FRD stress samples",
diagnostics=("no stress samples found for field element ids",),
)
)
continue
sigma_x = [-sample[1] / 1.0e6 for sample in samples]
sigma_y = [-sample[2] / 1.0e6 for sample in samples]
tau_xy = [sample[3] / 1.0e6 for sample in samples]
transverse_values = [sample[0] for sample in samples]
lower_transverse, upper_transverse = field_item.transverse_bounds
edge_width = max((upper_transverse - lower_transverse) * transverse_edge_fraction, 1.0e-9)
lower_indices = [
index for index, value in enumerate(transverse_values)
if value <= lower_transverse + edge_width
]
upper_indices = [
index for index, value in enumerate(transverse_values)
if value >= upper_transverse - edge_width
]
if not lower_indices or not upper_indices:
ordered = sorted(range(len(samples)), key=lambda index: transverse_values[index])
take = max(1, int(math.ceil(len(ordered) * transverse_edge_fraction)))
lower_indices = ordered[:take]
upper_indices = ordered[-take:]
sigma_x_nominal = _mean(sigma_x)
panel_stresses.append(
PanelStress(
field_id=field_item.field_id,
sigma_x1_mpa=sigma_x_nominal,
sigma_x2_mpa=sigma_x_nominal,
sigma_y1_mpa=_mean(sigma_y[index] for index in lower_indices),
sigma_y2_mpa=_mean(sigma_y[index] for index in upper_indices),
tau_xy_mpa=_mean(tau_xy),
sample_count=len(samples),
reduction="nominal membrane: mean axial/shear, transverse side-band means",
diagnostics=(
"FRD stress tensors projected to inferred panel axes",
"normal stresses converted from FE tension-positive Pa to compression-positive MPa",
"mid-surface shell result nodes preferred to avoid bending peak stress input",
),
)
)
return panel_stresses
def summarize_panel_stresses(panel_stresses: Sequence[PanelStress]) -> list[dict[str, Any]]:
"""Flatten reduced panel stresses for JSON/CSV-style inspection."""
return [
{
"field_id": stress.field_id,
"sigma_x1_mpa": stress.sigma_x1_mpa,
"sigma_x2_mpa": stress.sigma_x2_mpa,
"sigma_y1_mpa": stress.sigma_y1_mpa,
"sigma_y2_mpa": stress.sigma_y2_mpa,
"tau_xy_mpa": stress.tau_xy_mpa,
"sample_count": stress.sample_count,
"reduction": stress.reduction,
"source_units": stress.source_units,
"diagnostics": list(stress.diagnostics),
}
for stress in panel_stresses
]
def calculate_field_buckling(
fields: Sequence[PlateField],
panel_stresses: Sequence[PanelStress],
*,
calculation_method: str = "SemiAnalytical S3/U3",
buckling_acceptance: str = "ultimate",
pressure_mpa: float = 0.0,
material_yield_mpa: float = 355.0,
elastic_modulus_mpa: float = 210000.0,
material_factor: float = 1.15,
poisson: float = 0.3,
) -> list[dict[str, Any]]:
"""Run ANYstructure buckling checks for fields using reduced FE stresses."""
from anystruct.api import FlatStru
stresses_by_field = {stress.field_id: stress for stress in panel_stresses}
results: list[dict[str, Any]] = []
for field_item in fields:
stress = stresses_by_field.get(field_item.field_id)
if stress is None:
results.append(
{
"field_id": field_item.field_id,
"available": False,
"error": "missing reduced panel stress",
}
)
continue
domain = _flat_structure_domain_for_field(field_item)
try:
panel = FlatStru(domain)
panel.set_material(
mat_yield=material_yield_mpa,
emodule=elastic_modulus_mpa,
material_factor=material_factor,
poisson=poisson,
)
panel.set_plate_geometry(
spacing=field_item.spacing_m * 1000.0,
thickness=(field_item.shell_section_thickness_m or 0.0) * 1000.0,
span=field_item.span_m * 1000.0,
)
panel.set_stresses(
pressure=pressure_mpa,
sigma_x1=stress.sigma_x1_mpa,
sigma_x2=stress.sigma_x2_mpa,
sigma_y1=stress.sigma_y1_mpa,
sigma_y2=stress.sigma_y2_mpa,
tau_xy=stress.tau_xy_mpa,
)
stiffener = _first_member_by_role(field_item, "stiffener")
if stiffener is not None and domain != "Flat plate, unstiffened":
panel.set_stiffener(
hw=stiffener.web_height_m * 1000.0,
tw=(stiffener.web_thickness_m or 0.0) * 1000.0,
bf=(stiffener.flange_width_m or 0.0) * 1000.0,
tf=(stiffener.flange_thickness_m or 0.0) * 1000.0,
stf_type=stiffener.section_type,
spacing=field_item.spacing_m * 1000.0,
)
girder = _first_member_by_role(field_item, "girder")
if girder is not None and domain == "Flat plate, stiffened with girder":
panel.set_girder(
hw=girder.web_height_m * 1000.0,
tw=(girder.web_thickness_m or 0.0) * 1000.0,
bf=(girder.flange_width_m or 0.0) * 1000.0,
tf=(girder.flange_thickness_m or 0.0) * 1000.0,
stf_type=girder.section_type,
spacing=field_item.span_m * 1000.0,
)
panel.set_puls_parameters(sp_or_up="UP" if stiffener is None else "SP", puls_boundary="Int")
panel.set_buckling_parameters(
calculation_method=calculation_method,
buckling_acceptance=buckling_acceptance,
)
buckling_result = panel.get_buckling_results(calculation_method=calculation_method)
result_available = (
bool(buckling_result.get("available", True))
if isinstance(buckling_result, dict)
else True
)
results.append(
{
"field_id": field_item.field_id,
"domain": domain,
"available": result_available,
"calculation_method": calculation_method,
"buckling_acceptance": buckling_acceptance,
"stress": summarize_panel_stresses([stress])[0],
"result": buckling_result,
}
)
except Exception as err:
results.append(
{
"field_id": field_item.field_id,
"domain": domain,
"available": False,
"calculation_method": calculation_method,
"buckling_acceptance": buckling_acceptance,
"stress": summarize_panel_stresses([stress])[0],
"error": str(err),
}
)
return results
def _create_flat_fea_buckling_session(
inp_path: str | os.PathLike[str],
frd_path: str | os.PathLike[str] | None = None,
*,
calculation_method: str = "SemiAnalytical S3/U3",
buckling_acceptance: str = "ultimate",
pressure_mpa: float = 0.0,
material_yield_mpa: float = 355.0,
elastic_modulus_mpa: float = 210000.0,
material_factor: float = 1.15,
poisson: float = 0.3,
run_buckling: bool = True,
) -> FeaBucklingSession:
"""Create a selectable FE-result buckling session for API and GUI callers."""
inp_path = str(inp_path)
frd_path_text = None if frd_path is None else str(frd_path)
model = read_calculix_inp(inp_path)
fields = tuple(infer_plate_fields(model))
frd_summary = read_calculix_frd_summary(frd_path_text) if frd_path_text else None
diagnostics: list[str] = []
if frd_path_text:
frd_stress = read_calculix_frd_stress(frd_path_text)
panel_stresses = tuple(reduce_field_stresses(model, fields, frd_stress))
else:
panel_stresses = ()
diagnostics.append("no FRD result file supplied; panel stresses set to defaults")
buckling_results: tuple[dict[str, Any], ...] = ()
if run_buckling and panel_stresses:
buckling_results = tuple(
calculate_field_buckling(
fields,
panel_stresses,
calculation_method=calculation_method,
buckling_acceptance=buckling_acceptance,
pressure_mpa=pressure_mpa,
material_yield_mpa=material_yield_mpa,
elastic_modulus_mpa=elastic_modulus_mpa,
material_factor=material_factor,
poisson=poisson,
)
)
plot_records = panel_plot_records(model, fields)
plot_by_field = {record["field_id"]: record for record in plot_records}
stress_by_field = {stress.field_id: stress for stress in panel_stresses}
result_by_field = {str(result.get("field_id")): result for result in buckling_results if result.get("field_id")}
panels = tuple(
FeaBucklingPanel(
field_id=field_item.field_id,
field=field_item,
stress=stress_by_field.get(field_item.field_id),
anystructure_input=anystructure_input_for_field(
field_item,
stress_by_field.get(field_item.field_id),
pressure_mpa=pressure_mpa,
material_yield_mpa=material_yield_mpa,
elastic_modulus_mpa=elastic_modulus_mpa,
material_factor=material_factor,
poisson=poisson,
calculation_method=calculation_method,
buckling_acceptance=buckling_acceptance,
),
plot_bounds=tuple(plot_by_field.get(field_item.field_id, {}).get("bounds", (0.0, 0.0, 0.0, 0.0))),
buckling_result=result_by_field.get(field_item.field_id),
usage_factor=_selected_uf_from_buckling_result(result_by_field.get(field_item.field_id, {})),
)
for field_item in fields
)
return FeaBucklingSession(
inp_path=inp_path,
frd_path=frd_path_text,
model=model,
fields=fields,
panels=panels,
frd_summary=frd_summary,
diagnostics=tuple(diagnostics),
)
def anystructure_input_for_field(
field_item: PlateField,
stress: PanelStress | None = None,
*,
pressure_mpa: float = 0.0,
material_yield_mpa: float = 355.0,
elastic_modulus_mpa: float = 210000.0,
material_factor: float = 1.15,
poisson: float = 0.3,
calculation_method: str = "SemiAnalytical S3/U3",
buckling_acceptance: str = "ultimate",
) -> dict[str, Any]:
"""Return normal ANYstructure input values inferred for one FE panel."""
stiffener = _first_member_by_role(field_item, "stiffener")
girder = _first_member_by_role(field_item, "girder")
section_member = stiffener or girder
section_type = "FB" if section_member is None else section_member.section_type
panel_stress = stress or PanelStress(
field_id=field_item.field_id,
sigma_x1_mpa=0.0,
sigma_x2_mpa=0.0,
sigma_y1_mpa=0.0,
sigma_y2_mpa=0.0,
tau_xy_mpa=0.0,
sample_count=0,
reduction="default zero stress",
)
return {
"field_id": field_item.field_id,
"calculation_domain": _flat_structure_domain_for_field(field_item),
"geometry": {
"span_mm": field_item.span_m * 1000.0,
"spacing_mm": field_item.spacing_m * 1000.0,
"plate_thickness_mm": (field_item.shell_section_thickness_m or 0.0) * 1000.0,
},
"section": {
"type": section_type,
"web_height_mm": 0.0 if section_member is None else section_member.web_height_m * 1000.0,
"web_thickness_mm": 0.0 if section_member is None else (section_member.web_thickness_m or 0.0) * 1000.0,
"flange_width_mm": 0.0 if section_member is None else (section_member.flange_width_m or 0.0) * 1000.0,
"flange_thickness_mm": 0.0 if section_member is None else (section_member.flange_thickness_m or 0.0) * 1000.0,
"source_member_id": None if section_member is None else section_member.member_id,
},
"girder": None if girder is None else {
"type": girder.section_type,
"web_height_mm": girder.web_height_m * 1000.0,
"web_thickness_mm": (girder.web_thickness_m or 0.0) * 1000.0,
"flange_width_mm": (girder.flange_width_m or 0.0) * 1000.0,
"flange_thickness_mm": (girder.flange_thickness_m or 0.0) * 1000.0,
"source_member_id": girder.member_id,
},
"material": {
"yield_mpa": material_yield_mpa,
"elastic_modulus_mpa": elastic_modulus_mpa,
"material_factor": material_factor,
"poisson": poisson,
},
"stresses": {
"pressure_mpa": pressure_mpa,
"sigma_x1_mpa": panel_stress.sigma_x1_mpa,
"sigma_x2_mpa": panel_stress.sigma_x2_mpa,
"sigma_y1_mpa": panel_stress.sigma_y1_mpa,
"sigma_y2_mpa": panel_stress.sigma_y2_mpa,
"tau_xy_mpa": panel_stress.tau_xy_mpa,
"sample_count": panel_stress.sample_count,
"reduction": panel_stress.reduction,
},
"buckling": {
"calculation_method": calculation_method,
"buckling_acceptance": buckling_acceptance,
"puls_boundary": "Int",
"puls_sp_or_up": "UP" if stiffener is None else "SP",
"puls_up_boundary": "SSSS",
"stiffener_end_support": "Continuous",
},
}
def panel_plot_records(
model: FeShellModel,
fields: Sequence[PlateField],
field_values: dict[str, float] | None = None,
) -> list[dict[str, Any]]:
"""Return 2D plot rectangles for clickable GUI rendering of FE panels."""
patches = detect_surface_patches(model)
inference = _infer_members_from_patches(model, patches) if patches else None
member_direction = inference.member_direction if inference is not None else (1.0, 0.0, 0.0)
transverse_direction = inference.transverse_direction if inference is not None else (0.0, 1.0, 0.0)
records: list[dict[str, Any]] = []
for index, field_item in enumerate(fields):
bounds = _field_plot_bounds(field_item, member_direction, transverse_direction)
value = None if field_values is None else field_values.get(field_item.field_id)
records.append(
{
"field_id": field_item.field_id,
"index": index,
"bounds": bounds,
"value": value,
"span_m": field_item.span_m,
"spacing_m": field_item.spacing_m,
}
)
return records
def panel_3d_records(
model: FeShellModel,
fields: Sequence[PlateField],
field_values: dict[str, float] | None = None,
) -> list[dict[str, Any]]:
"""Return 3D buckling-panel polygons.
Unlike ``panel_plot_records`` this does not flatten panels into one plane.
Each field is represented by one coarse panel surface, so panels at
different elevations, perpendicular panels, and skewed panels remain
separated in model coordinates without exposing the FE mesh.
"""
if fields and isinstance(fields[0], CylinderField):
geometry = detect_cylinder_geometry(model)
return cylinder_3d_records(
model,
geometry,
fields, # type: ignore[arg-type]
field_values=field_values,
)
records: list[dict[str, Any]] = []
for index, field_item in enumerate(fields):
polygons = [_field_representative_panel_polygon(model, field_item)]
if not polygons:
polygons = [_field_bbox_representative_polygon(field_item)]
points = [point for polygon in polygons for point in polygon]
bbox = _bbox(points) if points else field_item.bbox
value = None if field_values is None else field_values.get(field_item.field_id)
records.append(
{
"field_id": field_item.field_id,
"index": index,
"polygons": polygons,
"bbox": bbox,
"centroid": _mean_point(points) if points else (
(bbox[0][0] + bbox[0][1]) / 2.0,
(bbox[1][0] + bbox[1][1]) / 2.0,
(bbox[2][0] + bbox[2][1]) / 2.0,
),
"normal": _field_representative_normal(model, field_item),
"value": value,
"span_m": field_item.span_m,
"spacing_m": field_item.spacing_m,
}
)
return records
def _field_representative_panel_polygon(model: FeShellModel, field_item: PlateField) -> list[Point3D]:
"""Return one oriented rectangle covering the FE elements in a panel field."""
element_polygons = _field_element_polygons(model, field_item)
points = [point for polygon in element_polygons for point in polygon]
if len(points) < 3:
return _field_bbox_representative_polygon(field_item)
normal = _field_representative_normal(model, field_item)
centroid = _mean_point(points)
bbox = _bbox(points)
axis_vectors = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))
projected_axes: list[tuple[float, Vector3D]] = []
for axis_index, axis_vector in enumerate(axis_vectors):
projected = _project_to_plane(axis_vector, normal)
projected_axes.append((bbox[axis_index][1] - bbox[axis_index][0], projected))
projected_axes = [
(extent, axis)
for extent, axis in sorted(projected_axes, key=lambda item: item[0], reverse=True)
if _length(axis) > 1.0e-12
]
if projected_axes:
u_axis = projected_axes[0][1]
else:
u_axis = _normalise(_subtract(points[1], points[0]))
v_axis = _normalise(_cross(normal, u_axis))
if _length(v_axis) <= 1.0e-12:
return _field_bbox_representative_polygon(field_item)
u_values = [_dot(_subtract(point, centroid), u_axis) for point in points]
v_values = [_dot(_subtract(point, centroid), v_axis) for point in points]
u_min, u_max = min(u_values), max(u_values)
v_min, v_max = min(v_values), max(v_values)
def corner(u_value: float, v_value: float) -> Point3D:
return (
centroid[0] + u_axis[0] * u_value + v_axis[0] * v_value,
centroid[1] + u_axis[1] * u_value + v_axis[1] * v_value,
centroid[2] + u_axis[2] * u_value + v_axis[2] * v_value,
)
return [
corner(u_min, v_min),
corner(u_max, v_min),
corner(u_max, v_max),
corner(u_min, v_max),
]
def plot_plate_fields_3d(
model: FeShellModel,
fields: Sequence[PlateField] | None = None,
*,
output_path: str | os.PathLike[str] | None = None,
field_values: dict[str, float] | None = None,
value_label: str = "UF",
cmap_name: str = "tab20",
annotate: bool = True,
dpi: int = 180,
) -> Any:
"""Plot discovered buckling panels as 3D shell-panel surfaces only."""
from matplotlib import colors as matplotlib_colors
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
fields = list(infer_plate_fields(model) if fields is None else fields)
records = panel_3d_records(model, fields, field_values=field_values)
fig = plt.figure(figsize=(9.0, 5.5), dpi=dpi)
ax = fig.add_subplot(111, projection="3d")
scalar_values = _finite_field_values(field_values)
if scalar_values:
scalar_cmap_name = "RdYlGn_r" if cmap_name == "tab20" else cmap_name
cmap = plt.get_cmap(scalar_cmap_name)
value_min = min(min(scalar_values.values()), 0.0)
value_max = max(max(scalar_values.values()), 1.0)
if math.isclose(value_min, value_max):
value_max = value_min + 1.0
norm = matplotlib_colors.Normalize(vmin=value_min, vmax=value_max)
else:
cmap = plt.get_cmap(cmap_name, max(len(records), 1))
norm = None
all_points: list[Point3D] = []
for record in records:
value = record.get("value")
if norm is not None:
color = cmap(norm(value)) if value is not None and math.isfinite(float(value)) else "0.82"
else:
color = cmap(record["index"] % max(len(records), 1))
collection = Poly3DCollection(
record["polygons"],
facecolor=color,
edgecolor="black",
linewidth=0.35,
alpha=0.78,