-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathtemp_fe.py
More file actions
5087 lines (4488 loc) · 198 KB
/
Copy pathtemp_fe.py
File metadata and controls
5087 lines (4488 loc) · 198 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 FE shell models.
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. CalculiX FRD and SESAM SIF
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]
STRESS_REDUCTION_METHODS: tuple[str, ...] = (
"CSR area weighted mean",
"Whole panel nodal mean",
"Centre strip mean",
)
_STRESS_REDUCTION_METHOD_ALIASES = {
"csr": "CSR area weighted mean",
"csr area mean": "CSR area weighted mean",
"csr area average": "CSR area weighted mean",
"csr area weighted": "CSR area weighted mean",
"csr area weighted mean": "CSR area weighted mean",
"area": "CSR area weighted mean",
"area weighted": "CSR area weighted mean",
"area weighted mean": "CSR area weighted mean",
"nodal": "Whole panel nodal mean",
"nodal mean": "Whole panel nodal mean",
"whole panel nodal mean": "Whole panel nodal mean",
"whole panel mean": "Whole panel nodal mean",
"centre strip": "Centre strip mean",
"centre strip mean": "Centre strip mean",
"center strip": "Centre strip mean",
"center strip mean": "Centre strip mean",
"line": "Centre strip mean",
"line mean": "Centre strip mean",
}
@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", "Q8")) and len(self.node_ids) >= 4:
if len(self.node_ids) >= 8:
return (self.node_ids[0], self.node_ids[2], self.node_ids[4], self.node_ids[6])
return self.node_ids[:4]
if element_type.startswith("T6") and len(self.node_ids) >= 3:
if len(self.node_ids) >= 6:
return (self.node_ids[0], self.node_ids[2], self.node_ids[4])
return self.node_ids[:3]
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 FeBeamElement:
"""One beam element carried alongside shell geometry for panel inference."""
element_id: int
node_ids: tuple[int, ...]
element_type: str = ""
property_id: int | None = None
material_id: int | None = None
cross_section: dict[str, Any] = field(default_factory=dict)
@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]
beam_elements: dict[int, FeBeamElement] = field(default_factory=dict)
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 available_stress_reduction_methods() -> tuple[str, ...]:
"""Return the supported FE-to-buckling-panel stress reduction methods."""
return STRESS_REDUCTION_METHODS
def normalize_stress_reduction_method(method: str | None) -> str:
"""Normalize a public stress-reduction method label or shorthand."""
if method is None:
return STRESS_REDUCTION_METHODS[0]
text = str(method).strip()
if text in STRESS_REDUCTION_METHODS:
return text
normalized = _STRESS_REDUCTION_METHOD_ALIASES.get(text.lower())
if normalized is None:
raise ValueError(
"stress_reduction_method must be one of: "
+ ", ".join(STRESS_REDUCTION_METHODS)
)
return normalized
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 _path_suffix(path: str | os.PathLike[str] | None) -> str:
return "" if path is None else Path(str(path)).suffix.lower()
def _is_sesam_model_path(path: str | os.PathLike[str] | None) -> bool:
return _path_suffix(path) in {".fem", ".sif"}
def _is_sesam_result_path(path: str | os.PathLike[str] | None) -> bool:
return _path_suffix(path) == ".sif"
def _paired_sesam_sif_path(path: str | os.PathLike[str]) -> str | None:
source = Path(str(path))
if source.suffix.lower() != ".fem":
return None
for suffix in (".SIF", ".sif"):
candidate = source.with_suffix(suffix)
if candidate.exists():
return str(candidate)
return None
def _default_fea_result_path(
inp_path: str | os.PathLike[str],
frd_path: str | os.PathLike[str] | None,
) -> str | None:
if frd_path is not None:
return str(frd_path)
if _is_sesam_result_path(inp_path):
return str(inp_path)
if _path_suffix(inp_path) == ".fem":
return _paired_sesam_sif_path(inp_path)
return None
def read_sesam_shell_model(path: str | os.PathLike[str]) -> FeShellModel:
"""Read SESAM FEM/SIF shell geometry into the FE-results interpreter model."""
from anystruct.fe_solver_backend.sesam_fem.importer import import_sesam_fem, _beam_section
from anystruct.fe_solver_backend.sesam_fem.schema import get_element_spec
path_text = str(path)
result = import_sesam_fem(path_text, strict=False, build_model=False)
document = result.document
shell_elements: dict[int, ShellElement] = {}
elsets: dict[str, list[int]] = defaultdict(list)
section_by_elset: dict[str, ShellSection] = {}
beam_elements: dict[int, FeBeamElement] = {}
for element in document.elements.values():
spec = get_element_spec(element.type_code)
if spec is None:
continue
material_id = element.material_id if element.material_id is not None else 0
section_id = element.section_id if element.section_id is not None else 0
if spec.is_shell:
elset = f"sesam_shell_{spec.name.lower()}_prop_{section_id}_mat_{material_id}"
shell_elements[element.element_id] = ShellElement(
element_id=element.element_id,
node_ids=element.node_ids,
element_type=spec.name,
elset=elset,
)
elsets[elset].append(element.element_id)
if elset not in section_by_elset:
thickness = None
if element.section_id is not None:
section = document.sections.get(element.section_id)
if section is not None and section.thickness is not None and section.thickness > 0.0:
thickness = float(section.thickness)
if thickness is None and document.sections:
for s in document.sections.values():
if s.thickness is not None and s.thickness > 0.0:
thickness = float(s.thickness)
break
if thickness is None:
thickness = 0.01
section_by_elset[elset] = ShellSection(
elset=elset,
material=f"sesam_material_{material_id}" if material_id else None,
thickness_m=thickness,
)
elif spec.is_beam:
cross_section = _beam_section(document.sections.get(section_id))
beam_elements[element.element_id] = FeBeamElement(
element_id=element.element_id,
node_ids=element.node_ids,
element_type=spec.name,
property_id=section_id,
material_id=material_id,
cross_section=cross_section,
)
return FeShellModel(
nodes={node_id: tuple(node.coordinates) for node_id, node in document.nodes.items()},
shell_elements=shell_elements,
beam_elements=beam_elements,
elsets={name: tuple(values) for name, values in elsets.items()},
shell_sections=tuple(section_by_elset.values()),
source_path=path_text,
)
def read_sesam_sif_stress_result(path: str | os.PathLike[str]) -> FrdStressResult:
"""Read SESAM SIF RVSTRESS as the FRD-like stress object used here."""
from anystruct.fe_solver_backend.sesam_fem.sif_importer import read_sesam_sif_stress
stress = read_sesam_sif_stress(path)
return FrdStressResult(
path=stress.path,
nodes=dict(stress.nodes),
element_nodes=dict(stress.element_nodes),
components=tuple(stress.components),
nodal_stress=dict(stress.nodal_stress),
units=stress.units,
)
def read_fea_shell_model(path: str | os.PathLike[str]) -> FeShellModel:
"""Read a supported FE shell model: CalculiX INP or SESAM FEM/SIF."""
if _is_sesam_model_path(path):
return read_sesam_shell_model(path)
return read_calculix_inp(path)
def read_fea_result_summary(path: str | os.PathLike[str]) -> dict[str, Any]:
"""Return lightweight result metadata for FRD or SIF files."""
if _is_sesam_result_path(path):
from anystruct.fe_solver_backend.sesam_fem.sif_importer import read_sesam_sif_summary
return read_sesam_sif_summary(path)
return read_calculix_frd_summary(path)
def read_fea_stress(path: str | os.PathLike[str]) -> FrdStressResult:
"""Read supported FE stress results: CalculiX FRD or SESAM SIF."""
if _is_sesam_result_path(path):
return read_sesam_sif_stress_result(path)
return read_calculix_frd_stress(path)
def reduce_field_stresses(
model: FeShellModel,
fields: Sequence[PlateField],
frd_stress: FrdStressResult,
*,
transverse_edge_fraction: float = 0.2,
stress_reduction_method: str | None = None,
centre_strip_fraction: float = 0.25,
) -> list[PanelStress]:
"""Reduce FRD shell stresses to one ANYstructure/PULS stress set per field.
The default method follows the CSR/PULS-style recommendation to use area
weighted average membrane stresses over the finite elements of the panel.
Alternative methods are offered for sensitivity checks. CalculiX stresses
are interpreted as tension-positive Pa; returned normal stresses are
compression-positive MPa.
"""
reduction_method = normalize_stress_reduction_method(stress_reduction_method)
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:
if reduction_method == "CSR area weighted mean":
samples = _field_element_stress_samples(
model,
field_item,
frd_stress,
member_direction,
transverse_direction,
)
else:
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
panel_stresses.append(
_reduced_panel_stress_from_samples(
field_item,
samples,
reduction_method,
transverse_edge_fraction=transverse_edge_fraction,
centre_strip_fraction=centre_strip_fraction,
)
)
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,
ml_algo: Any = None,
) -> 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,
ml_algo=ml_algo,
)
buckling_result = panel.get_buckling_results(calculation_method=calculation_method, ml_algo=ml_algo)
result_record = {
"field_id": field_item.field_id,
"domain": domain,
"calculation_method": calculation_method,
"buckling_acceptance": buckling_acceptance,
"stress": summarize_panel_stresses([stress])[0],
"result": buckling_result,
}
selected_uf = _selected_uf_from_buckling_result(result_record)
api_available = (
bool(buckling_result.get("available", True))
if isinstance(buckling_result, dict)
else buckling_result is not None
)
# A finite UF is a valid result even when an older/newer API wrapper
# reports ``available`` differently.
result_record["available"] = selected_uf is not None or api_available
result_record["usage_factor"] = selected_uf
if selected_uf is None and isinstance(buckling_result, dict):
result_record["error"] = str(
buckling_result.get("error")
or buckling_result.get("message")
or "buckling calculation returned no identifiable usage factor"
)
results.append(result_record)
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,
ml_algo: Any = None,
run_buckling: bool = True,
stress_reduction_method: str | None = None,
) -> FeaBucklingSession:
"""Create a selectable FE-result buckling session for API and GUI callers."""
inp_path = str(inp_path)
frd_path_text = _default_fea_result_path(inp_path, frd_path)
model = read_fea_shell_model(inp_path)
fields = tuple(infer_plate_fields(model))
frd_summary = read_fea_result_summary(frd_path_text) if frd_path_text else None
diagnostics: list[str] = []
reduction_method = normalize_stress_reduction_method(stress_reduction_method)
diagnostics.append(f"stress reduction method: {reduction_method}")
if frd_path_text:
frd_stress = read_fea_stress(frd_path_text)
panel_stresses = tuple(
reduce_field_stresses(
model,
fields,
frd_stress,
stress_reduction_method=reduction_method,
)
)
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,
ml_algo=ml_algo,
)
)
unavailable_results = [
result for result in buckling_results
if not result.get("available", False)
]
if unavailable_results:
diagnostics.append(
f"{len(unavailable_results)} of {len(buckling_results)} flat-panel buckling calculations "
"returned no identifiable usage factor"
)
diagnostics.extend(
f"{result.get('field_id', '?')}: {result.get('error', 'no result')}"
for result in unavailable_results[:20]
)
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."""