-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathbeso_lib.py
1910 lines (1759 loc) · 84.7 KB
/
beso_lib.py
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
import numpy as np
import operator
from math import *
# function to print ongoing messages to the log file
def write_to_log(file_name, msg):
f_log = open(file_name[:-4] + ".log", "a")
f_log.write(msg)
f_log.close()
# function importing a mesh consisting of nodes, volume and shell elements
def import_inp(file_name, domains_from_config, domain_optimized, shells_as_composite):
nodes = {} # dict with nodes position
class Elements():
tria3 = {}
tria6 = {}
quad4 = {}
quad8 = {}
tetra4 = {}
tetra10 = {}
hexa8 = {}
hexa20 = {}
penta6 = {}
penta15 = {}
all_tria3 = {}
all_tria6 = {}
all_quad4 = {}
all_quad8 = {}
all_tetra4 = {}
all_tetra10 = {}
all_hexa8 = {}
all_hexa20 = {}
all_penta6 = {}
all_penta15 = {}
model_definition = True
domains = {}
read_domain = False
read_node = False
elm_category = []
elm_2nd_line = False
elset_generate = False
special_type = "" # for plane strain, plane stress, or axisymmetry
plane_strain = set()
plane_stress = set()
axisymmetry = set()
try:
f = open(file_name, "r")
except IOError:
msg = ("CalculiX input file " + file_name + " not found. Check your inputs.")
write_to_log(file_name, "\nERROR: " + msg + "\n")
raise Exception(msg)
line = "\n"
include = ""
while line != "":
if include:
line = f_include.readline()
if line == "":
f_include.close()
include = ""
line = f.readline()
else:
line = f.readline()
if line.strip() == '':
continue
elif line[0] == '*': # start/end of a reading set
if line[0:2] == '**': # comments
continue
if line[:8].upper() == "*INCLUDE":
start = 1 + line.index("=")
include = line[start:].strip().strip('"')
f_include = open(include, "r")
continue
read_node = False
elm_category = []
elm_2nd_line = False
read_domain = False
elset_generate = False
# reading nodes
if (line[:5].upper() == "*NODE") and (model_definition is True):
read_node = True
elif read_node is True:
line_list = line.split(',')
number = int(line_list[0])
x = float(line_list[1])
y = float(line_list[2])
z = float(line_list[3])
nodes[number] = [x, y, z]
# reading elements
elif line[:8].upper() == "*ELEMENT":
current_elset = ""
line_list = line[8:].split(',')
for line_part in line_list:
if line_part.split('=')[0].strip().upper() == "TYPE":
elm_type = line_part.split('=')[1].strip().upper()
elif line_part.split('=')[0].strip().upper() == "ELSET":
current_elset = line_part.split('=')[1].strip()
if elm_type in ["S3", "CPS3", "CPE3", "CAX3", "M3D3"]:
elm_category = all_tria3
number_of_nodes = 3
elif elm_type in ["S6", "CPS6", "CPE6", "CAX6", "M3D6"]:
elm_category = all_tria6
number_of_nodes = 6
elif elm_type in ["S4", "S4R", "CPS4", "CPS4R", "CPE4", "CPE4R", "CAX4", "CAX4R", "M3D4", "M3D4R"]:
elm_category = all_quad4
number_of_nodes = 4
elif elm_type in ["S8", "S8R", "CPS8", "CPS8R", "CPE8", "CPE8R", "CAX8", "CAX8R", "M3D8", "M3D8R"]:
elm_category = all_quad8
number_of_nodes = 8
elif elm_type == "C3D4":
elm_category = all_tetra4
number_of_nodes = 4
elif elm_type == "C3D10":
elm_category = all_tetra10
number_of_nodes = 10
elif elm_type in ["C3D8", "C3D8R", "C3D8I"]:
elm_category = all_hexa8
number_of_nodes = 8
elif elm_type in ["C3D20", "C3D20R", "C3D20RI"]:
elm_category = all_hexa20
number_of_nodes = 20
elif elm_type == "C3D6":
elm_category = all_penta6
number_of_nodes = 6
elif elm_type == "C3D15":
elm_category = all_penta15
number_of_nodes = 15
if elm_type in ["CPE3", "CPE6", "CPE4", "CPE4R", "CPE8", "CPE8R"]:
special_type = "plane strain"
elif elm_type in ["CPS3", "CPS6", "CPS4", "CPS4R", "CPS8", "CPS8R"]:
special_type = "plane stress"
elif elm_type in ["CAX3", "CAX6", "CAX4", "CAX4R", "CAX8", "CAX8R"]:
special_type = "axisymmetry"
else:
special_type = ""
if (shells_as_composite is True) and (elm_type in ["S3", "S4", "S4R", "S8"]):
msg = ("\nERROR: " + elm_type + "element type found. CalculiX might need S6 or S8R elements for "
"composite\n")
print(msg)
write_to_log(file_name, msg)
elif elm_category != []:
line_list = line.split(',')
if elm_2nd_line is False:
en = int(line_list[0]) # element number
elm_category[en] = []
pos = 1
if current_elset: # save en to the domain
try:
domains[current_elset].add(en)
except KeyError:
domains[current_elset] = {en}
if special_type == "plane strain":
plane_strain.add(en)
elif special_type == "plane stress":
plane_stress.add(en)
elif special_type == "axisymmetry":
axisymmetry.add(en)
else:
pos = 0
elm_2nd_line = False
for nn in range(pos, pos + number_of_nodes - len(elm_category[en])):
try:
enode = int(line_list[nn])
elm_category[en].append(enode)
except(IndexError, ValueError):
elm_2nd_line = True
break
# reading domains from elset
elif line[:6].upper() == "*ELSET":
line_split_comma = line.split(",")
if "=" in line_split_comma[1]:
name_member = 1
try:
if "GENERATE" in line_split_comma[2].upper():
elset_generate = True
except IndexError:
pass
else:
name_member = 2
if "GENERATE" in line_split_comma[1].upper():
elset_generate = True
member_split = line_split_comma[name_member].split("=")
current_elset = member_split[1].strip()
try:
domains[current_elset]
except KeyError:
domains[current_elset] = set()
if elset_generate is False:
read_domain = True
elif read_domain is True:
for en in line.split(","):
en = en.strip()
if en.isdigit():
domains[current_elset].add(int(en))
elif en.isalpha(): # else: en is name of a previous elset
domains[current_elset].update(domains[en])
elif elset_generate is True:
line_split_comma = line.split(",")
try:
if line_split_comma[3]:
en_generated = list(range(int(line_split_comma[0]), int(line_split_comma[1]) + 1,
int(line_split_comma[2])))
except IndexError:
en_generated = list(range(int(line_split_comma[0]), int(line_split_comma[1]) + 1))
domains[current_elset].update(en_generated)
elif line[:5].upper() == "*STEP":
model_definition = False
f.close()
for dn in domains:
domains[dn] = list(domains[dn])
en_all = []
opt_domains = []
all_available = False
for dn in domains_from_config:
if dn.upper() == "ALL_AVAILABLE":
all_available = True
continue
try:
en_all.extend(domains[dn])
except KeyError:
msg = "Element set '{}' not found in the inp file.".format(dn)
write_to_log(file_name, "\nERROR: " + msg + "\n")
raise Exception(msg)
if domain_optimized[dn] is True:
opt_domains.extend(domains[dn])
msg = ("domains: %.f\n" % len(domains_from_config))
if all_available: # domain called all_available will contain rest of the elements
en_all2 = set()
en_all2 = en_all2.union(all_tria3.keys(), all_tria6.keys(), all_quad4.keys(), all_quad8.keys(),
all_tetra4.keys(), all_tetra10.keys(), all_hexa8.keys(), all_hexa20.keys(),
all_penta6.keys(), all_penta15.keys())
Elements.tria3 = all_tria3
Elements.tria6 = all_tria6
Elements.quad4 = all_quad4
Elements.quad8 = all_quad8
Elements.tetra4 = all_tetra4
Elements.tetra10 = all_tetra10
Elements.hexa8 = all_hexa8
Elements.hexa20 = all_hexa20
Elements.penta6 = all_penta6
Elements.penta15 = all_penta15
domains["all_available"] = en_all2 - set(en_all)
opt_domains.extend(domains["all_available"])
en_all = list(en_all2)
else:
# only elements in domains_from_config are stored, the rest is discarded
keys = set(en_all).intersection(set(all_tria3.keys()))
Elements.tria3 = {k: all_tria3[k] for k in keys}
keys = set(en_all).intersection(set(all_tria6.keys()))
Elements.tria6 = {k: all_tria6[k] for k in keys}
keys = set(en_all).intersection(set(all_quad4.keys()))
Elements.quad4 = {k: all_quad4[k] for k in keys}
keys = set(en_all).intersection(set(all_quad8.keys()))
Elements.quad8 = {k: all_quad8[k] for k in keys}
keys = set(en_all).intersection(set(all_tetra4.keys()))
Elements.tetra4 = {k: all_tetra4[k] for k in keys}
keys = set(en_all).intersection(set(all_tetra10.keys()))
Elements.tetra10 = {k: all_tetra10[k] for k in keys}
keys = set(en_all).intersection(set(all_hexa8.keys()))
Elements.hexa8 = {k: all_hexa8[k] for k in keys}
keys = set(en_all).intersection(set(all_hexa20.keys()))
Elements.hexa20 = {k: all_hexa20[k] for k in keys}
keys = set(en_all).intersection(set(all_penta6.keys()))
Elements.penta6 = {k: all_penta6[k] for k in keys}
keys = set(en_all).intersection(set(all_penta15.keys()))
Elements.penta15 = {k: all_penta15[k] for k in keys}
en_all = list(Elements.tria3.keys()) + list(Elements.tria6.keys()) + list(Elements.quad4.keys()) + \
list(Elements.quad8.keys()) + list(Elements.tetra4.keys()) + list(Elements.tetra10.keys()) + \
list(Elements.hexa8.keys()) + list(Elements.hexa20.keys()) + list(Elements.penta6.keys()) + \
list(Elements.penta15.keys())
msg += ("nodes : %.f\nTRIA3 : %.f\nTRIA6 : %.f\nQUAD4 : %.f\nQUAD8 : %.f\nTETRA4 : %.f\nTETRA10: %.f\n"
"HEXA8 : %.f\nHEXA20 : %.f\nPENTA6 : %.f\nPENTA15: %.f\n"
% (len(nodes), len(Elements.tria3), len(Elements.tria6), len(Elements.quad4), len(Elements.quad8),
len(Elements.tetra4), len(Elements.tetra10), len(Elements.hexa8), len(Elements.hexa20),
len(Elements.penta6), len(Elements.penta15)))
print(msg)
write_to_log(file_name, msg)
if not opt_domains:
row = "None optimized domain has been found. Check your inputs."
msg = ("\nERROR: " + row + "\n")
write_to_log(file_name, msg)
assert False, row
return nodes, Elements, domains, opt_domains, en_all, plane_strain, plane_stress, axisymmetry
# function for computing volumes or area (shell elements) and centres of gravity
# approximate for 2nd order elements!
def elm_volume_cg(file_name, nodes, Elements):
u = [0.0, 0.0, 0.0]
v = [0.0, 0.0, 0.0]
w = [0.0, 0.0, 0.0]
def tria_area_cg(nod):
# compute volume
for i in [0, 1, 2]: # denote x, y, z directions
u[i] = nodes[nod[2]][i] - nodes[nod[1]][i]
v[i] = nodes[nod[0]][i] - nodes[nod[1]][i]
area_tria = np.linalg.linalg.norm(np.cross(u, v)) / 2.0
# compute centre of gravity
x_cg = (nodes[nod[0]][0] + nodes[nod[1]][0] + nodes[nod[2]][0]) / 3.0
y_cg = (nodes[nod[0]][1] + nodes[nod[1]][1] + nodes[nod[2]][1]) / 3.0
z_cg = (nodes[nod[0]][2] + nodes[nod[1]][2] + nodes[nod[2]][2]) / 3.0
cg_tria = [x_cg, y_cg, z_cg]
return area_tria, cg_tria
def tetra_volume_cg(nod):
# compute volume
for i in [0, 1, 2]: # denote x, y, z directions
u[i] = nodes[nod[2]][i] - nodes[nod[1]][i]
v[i] = nodes[nod[3]][i] - nodes[nod[1]][i]
w[i] = nodes[nod[0]][i] - nodes[nod[1]][i]
volume_tetra = abs(np.dot(np.cross(u, v), w)) / 6.0
# compute centre of gravity
x_cg = (nodes[nod[0]][0] + nodes[nod[1]][0] + nodes[nod[2]][0] + nodes[nod[3]][0]) / 4.0
y_cg = (nodes[nod[0]][1] + nodes[nod[1]][1] + nodes[nod[2]][1] + nodes[nod[3]][1]) / 4.0
z_cg = (nodes[nod[0]][2] + nodes[nod[1]][2] + nodes[nod[2]][2] + nodes[nod[3]][2]) / 4.0
cg_tetra = [x_cg, y_cg, z_cg]
return volume_tetra, cg_tetra
def second_order_info(elm_type):
msg = "\nINFO: areas and centres of gravity of " + elm_type.upper() + " elements ignore mid-nodes' positions\n"
print(msg)
write_to_log(file_name, msg)
# defining volume and centre of gravity for all element types
volume_elm = {}
area_elm = {}
cg = {}
for en, nod in Elements.tria3.items():
[area_elm[en], cg[en]] = tria_area_cg(nod)
if Elements.tria6:
second_order_info("tria6")
for en, nod in Elements.tria6.items(): # copy from tria3
[area_elm[en], cg[en]] = tria_area_cg(nod)
for en, nod in Elements.quad4.items():
[a1, cg1] = tria_area_cg(nod[0:3])
[a2, cg2] = tria_area_cg(nod[0:1] + nod[2:4])
area_elm[en] = float(a1 + a2)
cg[en] = [[], [], []]
for k in [0, 1, 2]: # denote x, y, z dimensions
cg[en][k] = (a1 * cg1[k] + a2 * cg2[k]) / area_elm[en]
if Elements.quad8:
second_order_info("quad8")
for en, nod in Elements.quad8.items(): # copy from quad4
[a1, cg1] = tria_area_cg(nod[0:3])
[a2, cg2] = tria_area_cg(nod[0:1] + nod[2:4])
area_elm[en] = float(a1 + a2)
cg[en] = [[], [], []]
for k in [0, 1, 2]: # denote x, y, z dimensions
cg[en][k] = (a1 * cg1[k] + a2 * cg2[k]) / area_elm[en]
for en, nod in Elements.tetra4.items():
[volume_elm[en], cg[en]] = tetra_volume_cg(nod)
if Elements.tetra10:
second_order_info("tetra10")
for en, nod in Elements.tetra10.items(): # copy from tetra4
[volume_elm[en], cg[en]] = tetra_volume_cg(nod)
for en, nod in Elements.hexa8.items():
[v1, cg1] = tetra_volume_cg(nod[0:3] + nod[5:6])
[v2, cg2] = tetra_volume_cg(nod[0:1] + nod[2:3] + nod[4:6])
[v3, cg3] = tetra_volume_cg(nod[2:3] + nod[4:7])
[v4, cg4] = tetra_volume_cg(nod[0:1] + nod[2:5])
[v5, cg5] = tetra_volume_cg(nod[3:5] + nod[6:8])
[v6, cg6] = tetra_volume_cg(nod[2:5] + nod[6:7])
volume_elm[en] = float(v1 + v2 + v3 + v4 + v5 + v6)
cg[en] = [[], [], []]
for k in [0, 1, 2]: # denote x, y, z dimensions
cg[en][k] = (v1 * cg1[k] + v2 * cg2[k] + v3 * cg3[k] + v4 * cg4[k] + v5 * cg5[k] + v6 * cg6[k]
) / volume_elm[en]
if Elements.hexa20:
second_order_info("hexa20")
for en, nod in Elements.hexa20.items(): # copy from hexa8
[v1, cg1] = tetra_volume_cg(nod[0:3] + nod[5:6])
[v2, cg2] = tetra_volume_cg(nod[0:1] + nod[2:3] + nod[4:6])
[v3, cg3] = tetra_volume_cg(nod[2:3] + nod[4:7])
[v4, cg4] = tetra_volume_cg(nod[0:1] + nod[2:5])
[v5, cg5] = tetra_volume_cg(nod[3:5] + nod[6:8])
[v6, cg6] = tetra_volume_cg(nod[2:5] + nod[6:7])
volume_elm[en] = float(v1 + v2 + v3 + v4 + v5 + v6)
cg[en] = [[], [], []]
for k in [0, 1, 2]: # denote x, y, z dimensions
cg[en][k] = (v1 * cg1[k] + v2 * cg2[k] + v3 * cg3[k] + v4 * cg4[k] + v5 * cg5[k] + v6 * cg6[k]
) / volume_elm[en]
for en, nod in Elements.penta6.items():
[v1, cg1] = tetra_volume_cg(nod[0:4])
[v2, cg2] = tetra_volume_cg(nod[1:5])
[v3, cg3] = tetra_volume_cg(nod[2:6])
volume_elm[en] = float(v1 + v2 + v3)
cg[en] = [[], [], []]
for k in [0, 1, 2]: # denote x, y, z dimensions
cg[en][k] = (v1 * cg1[k] + v2 * cg2[k] + v3 * cg3[k]) / volume_elm[en]
if Elements.penta15:
second_order_info("penta15") # copy from penta6
for en, nod in Elements.penta15.items():
[v1, cg1] = tetra_volume_cg(nod[0:4])
[v2, cg2] = tetra_volume_cg(nod[1:5])
[v3, cg3] = tetra_volume_cg(nod[2:6])
volume_elm[en] = float(v1 + v2 + v3)
cg[en] = [[], [], []]
for k in [0, 1, 2]: # denote x, y, z dimensions
cg[en][k] = (v1 * cg1[k] + v2 * cg2[k] + v3 * cg3[k]) / volume_elm[en]
# finding the minimum and maximum cg position
x_cg = []
y_cg = []
z_cg = []
for xyz in cg.values():
x_cg.append(xyz[0])
y_cg.append(xyz[1])
z_cg.append(xyz[2])
cg_min = [min(x_cg), min(y_cg), min(z_cg)]
cg_max = [max(x_cg), max(y_cg), max(z_cg)]
return cg, cg_min, cg_max, volume_elm, area_elm
# function for copying .inp file with additional elsets, materials, solid and shell sections, different output request
# elm_states is a dict of the elements containing 0 for void element or 1 for full element
def write_inp(file_name, file_nameW, elm_states, number_of_states, domains, domains_from_config, domain_optimized,
domain_thickness, domain_offset, domain_orientation, domain_material, domain_volumes, domain_shells,
plane_strain, plane_stress, axisymmetry, save_iteration_results, i, reference_points, shells_as_composite,
optimization_base, displacement_graph, domain_FI_filled):
if reference_points == "nodes":
fR = open(file_name[:-4] + "_separated.inp", "r")
else:
fR = open(file_name, "r")
check_line_endings = False
try:
fW = open(file_nameW + ".inp", "w", newline="\n")
except TypeError: # python 2.x do not have newline argument
fW = open(file_nameW + ".inp", "w")
check_line_endings = True
# function for writing ELSETs of each state
def write_elset():
fW.write(" \n")
fW.write("** Added ELSETs by optimization:\n")
for dn in domains_from_config:
if domain_optimized[dn] is True:
elsets_used[dn] = []
elset_new[dn] = {}
for sn in range(number_of_states):
elset_new[dn][sn] = []
for en in domains[dn]:
if elm_states[en] == sn:
elset_new[dn][elm_states[en]].append(en)
for sn, en_list in elset_new[dn].items():
if en_list:
elsets_used[dn].append(sn)
fW.write("*ELSET,ELSET=" + dn + str(sn) + "\n")
position = 0
for en in en_list:
if position < 8:
fW.write(str(en) + ", ")
position += 1
else:
fW.write(str(en) + ",\n")
position = 0
fW.write("\n")
fW.write(" \n")
# all available elsets together
if "all_available" in domains.keys():
fW.write(" \n")
fW.write("*ELSET,ELSET=all_available\n")
position = 0
for en in domains["all_available"]:
if position < 8:
fW.write(str(en) + ", ")
position += 1
else:
fW.write(str(en) + ",\n")
position = 0
fW.write("\n")
# function to add orientation to solid or shell section
def add_orientation():
try:
fW.write(", ORIENTATION=" + domain_orientation[dn][sn] + "\n")
except (KeyError, IndexError):
fW.write("\n")
elsets_done = 0
sections_done = 0
outputs_done = 1
commenting = False
elset_new = {}
elsets_used = {}
msg_error = ""
for line in fR:
if line[0] == "*":
commenting = False
# writing ELSETs
if (line[:6].upper() == "*ELSET" and elsets_done == 0) or (line[:5].upper() == "*STEP" and elsets_done == 0):
write_elset()
elsets_done = 1
# optimization materials, solid and shell sections
if line[:5].upper() == "*STEP" and sections_done == 0:
if elsets_done == 0:
write_elset()
elsets_done = 1
fW.write(" \n")
fW.write("** Materials and sections in optimized domains\n")
fW.write("** (redefines elements properties defined above):\n")
for dn in domains_from_config:
if domain_optimized[dn]:
for sn in elsets_used[dn]:
fW.write("*MATERIAL, NAME=" + dn + str(sn) + "\n")
fW.write(domain_material[dn][sn] + "\n")
if domain_volumes[dn]:
fW.write("*SOLID SECTION, ELSET=" + dn + str(sn) + ", MATERIAL=" + dn + str(sn))
add_orientation()
elif len(plane_strain.intersection(domain_shells[dn])) == len(domain_shells[dn]):
fW.write("*SOLID SECTION, ELSET=" + dn + str(sn) + ", MATERIAL=" + dn + str(sn))
add_orientation()
fW.write(str(domain_thickness[dn][sn]) + "\n")
elif plane_strain.intersection(domain_shells[dn]):
msg_error = dn + " domain does not contain only plane strain types for 2D elements"
elif len(plane_stress.intersection(domain_shells[dn])) == len(domain_shells[dn]):
fW.write("*SOLID SECTION, ELSET=" + dn + str(sn) + ", MATERIAL=" + dn + str(sn))
add_orientation()
fW.write(str(domain_thickness[dn][sn]) + "\n")
elif plane_stress.intersection(domain_shells[dn]):
msg_error = dn + " domain does not contain only plane stress types for 2D elements"
elif len(axisymmetry.intersection(domain_shells[dn])) == len(domain_shells[dn]):
fW.write("*SOLID SECTION, ELSET=" + dn + str(sn) + ", MATERIAL=" + dn + str(sn))
add_orientation()
elif axisymmetry.intersection(domain_shells[dn]):
msg_error = dn + " domain does not contain only axisymmetry types for 2D elements"
elif shells_as_composite is True:
fW.write("*SHELL SECTION, ELSET=" + dn + str(sn) + ", OFFSET=" + str(domain_offset[dn]) +
", COMPOSITE")
add_orientation()
# 0.1 + 0.8 + 0.1 of thickness, , material name
fW.write(str(0.1 * domain_thickness[dn][sn]) + ",," + dn + str(sn) + "\n")
fW.write(str(0.8 * domain_thickness[dn][sn]) + ",," + dn + str(sn) + "\n")
fW.write(str(0.1 * domain_thickness[dn][sn]) + ",," + dn + str(sn) + "\n")
else:
fW.write("*SHELL SECTION, ELSET=" + dn + str(sn) + ", MATERIAL=" + dn + str(sn) +
", OFFSET=" + str(domain_offset[dn]))
add_orientation()
fW.write(str(domain_thickness[dn][sn]) + "\n")
fW.write(" \n")
if msg_error:
write_to_log(file_name, "\nERROR: " + msg_error + "\n")
raise Exception(msg_error)
sections_done = 1
if line[:5].upper() == "*STEP":
outputs_done -= 1
# output request only for element stresses in .dat file:
if line[0:10].upper() == "*NODE FILE" or line[0:8].upper() == "*EL FILE" or \
line[0:13].upper() == "*CONTACT FILE" or line[0:11].upper() == "*NODE PRINT" or \
line[0:9].upper() == "*EL PRINT" or line[0:14].upper() == "*CONTACT PRINT":
if outputs_done < 1:
fW.write(" \n")
if optimization_base in ["stiffness", "buckling"]:
for dn in domains_from_config:
fW.write("*EL PRINT, " + "ELSET=" + dn + "\n")
fW.write("ENER\n")
if optimization_base == "heat":
for dn in domains_from_config:
fW.write("*EL PRINT, " + "ELSET=" + dn + ", FREQUENCY=1000" + "\n")
fW.write("HFL\n")
if (reference_points == "integration points") and (domain_FI_filled is True):
for dn in domains_from_config:
fW.write("*EL PRINT, " + "ELSET=" + dn + "\n")
fW.write("S\n")
elif reference_points == "nodes":
fW.write("*EL FILE, GLOBAL=NO\n")
fW.write("S\n")
if displacement_graph:
ns_written = []
for [ns, component] in displacement_graph:
if ns not in ns_written:
ns_written.append(ns)
fW.write("*NODE PRINT, NSET=" + ns + "\n")
fW.write("U\n")
fW.write(" \n")
outputs_done += 1
commenting = True
if not save_iteration_results or np.mod(float(i - 1), save_iteration_results) != 0:
continue
elif commenting is True:
if not save_iteration_results or np.mod(float(i - 1), save_iteration_results) != 0:
continue
fW.write(line)
fR.close()
fW.close()
if check_line_endings:
fW = open(file_nameW + ".inp", "rb")
content = fW.read().replace("\r\n", "\n")
fW.close()
fW = open(file_nameW + ".inp", "wb")
fW.write(content)
fW.close()
# function for importing results from .dat file
# Failure Indices are computed at each integration point and maximum or average above each element is returned
def import_FI_int_pt(reference_value, file_nameW, domains, criteria, domain_FI, file_name, elm_states,
domains_from_config, steps_superposition, displacement_graph):
try:
f = open(file_nameW + ".dat", "r")
except IOError:
msg = "CalculiX result file not found, check your inputs"
write_to_log(file_name, "\nERROR: " + msg + "\n")
assert False, msg
last_time = "initial" # TODO solve how to read a new step which differs in time
step_number = -1
criteria_elm = {} # {en1: numbers of applied criteria, en2: [], ...}
FI_step = [] # list for steps - [{en1: list for criteria FI, en2: [], ...}, {en1: [], en2: [], ...}, next step]
energy_density_step = [] # list for steps - [{en1: energy_density, en2: ..., ...}, {en1: ..., ...}, next step]
energy_density_eigen = {} # energy_density_eigen[eigen_number][en_last] = np.average(ener_int_pt)
heat_flux = {} # only for the last step
memorized_steps = set() # steps to use in superposition
if steps_superposition:
step_stress = {} # {sn: {en: [sxx, syy, szz, sxy, sxz, syz], next element with int. pt. stresses}, next step, ...}
step_ener = {} # energy density {sn: {en: ener, next element with int. pt. stresses}, next step, ...}
for LCn in range(len(steps_superposition)):
for (scale, sn) in steps_superposition[LCn]:
sn -= 1 # step numbering in CalculiX is from 1, but we have it 0 based
memorized_steps.add(sn)
step_stress[sn] = {}
step_ener[sn] = {}
# prepare FI dict from failure criteria
for dn in domain_FI:
if domain_FI[dn]:
for en in domains[dn]:
cr = []
for dn_crit in domain_FI[dn][elm_states[en]]:
cr.append(criteria.index(dn_crit))
criteria_elm[en] = cr
def compute_FI(): # for the actual integration point
if en in criteria_elm:
for FIn in criteria_elm[en]:
if criteria[FIn][0] == "stress_von_Mises":
s_allowable = criteria[FIn][1]
FI_int_pt[FIn].append(np.sqrt(0.5 * ((sxx - syy) ** 2 + (syy - szz) ** 2 + (szz - sxx) ** 2 +
6 * (sxy ** 2 + syz ** 2 + sxz ** 2))) / s_allowable)
elif criteria[FIn][0] == "user_def":
FI_int_pt[FIn].append(eval(criteria[FIn][1]))
else:
msg = "\nError: failure criterion " + str(criteria[FIn]) + " not recognised.\n"
write_to_log(file_name, msg)
def save_FI(sn, en):
FI_step[sn][en] = []
for FIn in range(len(criteria)):
FI_step[sn][en].append(None)
if FIn in criteria_elm[en]:
if reference_value == "max":
FI_step[sn][en][FIn] = max(FI_int_pt[FIn])
elif reference_value == "average":
FI_step[sn][en][FIn] = np.average(FI_int_pt[FIn])
read_stresses = 0
read_energy_density = 0
read_heat_flux = 0
read_displacement = 0
disp_i = [None for _ in range(len(displacement_graph))]
disp_condition = {}
disp_components = []
read_buckling_factors = 0
buckling_factors = []
read_eigenvalues = 0
for line in f:
line_split = line.split()
if line.replace(" ", "") == "\n":
if read_stresses == 1:
save_FI(step_number, en_last)
if read_energy_density == 1:
if read_eigenvalues:
energy_density_eigen[eigen_number][en_last] = np.average(ener_int_pt)
else:
energy_density_step[step_number][en_last] = np.average(ener_int_pt)
if read_heat_flux == 1:
heat_flux[en_last] = np.average(heat_int_pt)
if read_displacement == 1:
for cn in ns_reading:
try:
disp_i[cn] = max([disp_i[cn]] + disp_condition[cn])
except TypeError:
disp_i[cn] = max(disp_condition[cn])
read_stresses -= 1
read_energy_density -= 1
read_heat_flux -= 1
read_displacement -= 1
read_buckling_factors -= 1
FI_int_pt = [[] for _ in range(len(criteria))]
ener_int_pt = []
heat_int_pt = []
en_last = None
elif line[:9] == " stresses":
if line.split()[-4] in map(lambda x: x.upper(), domains_from_config): # TODO upper already on user input
read_stresses = 2
if last_time != line_split[-1]:
step_number += 1
FI_step.append({})
energy_density_step.append({})
if steps_superposition:
disp_components.append({}) # appending sn
last_time = line_split[-1]
read_eigenvalues = False # TODO not for frequencies?
elif line[:24] == " internal energy density":
if line.split()[-4] in map(lambda x: x.upper(), domains_from_config): # TODO upper already on user input
read_energy_density = 2
if last_time != line_split[-1]:
step_number += 1
FI_step.append({})
energy_density_step.append({})
if steps_superposition:
disp_components.append({}) # appending sn
last_time = line_split[-1]
read_eigenvalues = False # TODO not for frequencies?
elif line[:10] == " heat flux":
if line.split()[-4] in map(lambda x: x.upper(), domains_from_config): # TODO upper already on user input
read_heat_flux = 2
elif line[:48] == " B U C K L I N G F A C T O R O U T P U T":
read_buckling_factors = 3
elif read_buckling_factors == 1:
buckling_factors.append(float(line_split[1]))
elif line[:54] == " E I G E N V A L U E N U M B E R":
eigen_number = int(line_split[-1])
read_eigenvalues = True
energy_density_eigen[eigen_number] = {}
elif line[:14] == " displacements":
cn = 0
ns_reading = []
for [ns, component] in displacement_graph:
if ns.upper() == line_split[4]:
ns_reading.append(cn)
disp_condition[cn] = []
cn += 1
read_displacement = 2
if steps_superposition:
if last_time != line_split[-1]:
step_number += 1
disp_components.append({}) # appending sn
FI_step.append({})
energy_density_step.append({})
last_time = line_split[-1]
ns = line_split[4]
disp_components[-1][ns] = [] # appending ns
elif read_stresses == 1:
en = int(line_split[0])
if en_last != en:
if en_last:
save_FI(step_number, en_last)
FI_int_pt = [[] for _ in range(len(criteria))]
en_last = en
sxx = float(line_split[2])
syy = float(line_split[3])
szz = float(line_split[4])
sxy = float(line_split[5])
sxz = float(line_split[6])
syz = float(line_split[7])
syx = sxy
szx = sxz
szy = syz
compute_FI()
if step_number in memorized_steps:
try:
step_stress[step_number][en]
except KeyError:
step_stress[step_number][en] = []
step_stress[step_number][en].append([sxx, syy, szz, sxy, sxz, syz])
elif read_energy_density == 1:
en = int(line_split[0])
if en_last != en:
if en_last:
if read_eigenvalues:
energy_density_eigen[eigen_number][en_last] = np.average(ener_int_pt)
else:
energy_density_step[step_number][en_last] = np.average(ener_int_pt)
ener_int_pt = []
en_last = en
energy_density = float(line_split[2])
ener_int_pt.append(energy_density)
if step_number in memorized_steps:
try:
step_ener[step_number][en]
except KeyError:
step_ener[step_number][en] = []
step_ener[step_number][en].append(energy_density)
elif read_heat_flux == 1:
en = int(line_split[0])
if en_last != en:
if en_last:
heat_flux[en_last] = np.average(heat_int_pt)
heat_int_pt = []
en_last = en
heat_flux_total = np.sqrt(float(line_split[2]) ** 2 + float(line_split[3]) ** 2 + float(line_split[4]) ** 2)
heat_int_pt.append(heat_flux_total)
elif read_displacement == 1:
ux = float(line_split[1])
uy = float(line_split[2])
uz = float(line_split[3])
for cn in ns_reading:
component = displacement_graph[cn][1]
if component.upper() == "TOTAL": # total displacement
disp_condition[cn].append(sqrt(ux ** 2 + uy ** 2 + uz ** 2))
else:
disp_condition[cn].append(eval(component))
if steps_superposition: # save ux, uy, uz for steps superposition
disp_components[step_number][ns].append((ux, uy, uz))
if read_stresses == 1:
save_FI(step_number, en_last)
if read_energy_density == 1:
if read_eigenvalues:
energy_density_eigen[eigen_number][en_last] = np.average(ener_int_pt)
else:
energy_density_step[step_number][en_last] = np.average(ener_int_pt)
if read_heat_flux == 1:
heat_flux[en_last] = np.average(heat_int_pt)
if read_displacement == 1:
for cn in ns_reading:
try:
disp_i[cn] = max([disp_i[cn]] + disp_condition[cn])
except TypeError:
disp_i[cn] = max(disp_condition[cn])
f.close()
# superposed steps
# step_stress = {sn: {en: [[sxx, syy, szz, sxy, sxz, syz], next integration point], next element with int. pt. stresses}, next step, ...}
# steps_superposition = [[(sn, scale), next scaled step to add, ...], next superposed step]
for LCn in range(len(steps_superposition)):
FI_step.append({})
energy_density_step.append({})
# sum scaled stress components at each integration point
superposition_stress = {}
superposition_energy_density = {}
for (scale, sn) in steps_superposition[LCn]:
sn -= 1 # step numbering in CalculiX is from 1, but we have it 0 based
# with stresses
for en in step_stress[sn]:
try:
superposition_stress[en]
except KeyError:
superposition_stress[en] = [] # list of integration points
for ip in range(len(step_stress[sn][en])):
try:
superposition_stress[en][ip]
except IndexError:
superposition_stress[en].append([0, 0, 0, 0, 0, 0]) # components of stress
for component in range(6):
superposition_stress[en][ip][component] += scale * step_stress[sn][en][ip][component]
# again with energy density
for en in step_ener[sn]:
try:
superposition_energy_density[en]
except KeyError:
superposition_energy_density[en] = [] # list of integration points
for ip in range(len(step_ener[sn][en])):
try:
superposition_energy_density[en][ip]
except IndexError:
superposition_energy_density[en].append(0) # components of stress
for component in range(6):
superposition_energy_density[en][ip] += scale * step_ener[sn][en][ip]
# compute FI in each element at superposed step
for en in superposition_stress:
FI_int_pt = [[] for _ in range(len(criteria))]
for ip in range(len(superposition_stress[en])):
sxx = superposition_stress[en][ip][0]
syy = superposition_stress[en][ip][1]
szz = superposition_stress[en][ip][2]
sxy = superposition_stress[en][ip][3]
sxz = superposition_stress[en][ip][4]
syz = superposition_stress[en][ip][5]
syx = sxy
szx = sxz
szy = syz
compute_FI() # fill FI_int_pt
sn = -1 # last step number
save_FI(sn, en) # save value to FI_step for given en
# compute average energy density over integration point at superposed step
for en in superposition_energy_density:
ener_int_pt = []
for ip in range(len(superposition_energy_density[en])):
ener_int_pt.append(superposition_energy_density[en][ip])
sn = -1 # last step number
energy_density_step[sn][en] = np.average(ener_int_pt)
# superposition of displacements to graph, same code block as in import_displacement function
cn = 0
for (ns, component) in displacement_graph:
ns = ns.upper()
uxe = []
uye = []
uze = []
for en2 in range(len(disp_components[0][ns])):
uxe.append(0)
uye.append(0)
uze.append(0)
for (scale, sn) in steps_superposition[LCn]:
sn -= 1 # step numbering in CalculiX is from 1, but we have it 0 based
uxe[-1] += scale * disp_components[sn][ns][en2][0]
uye[-1] += scale * disp_components[sn][ns][en2][1]
uze[-1] += scale * disp_components[sn][ns][en2][2]
for en2 in range(len(uxe)): # iterate over elements in nset
ux = uxe.pop()
uy = uye.pop()
uz = uze.pop()
if component.upper() == "TOTAL": # total displacement
disp_condition[cn].append(sqrt(ux ** 2 + uy ** 2 + uz ** 2))
else:
disp_condition[cn].append(eval(component))
try:
disp_i[cn] = max([disp_i[cn]] + disp_condition[cn])
except TypeError:
disp_i[cn] = max(disp_condition[cn])
cn += 1
return FI_step, energy_density_step, disp_i, buckling_factors, energy_density_eigen, heat_flux
# function for importing displacements if import_FI_int_pt is not called to read .dat file
def import_displacement(file_nameW, displacement_graph, steps_superposition):
f = open(file_nameW + ".dat", "r")
read_displacement = 0
disp_i = [None for _ in range(len(displacement_graph))]
disp_condition = {}
disp_components = []
last_time = "initial"
step_number = -1
for line in f:
line_split = line.split()
if line.replace(" ", "") == "\n":
if read_displacement == 1:
for cn in ns_reading:
try:
disp_i[cn] = max([disp_i[cn]] + disp_condition[cn])
except TypeError:
disp_i[cn] = max(disp_condition[cn])
read_displacement -= 1
elif line[:14] == " displacements":
cn = 0
ns_reading = []
for [ns, component] in displacement_graph:
if ns.upper() == line_split[4]:
ns_reading.append(cn)
disp_condition[cn] = []
cn += 1
read_displacement = 2
if steps_superposition:
if last_time != line_split[-1]:
step_number += 1
disp_components.append({}) # appending sn
last_time = line_split[-1]
ns = line_split[4]
disp_components[-1][ns] = [] # appending ns
elif read_displacement == 1:
ux = float(line_split[1])